public void parse(File file, int maxPaths, ProgressMonitor monitor) throws Exception {
    monitor.beginTask(tr("Parsing PDF", 1));

    PDDocument document = PDDocument.load(file);

    if (document.isEncrypted()) {
      throw new Exception(tr("Encrypted documents not supported."));
    }

    List<?> allPages = document.getDocumentCatalog().getAllPages();

    if (allPages.size() != 1) {
      throw new Exception(tr("The PDF file must have exactly one page."));
    }

    PDPage page = (PDPage) allPages.get(0);
    PDRectangle pageSize = page.findMediaBox();
    Integer rotationVal = page.getRotation();
    int rotation = 0;
    if (rotationVal != null) {
      rotation = rotationVal.intValue();
    }

    GraphicsProcessor p = new GraphicsProcessor(target, rotation, maxPaths, monitor);
    PageDrawer drawer = new PageDrawer();
    drawer.drawPage(p, page);
    this.target.bounds =
        new Rectangle2D.Double(
            pageSize.getLowerLeftX(),
            pageSize.getLowerLeftY(),
            pageSize.getWidth(),
            pageSize.getHeight());

    monitor.finishTask();
  }
 @Override
 public GpxData parseRawGps(ProgressMonitor progressMonitor) throws OsmTransferException {
   progressMonitor.beginTask("", 1);
   try {
     progressMonitor.indeterminateSubTask(getTaskName());
     if (crosses180th) {
       // API 0.6 does not support requests crossing the 180th meridian, so make two requests
       GpxData result = downloadRawGps(new Bounds(lat1, lon1, lat2, 180.0), progressMonitor);
       result.mergeFrom(downloadRawGps(new Bounds(lat1, -180.0, lat2, lon2), progressMonitor));
       return result;
     } else {
       // Simple request
       return downloadRawGps(new Bounds(lat1, lon1, lat2, lon2), progressMonitor);
     }
   } catch (IllegalArgumentException e) {
     // caused by HttpUrlConnection in case of illegal stuff in the response
     if (cancel) return null;
     throw new OsmTransferException("Illegal characters within the HTTP-header response.", e);
   } catch (IOException e) {
     if (cancel) return null;
     throw new OsmTransferException(e);
   } catch (SAXException e) {
     throw new OsmTransferException(e);
   } catch (OsmTransferException e) {
     throw e;
   } catch (RuntimeException e) {
     if (cancel) return null;
     throw e;
   } finally {
     progressMonitor.finishTask();
   }
 }
Example #3
0
 private GpxData downloadRawGps(String url, ProgressMonitor progressMonitor)
     throws IOException, OsmTransferException, SAXException {
   boolean done = false;
   GpxData result = null;
   for (int i = 0; !done; ++i) {
     progressMonitor.subTask(tr("Downloading points {0} to {1}...", i * 5000, ((i + 1) * 5000)));
     InputStream in = getInputStream(url + i, progressMonitor.createSubTaskMonitor(1, true));
     if (in == null) {
       break;
     }
     progressMonitor.setTicks(0);
     GpxReader reader = new GpxReader(in);
     gpxParsedProperly = reader.parse(false);
     GpxData currentGpx = reader.data;
     if (result == null) {
       result = currentGpx;
     } else if (currentGpx.hasTrackPoints()) {
       result.mergeFrom(currentGpx);
     } else {
       done = true;
     }
     in.close();
     activeConnection = null;
   }
   result.fromServer = true;
   return result;
 }
Example #4
0
 /**
  * Visits all primitives to be tested. These primitives are always visited in the same order:
  * nodes first, then ways.
  *
  * @param selection The primitives to be tested
  */
 public void visit(Collection<OsmPrimitive> selection) {
   progressMonitor.setTicksCount(selection.size());
   for (OsmPrimitive p : selection) {
     if (p.isUsable()) {
       p.visit(this);
     }
     progressMonitor.worked(1);
   }
 }
