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();
  }
  /**
   * 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();
    }
  }
 @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 #4
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);
      }
    }
Example #5
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();
    }
  }
  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
  /**
   * 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;
    }
  }
  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 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();
  }
 @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 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 #12
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();
 }