Example #5
0
    @Override
    protected void realRun() {
      try {
        foundMatches = 0;
        SearchCompiler.Match matcher = SearchCompiler.compile(setting);

        if (setting.mode == SearchMode.replace) {
          selection.clear();
        } else if (setting.mode == SearchMode.in_selection) {
          foundMatches = selection.size();
        }

        Collection<OsmPrimitive> all;
        if (setting.allElements) {
          all = ds.allPrimitives();
        } else {
          all = ds.getPrimitives(OsmPrimitive::isSelectable);
        }
        final ProgressMonitor subMonitor =
            getProgressMonitor().createSubTaskMonitor(all.size(), false);
        subMonitor.beginTask(
            trn("Searching in {0} object", "Searching in {0} objects", all.size(), all.size()));

        for (OsmPrimitive osm : all) {
          if (canceled) {
            return;
          }
          if (setting.mode == SearchMode.replace) {
            if (matcher.match(osm)) {
              selection.add(osm);
              ++foundMatches;
            }
          } else if (setting.mode == SearchMode.add && !predicate.test(osm) && matcher.match(osm)) {
            selection.add(osm);
            ++foundMatches;
          } else if (setting.mode == SearchMode.remove
              && predicate.test(osm)
              && matcher.match(osm)) {
            selection.remove(osm);
            ++foundMatches;
          } else if (setting.mode == SearchMode.in_selection
              && predicate.test(osm)
              && !matcher.match(osm)) {
            selection.remove(osm);
            --foundMatches;
          }
          subMonitor.worked(1);
        }
        subMonitor.finishTask();
      } catch (ParseError e) {
        Main.debug(e);
        JOptionPane.showMessageDialog(
            Main.parent, e.getMessage(), tr("Error"), JOptionPane.ERROR_MESSAGE);
      }
    }
  private OsmDataLayer makeLayer(
      String name, FilePlacement placement, OsmBuilder.Mode mode, ProgressMonitor monitor) {
    monitor.beginTask(tr("Building JOSM layer"), 100);
    OsmBuilder builder = new OsmBuilder(placement);
    DataSet data =
        builder.build(this.data.getLayers(), mode, monitor.createSubTaskMonitor(50, false));
    monitor.setTicks(50);
    monitor.setCustomText(tr("Postprocessing layer"));
    OsmDataLayer result = new OsmDataLayer(data, name, null);
    result.onPostLoadFromFile();

    monitor.finishTask();
    return result;
  }
Example #7
0
 /**
  * Retries to recover the upload operation from an exception which was thrown because an uploaded
  * primitive was already deleted on the server.
  *
  * @param e the exception throw by the API
  * @param monitor a progress monitor
  * @throws OsmTransferException thrown if we can't recover from the exception
  */
 protected void recoverFromGoneOnServer(OsmApiPrimitiveGoneException e, ProgressMonitor monitor)
     throws OsmTransferException {
   if (!e.isKnownPrimitive()) throw e;
   OsmPrimitive p = layer.data.getPrimitiveById(e.getPrimitiveId(), e.getPrimitiveType());
   if (p == null) throw e;
   if (p.isDeleted()) {
     // we tried to delete an already deleted primitive.
     //
     System.out.println(
         tr(
             "Warning: object ''{0}'' is already deleted on the server. Skipping this object and retrying to upload.",
             p.getDisplayName(DefaultNameFormatter.getInstance())));
     monitor.appendLogMessage(
         tr(
             "Object ''{0}'' is already deleted. Skipping object in upload.",
             p.getDisplayName(DefaultNameFormatter.getInstance())));
     processedPrimitives.addAll(writer.getProcessedPrimitives());
     processedPrimitives.add(p);
     toUpload.removeProcessed(processedPrimitives);
     return;
   }
   // exception was thrown because we tried to *update* an already deleted
   // primitive. We can't resolve this automatically. Re-throw exception,
   // a conflict is going to be created later.
   throw e;
 }
 /**
  * Retries to recover the upload operation from an exception which was thrown because an uploaded
  * primitive was already deleted on the server.
  *
  * @param e the exception throw by the API
  * @param monitor a progress monitor
  * @throws OsmTransferException if we can't recover from the exception
  */
 protected void recoverFromGoneOnServer(OsmApiPrimitiveGoneException e, ProgressMonitor monitor)
     throws OsmTransferException {
   if (!e.isKnownPrimitive()) throw e;
   OsmPrimitive p = layer.data.getPrimitiveById(e.getPrimitiveId(), e.getPrimitiveType());
   if (p == null) throw e;
   if (p.isDeleted()) {
     // we tried to delete an already deleted primitive.
     final String msg;
     final String displayName = p.getDisplayName(DefaultNameFormatter.getInstance());
     if (p instanceof Node) {
       msg = tr("Node ''{0}'' is already deleted. Skipping object in upload.", displayName);
     } else if (p instanceof Way) {
       msg = tr("Way ''{0}'' is already deleted. Skipping object in upload.", displayName);
     } else if (p instanceof Relation) {
       msg = tr("Relation ''{0}'' is already deleted. Skipping object in upload.", displayName);
     } else {
       msg = tr("Object ''{0}'' is already deleted. Skipping object in upload.", displayName);
     }
     monitor.appendLogMessage(msg);
     Main.warn(msg);
     processedPrimitives.addAll(writer.getProcessedPrimitives());
     processedPrimitives.add(p);
     toUpload.removeProcessed(processedPrimitives);
     return;
   }
   // exception was thrown because we tried to *update* an already deleted
   // primitive. We can't resolve this automatically. Re-throw exception,
   // a conflict is going to be created later.
   throw e;
 }
  /**
   * Parse the given input source and return the dataset.
   *
   * @param source the source input stream. Must not be null.
   * @param progressMonitor the progress monitor. If null, {@see NullProgressMonitor#INSTANCE} is
   *     assumed
   * @return the dataset with the parsed data
   * @throws IllegalDataException thrown if the an error was found while parsing the data from the
   *     source
   * @throws IllegalArgumentException thrown if source is null
   */
  public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor)
      throws IllegalDataException {
    ProgressMonitor monitor =
        progressMonitor == null ? NullProgressMonitor.INSTANCE : progressMonitor;
    CheckParameterUtil.ensureParameterNotNull(source, "source");

    PbfReader reader = new PbfReader();

    try {
      monitor.beginTask(tr("Prepare OSM data...", 2));
      monitor.indeterminateSubTask(tr("Reading OSM data..."));

      reader.parse(source);
      monitor.worked(1);

      monitor.indeterminateSubTask(tr("Preparing data set..."));
      reader.prepareDataSet();
      monitor.worked(1);
      return reader.getDataSet();
    } catch (IllegalDataException e) {
      throw e;
    } catch (Exception e) {
      throw new IllegalDataException(e);
    } finally {
      monitor.finishTask();
    }
  }
Example #10
0
  /**
   * Read the data from the osm server address.
   *
   * @return A data set containing all data retrieved from that url
   */
  @Override
  public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
    progressMonitor.beginTask(tr("Contacting OSM Server..."), 10);
    InputStream in = null;
    try {
      DataSet ds = null;
      progressMonitor.indeterminateSubTask(null);
      if (crosses180th) {
        // API 0.6 does not support requests crossing the 180th meridian, so make two requests
        in =
            getInputStream(
                getRequestForBbox(lon1, lat1, 180.0, lat2),
                progressMonitor.createSubTaskMonitor(9, false));
        if (in == null) return null;
        ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));

        in =
            getInputStream(
                getRequestForBbox(-180.0, lat1, lon2, lat2),
                progressMonitor.createSubTaskMonitor(9, false));
        if (in == null) return null;
        DataSet ds2 = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
        if (ds2 == null) return null;
        ds.mergeFrom(ds2);

      } else {
        // Simple request
        in =
            getInputStream(
                getRequestForBbox(lon1, lat1, lon2, lat2),
                progressMonitor.createSubTaskMonitor(9, false));
        if (in == null) return null;
        ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
      }
      return ds;
    } catch (OsmTransferException e) {
      throw e;
    } catch (Exception e) {
      throw new OsmTransferException(e);
    } finally {
      progressMonitor.finishTask();
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
      activeConnection = null;
    }
  }
Example #11
0
 /**
  * Open a connection to the given url and return a reader on the input stream from that
  * connection. In case of user cancel, return <code>null</code>. Relative URL's are directed to
  * API base URL.
  *
  * @param urlStr The url to connect to.
  * @param progressMonitor progress monitoring and abort handler
  * @return An reader reading the input stream (servers answer) or <code>null</code>.
  * @throws OsmTransferException thrown if data transfer errors occur
  */
 protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor)
     throws OsmTransferException {
   try {
     api.initialize(progressMonitor);
     urlStr = urlStr.startsWith("http") ? urlStr : (getBaseUrl() + urlStr);
     return getInputStreamRaw(urlStr, progressMonitor);
   } finally {
     progressMonitor.invalidate();
   }
 }
Example #12
0
    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;
      }
    }
  private void infoSync(LatLon pos, ProgressMonitor progressMonitor) {

    progressMonitor.beginTask(null, 3);
    try {
      mRuian.prepareData(pos);
      htmlText = mRuian.getHtml();
      coordinatesText = PointInfoUtils.formatCoordinates(pos.lat(), pos.lon());

    } finally {
      progressMonitor.finishTask();
    }
    progressMonitor.invalidate();
    if (htmlText.length() == 0) {
      GuiHelper.runInEDTAndWait(
          () ->
              PointInfoUtils.showNotification(
                  tr("Data not available.") + "\n(" + pos.toDisplayString() + ")", "warning"));
      return;
    }
  }
 private GpxData downloadRawGps(Bounds b, ProgressMonitor progressMonitor)
     throws IOException, OsmTransferException, SAXException {
   boolean done = false;
   GpxData result = null;
   String url =
       "trackpoints?bbox="
           + b.getMinLon()
           + ','
           + b.getMinLat()
           + ','
           + b.getMaxLon()
           + ','
           + b.getMaxLat()
           + "&page=";
   for (int i = 0; !done; ++i) {
     progressMonitor.subTask(tr("Downloading points {0} to {1}...", i * 5000, (i + 1) * 5000));
     try (InputStream in =
         getInputStream(url + i, progressMonitor.createSubTaskMonitor(1, true))) {
       if (in == null) {
         break;
       }
       progressMonitor.setTicks(0);
       GpxReader reader = new GpxReader(in);
       gpxParsedProperly = reader.parse(false);
       GpxData currentGpx = reader.getGpxData();
       if (result == null) {
         result = currentGpx;
       } else if (currentGpx.hasTrackPoints()) {
         result.mergeFrom(currentGpx);
       } else {
         done = true;
       }
     }
     activeConnection = null;
   }
   if (result != null) {
     result.fromServer = true;
     result.dataSources.add(new DataSource(b, "OpenStreetMap server"));
   }
   return result;
 }
 @Override
 public List<Note> parseNotes(int noteLimit, int daysClosed, ProgressMonitor progressMonitor)
     throws OsmTransferException, MoreNotesException {
   progressMonitor.beginTask("Downloading notes");
   CheckParameterUtil.ensureThat(noteLimit > 0, "Requested note limit is less than 1.");
   // see result_limit in
   // https://github.com/openstreetmap/openstreetmap-website/blob/master/app/controllers/notes_controller.rb
   CheckParameterUtil.ensureThat(
       noteLimit <= 10000, "Requested note limit is over API hard limit of 10000.");
   CheckParameterUtil.ensureThat(daysClosed >= -1, "Requested note limit is less than -1.");
   String url =
       "notes?limit="
           + noteLimit
           + "&closed="
           + daysClosed
           + "&bbox="
           + lon1
           + ','
           + lat1
           + ','
           + lon2
           + ','
           + lat2;
   try {
     InputStream is = getInputStream(url, progressMonitor.createSubTaskMonitor(1, false));
     NoteReader reader = new NoteReader(is);
     final List<Note> notes = reader.parse();
     if (notes.size() == noteLimit) {
       throw new MoreNotesException(notes, noteLimit);
     }
     return notes;
   } catch (IOException e) {
     throw new OsmTransferException(e);
   } catch (SAXException e) {
     throw new OsmTransferException(e);
   } finally {
     progressMonitor.finishTask();
   }
 }
  private void saveLayer(java.io.File file, FilePlacement placement, ProgressMonitor monitor) {
    monitor.beginTask(tr("Saving to file."), 1000);

    OsmBuilder builder = new OsmBuilder(placement);
    DataSet data =
        builder.build(
            this.data.getLayers(), OsmBuilder.Mode.Final, monitor.createSubTaskMonitor(500, false));
    OsmDataLayer layer = new OsmDataLayer(data, file.getName(), file);

    monitor.setCustomText(tr(" Writing to file"));
    monitor.setTicks(500);

    OsmExporter exporter = new OsmExporter();

    try {
      exporter.exportData(file, layer);
    } catch (IOException e) {
      // TODO:
    }

    monitor.finishTask();
  }
Example #17
0
  protected DataSet doParseDataSet(InputStream source, ProgressMonitor progressMonitor)
      throws IllegalDataException {
    if (progressMonitor == null) {
      progressMonitor = NullProgressMonitor.INSTANCE;
    }
    CheckParameterUtil.ensureParameterNotNull(source, "source");
    try {
      progressMonitor.beginTask(tr("Prepare OSM data...", 2));
      progressMonitor.indeterminateSubTask(tr("Parsing OSM data..."));

      InputStreamReader ir = UTFInputStreamReader.create(source, "UTF-8");
      XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
      setParser(parser);
      parse();
      progressMonitor.worked(1);

      progressMonitor.indeterminateSubTask(tr("Preparing data set..."));
      prepareDataSet();
      progressMonitor.worked(1);

      // iterate over registered postprocessors and give them each a chance
      // to modify the dataset we have just loaded.
      if (postprocessors != null) {
        for (OsmServerReadPostprocessor pp : postprocessors) {
          pp.postprocessDataSet(getDataSet(), progressMonitor);
        }
      }
      return getDataSet();
    } catch (IllegalDataException e) {
      throw e;
    } catch (OsmParsingException e) {
      throw new IllegalDataException(e.getMessage(), e);
    } catch (XMLStreamException e) {
      String msg = e.getMessage();
      Pattern p = Pattern.compile("Message: (.+)");
      Matcher m = p.matcher(msg);
      if (m.find()) {
        msg = m.group(1);
      }
      if (e.getLocation() != null)
        throw new IllegalDataException(
            tr(
                    "Line {0} column {1}: ",
                    e.getLocation().getLineNumber(), e.getLocation().getColumnNumber())
                + msg,
            e);
      else throw new IllegalDataException(msg, e);
    } catch (Exception e) {
      throw new IllegalDataException(e);
    } finally {
      progressMonitor.finishTask();
    }
  }
Example #18
0
  private void parseJos(Document doc, ProgressMonitor progressMonitor) throws IllegalDataException {
    Element root = doc.getDocumentElement();
    if (!equal(root.getTagName(), "josm-session")) {
      error(tr("Unexpected root element ''{0}'' in session file", root.getTagName()));
    }
    String version = root.getAttribute("version");
    if (!"0.1".equals(version)) {
      error(tr("Version ''{0}'' of session file is not supported. Expected: 0.1", version));
    }

    Element viewportEl = getElementByTagName(root, "viewport");
    if (viewportEl != null) {
      EastNorth center = null;
      Element centerEl = getElementByTagName(viewportEl, "center");
      if (centerEl != null && centerEl.hasAttribute("lat") && centerEl.hasAttribute("lon")) {
        try {
          LatLon centerLL =
              new LatLon(
                  Double.parseDouble(centerEl.getAttribute("lat")),
                  Double.parseDouble(centerEl.getAttribute("lon")));
          center = Projections.project(centerLL);
        } catch (NumberFormatException ex) {
        }
      }
      if (center != null) {
        Element scaleEl = getElementByTagName(viewportEl, "scale");
        if (scaleEl != null && scaleEl.hasAttribute("meter-per-pixel")) {
          try {
            double meterPerPixel = Double.parseDouble(scaleEl.getAttribute("meter-per-pixel"));
            Projection proj = Main.getProjection();
            // Get a "typical" distance in east/north units that
            // corresponds to a couple of pixels. Shouldn't be too
            // large, to keep it within projection bounds and
            // not too small to avoid rounding errors.
            double dist = 0.01 * proj.getDefaultZoomInPPD();
            LatLon ll1 = proj.eastNorth2latlon(new EastNorth(center.east() - dist, center.north()));
            LatLon ll2 = proj.eastNorth2latlon(new EastNorth(center.east() + dist, center.north()));
            double meterPerEasting = ll1.greatCircleDistance(ll2) / dist / 2;
            double scale = meterPerPixel / meterPerEasting; // unit: easting per pixel
            viewport = new ViewportData(center, scale);
          } catch (NumberFormatException ex) {
          }
        }
      }
    }

    Element layersEl = getElementByTagName(root, "layers");
    if (layersEl == null) return;

    String activeAtt = layersEl.getAttribute("active");
    try {
      active = (activeAtt != null && !activeAtt.isEmpty()) ? Integer.parseInt(activeAtt) - 1 : -1;
    } catch (NumberFormatException e) {
      Main.warn(
          "Unsupported value for 'active' layer attribute. Ignoring it. Error was: "
              + e.getMessage());
      active = -1;
    }

    MultiMap<Integer, Integer> deps = new MultiMap<Integer, Integer>();
    Map<Integer, Element> elems = new HashMap<Integer, Element>();

    NodeList nodes = layersEl.getChildNodes();

    for (int i = 0; i < nodes.getLength(); ++i) {
      Node node = nodes.item(i);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element e = (Element) node;
        if (equal(e.getTagName(), "layer")) {

          if (!e.hasAttribute("index")) {
            error(tr("missing mandatory attribute ''index'' for element ''layer''"));
          }
          Integer idx = null;
          try {
            idx = Integer.parseInt(e.getAttribute("index"));
          } catch (NumberFormatException ex) {
          }
          if (idx == null) {
            error(tr("unexpected format of attribute ''index'' for element ''layer''"));
          }
          if (elems.containsKey(idx)) {
            error(
                tr(
                    "attribute ''index'' ({0}) for element ''layer'' must be unique",
                    Integer.toString(idx)));
          }
          elems.put(idx, e);

          deps.putVoid(idx);
          String depStr = e.getAttribute("depends");
          if (depStr != null) {
            for (String sd : depStr.split(",")) {
              Integer d = null;
              try {
                d = Integer.parseInt(sd);
              } catch (NumberFormatException ex) {
                Main.warn(ex);
              }
              if (d != null) {
                deps.put(idx, d);
              }
            }
          }
        }
      }
    }

    List<Integer> sorted = Utils.topologicalSort(deps);
    final Map<Integer, Layer> layersMap = new TreeMap<Integer, Layer>(Collections.reverseOrder());
    final Map<Integer, SessionLayerImporter> importers =
        new HashMap<Integer, SessionLayerImporter>();
    final Map<Integer, String> names = new HashMap<Integer, String>();

    progressMonitor.setTicksCount(sorted.size());
    LAYER:
    for (int idx : sorted) {
      Element e = elems.get(idx);
      if (e == null) {
        error(tr("missing layer with index {0}", idx));
      }
      if (!e.hasAttribute("name")) {
        error(tr("missing mandatory attribute ''name'' for element ''layer''"));
      }
      String name = e.getAttribute("name");
      names.put(idx, name);
      if (!e.hasAttribute("type")) {
        error(tr("missing mandatory attribute ''type'' for element ''layer''"));
      }
      String type = e.getAttribute("type");
      SessionLayerImporter imp = getSessionLayerImporter(type);
      if (imp == null) {
        CancelOrContinueDialog dialog = new CancelOrContinueDialog();
        dialog.show(
            tr("Unable to load layer"),
            tr("Cannot load layer of type ''{0}'' because no suitable importer was found.", type),
            JOptionPane.WARNING_MESSAGE,
            progressMonitor);
        if (dialog.isCancel()) {
          progressMonitor.cancel();
          return;
        } else {
          continue;
        }
      } else {
        importers.put(idx, imp);
        List<LayerDependency> depsImp = new ArrayList<LayerDependency>();
        for (int d : deps.get(idx)) {
          SessionLayerImporter dImp = importers.get(d);
          if (dImp == null) {
            CancelOrContinueDialog dialog = new CancelOrContinueDialog();
            dialog.show(
                tr("Unable to load layer"),
                tr(
                    "Cannot load layer {0} because it depends on layer {1} which has been skipped.",
                    idx, d),
                JOptionPane.WARNING_MESSAGE,
                progressMonitor);
            if (dialog.isCancel()) {
              progressMonitor.cancel();
              return;
            } else {
              continue LAYER;
            }
          }
          depsImp.add(new LayerDependency(d, layersMap.get(d), dImp));
        }
        ImportSupport support = new ImportSupport(name, idx, depsImp);
        Layer layer = null;
        Exception exception = null;
        try {
          layer = imp.load(e, support, progressMonitor.createSubTaskMonitor(1, false));
        } catch (IllegalDataException ex) {
          exception = ex;
        } catch (IOException ex) {
          exception = ex;
        }
        if (exception != null) {
          exception.printStackTrace();
          CancelOrContinueDialog dialog = new CancelOrContinueDialog();
          dialog.show(
              tr("Error loading layer"),
              tr(
                  "<html>Could not load layer {0} ''{1}''.<br>Error is:<br>{2}</html>",
                  idx, name, exception.getMessage()),
              JOptionPane.ERROR_MESSAGE,
              progressMonitor);
          if (dialog.isCancel()) {
            progressMonitor.cancel();
            return;
          } else {
            continue;
          }
        }

        if (layer == null) throw new RuntimeException();
        layersMap.put(idx, layer);
      }
      progressMonitor.worked(1);
    }

    layers = new ArrayList<Layer>();
    for (int idx : layersMap.keySet()) {
      Layer layer = layersMap.get(idx);
      if (layer == null) {
        continue;
      }
      Element el = elems.get(idx);
      if (el.hasAttribute("visible")) {
        layer.setVisible(Boolean.parseBoolean(el.getAttribute("visible")));
      }
      if (el.hasAttribute("opacity")) {
        try {
          double opacity = Double.parseDouble(el.getAttribute("opacity"));
          layer.setOpacity(opacity);
        } catch (NumberFormatException ex) {
          Main.warn(ex);
        }
      }
    }
    for (Entry<Integer, Layer> e : layersMap.entrySet()) {
      Layer l = e.getValue();
      if (l == null) {
        continue;
      }

      l.setName(names.get(e.getKey()));
      layers.add(l);
    }
  }
Example #19
0
 public boolean isCancelled() {
   return progressMonitor.isCancelled();
 }
Example #20
0
 /**
  * Notification of the end of the test. The tester may perform additional actions and destroy the
  * used structures
  */
 public void endTest() {
   progressMonitor.finishTask();
   progressMonitor = null;
 }
Example #21
0
  /**
   * Open a connection to the given url and return a reader on the input stream from that
   * connection. In case of user cancel, return <code>null</code>.
   *
   * @param urlStr The exact url to connect to.
   * @param progressMonitor progress monitoring and abort handler
   * @return An reader reading the input stream (servers answer) or <code>null</code>.
   * @throws OsmTransferException thrown if data transfer errors occur
   */
  protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor)
      throws OsmTransferException {
    try {
      URL url = null;
      try {
        url = new URL(urlStr.replace(" ", "%20"));
      } catch (MalformedURLException e) {
        throw new OsmTransferException(e);
      }
      try {
        // fix #7640, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive
        activeConnection = Utils.openHttpConnection(url, false);
      } catch (Exception e) {
        throw new OsmTransferException(
            tr("Failed to open connection to API {0}.", url.toExternalForm()), e);
      }
      if (cancel) {
        activeConnection.disconnect();
        return null;
      }

      if (doAuthenticate) {
        addAuth(activeConnection);
      }
      if (cancel) throw new OsmTransferCanceledException();
      if (Main.pref.getBoolean("osm-server.use-compression", true)) {
        activeConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      }

      activeConnection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15) * 1000);

      try {
        Main.info("GET " + url);
        activeConnection.connect();
      } catch (Exception e) {
        e.printStackTrace();
        OsmTransferException ote =
            new OsmTransferException(
                tr("Could not connect to the OSM server. Please check your internet connection."),
                e);
        ote.setUrl(url.toString());
        throw ote;
      }
      try {
        if (activeConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
          throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, null, null);

        if (activeConnection.getResponseCode() == HttpURLConnection.HTTP_PROXY_AUTH)
          throw new OsmTransferCanceledException();

        String encoding = activeConnection.getContentEncoding();
        if (activeConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
          String errorHeader = activeConnection.getHeaderField("Error");
          StringBuilder errorBody = new StringBuilder();
          try {
            InputStream i = FixEncoding(activeConnection.getErrorStream(), encoding);
            if (i != null) {
              BufferedReader in = new BufferedReader(new InputStreamReader(i));
              String s;
              while ((s = in.readLine()) != null) {
                errorBody.append(s);
                errorBody.append("\n");
              }
            }
          } catch (Exception e) {
            errorBody.append(tr("Reading error text failed."));
          }

          throw new OsmApiException(
              activeConnection.getResponseCode(),
              errorHeader,
              errorBody.toString(),
              url.toString());
        }

        return FixEncoding(new ProgressInputStream(activeConnection, progressMonitor), encoding);
      } catch (OsmTransferException e) {
        throw e;
      } catch (Exception e) {
        throw new OsmTransferException(e);
      }
    } finally {
      progressMonitor.invalidate();
    }
  }
  private PathOptimizer loadPDF(File fileName, ProgressMonitor monitor) {

    monitor.beginTask("", 100);
    monitor.setTicks(0);
    monitor.setCustomText(tr("Preparing"));

    double nodesTolerance = 0.0;
    Color color = null;
    int maxPaths = Integer.MAX_VALUE;

    if (this.mergeCloseNodesCheck.isSelected()) {
      try {
        nodesTolerance = Double.parseDouble(this.mergeCloseNodesTolerance.getText());
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Main.parent, tr("Tolerance is not a number"));
        return null;
      }
    }

    if (this.colorFilterCheck.isSelected()) {
      try {
        String colString = this.colorFilterColor.getText().replace("#", "");
        color = new Color(Integer.parseInt(colString, 16));
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Main.parent, tr("Could not parse color"));
        return null;
      }
    }

    if (this.limitPathCountCheck.isSelected()) {
      try {
        maxPaths = Integer.parseInt(this.limitPathCount.getText());
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Main.parent, tr("Could not parse max path count"));
        return null;
      }
    }

    monitor.setTicks(10);
    monitor.setCustomText(tr("Parsing file"));

    PathOptimizer data =
        new PathOptimizer(nodesTolerance, color, this.splitOnColorChangeCheck.isSelected());

    try {
      PdfBoxParser parser = new PdfBoxParser(data);
      parser.parse(fileName, maxPaths, monitor.createSubTaskMonitor(80, false));

    } catch (FileNotFoundException e1) {
      JOptionPane.showMessageDialog(Main.parent, tr("File not found."));
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing: {0}", e.getMessage()));
      return null;
    }

    monitor.setTicks(80);

    if (this.removeParallelSegmentsCheck.isSelected()) {
      try {
        double tolerance = Double.parseDouble(this.removeParallelSegmentsTolerance.getText());
        monitor.setCustomText(tr("Removing parallel segments"));
        data.removeParallelLines(tolerance);
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Main.parent, tr("Max distance is not a number"));
        return null;
      }
    }

    if (nodesTolerance > 0.0) {
      monitor.setTicks(83);
      monitor.setCustomText(tr("Joining nodes"));
      data.mergeNodes();
    }

    monitor.setTicks(85);
    monitor.setCustomText(tr("Joining adjacent segments"));
    data.mergeSegments();

    if (this.removeSmallObjectsCheck.isSelected()) {
      try {
        double tolerance = Double.parseDouble(this.removeSmallObjectsSize.getText());
        monitor.setTicks(90);
        monitor.setCustomText(tr("Removing small objects"));

        data.removeSmallObjects(tolerance);
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Main.parent, tr("Tolerance is not a number"));
        return null;
      }
    }

    if (this.removeLargeObjectsCheck.isSelected()) {
      try {
        double tolerance = Double.parseDouble(this.removeLargeObjectsSize.getText());
        monitor.setTicks(90);
        monitor.setCustomText(tr("Removing large objects"));
        data.removeLargeObjects(tolerance);
      } catch (Exception e) {
        JOptionPane.showMessageDialog(Main.parent, tr("Tolerance is not a number"));
        return null;
      }
    }

    monitor.setTicks(95);
    monitor.setCustomText(tr("Finalizing layers"));
    data.splitLayersByPathKind(
        this.splitOnShapeClosedCheck.isSelected(),
        this.splitOnSingleSegmentCheck.isSelected(),
        this.splitOnOrthogonalCheck.isSelected());
    data.finish();

    monitor.finishTask();
    return data;
  }
Example #23
0
 protected void launchSafeAndUploadTask() {
   ProgressMonitor monitor = new SwingRenderingProgressMonitor(pnlUploadLayers);
   monitor.beginTask(tr("Uploading and saving modified layers ..."));
   this.saveAndUploadTask = new SaveAndUploadTask(model, monitor);
   new Thread(saveAndUploadTask, saveAndUploadTask.getClass().getName()).start();
 }