/** @see CredentialsAgent#lookup */
 @Override
 public PasswordAuthentication lookup(RequestorType requestorType, String host)
     throws CredentialsAgentException {
   if (requestorType == null) return null;
   String user;
   String password;
   switch (requestorType) {
     case SERVER:
       if (Objects.equals(OsmApi.getOsmApi().getHost(), host)) {
         user = Main.pref.get("osm-server.username", null);
         password = Main.pref.get("osm-server.password", null);
       } else if (host != null) {
         user = Main.pref.get("server.username." + host, null);
         password = Main.pref.get("server.password." + host, null);
       } else {
         user = null;
         password = null;
       }
       if (user == null) return null;
       return new PasswordAuthentication(
           user, password == null ? new char[0] : password.toCharArray());
     case PROXY:
       user = Main.pref.get(ProxyPreferencesPanel.PROXY_USER, null);
       password = Main.pref.get(ProxyPreferencesPanel.PROXY_PASS, null);
       if (user == null) return null;
       return new PasswordAuthentication(
           user, password == null ? new char[0] : password.toCharArray());
   }
   return null;
 }
Exemplo n.º 2
0
  /**
   * Explains a {@link OsmApiException} which was thrown because accessing a protected resource was
   * forbidden (HTTP 403).
   *
   * @param e the exception
   */
  public static void explainAuthorizationFailed(OsmApiException e) {

    Matcher m;
    String msg;
    String url = e.getAccessedUrl();
    Pattern p = Pattern.compile("https?://.*/api/0.6/(node|way|relation)/(\\d+)/(\\d+)");

    // Special case for individual access to redacted versions
    // See http://wiki.openstreetmap.org/wiki/Open_Database_License/Changes_in_the_API
    if (url != null && (m = p.matcher(url)).matches()) {
      String type = m.group(1);
      String id = m.group(2);
      String version = m.group(3);
      // {1} is the translation of "node", "way" or "relation"
      msg =
          tr("Access to redacted version ''{0}'' of {1} {2} is forbidden.", version, tr(type), id);
    } else if (OsmApi.isUsingOAuth()) {
      msg = ExceptionUtil.explainFailedOAuthAuthorisation(e);
    } else {
      msg = ExceptionUtil.explainFailedAuthorisation(e);
    }

    HelpAwareOptionPane.showOptionDialog(
        Main.parent,
        msg,
        tr("Authorisation Failed"),
        JOptionPane.ERROR_MESSAGE,
        ht("/ErrorMessages#AuthorizationFailed"));
  }
 /** @see CredentialsAgent#store */
 @Override
 public void store(RequestorType requestorType, String host, PasswordAuthentication credentials)
     throws CredentialsAgentException {
   if (requestorType == null) return;
   switch (requestorType) {
     case SERVER:
       if (Objects.equals(OsmApi.getOsmApi().getHost(), host)) {
         Main.pref.put("osm-server.username", credentials.getUserName());
         if (credentials.getPassword() == null) {
           Main.pref.put("osm-server.password", null);
         } else {
           Main.pref.put("osm-server.password", String.valueOf(credentials.getPassword()));
         }
       } else if (host != null) {
         Main.pref.put("server.username." + host, credentials.getUserName());
         if (credentials.getPassword() == null) {
           Main.pref.put("server.password." + host, null);
         } else {
           Main.pref.put("server.password." + host, String.valueOf(credentials.getPassword()));
         }
       }
       break;
     case PROXY:
       Main.pref.put(ProxyPreferencesPanel.PROXY_USER, credentials.getUserName());
       if (credentials.getPassword() == null) {
         Main.pref.put(ProxyPreferencesPanel.PROXY_PASS, null);
       } else {
         Main.pref.put(
             ProxyPreferencesPanel.PROXY_PASS, String.valueOf(credentials.getPassword()));
       }
       break;
   }
 }
Exemplo n.º 4
0
 @Override
 public void mouseClicked(MouseEvent e) {
   if (SwingUtilities.isRightMouseButton(e) && noteData.getSelectedNote() != null) {
     final String url =
         OsmApi.getOsmApi().getBaseUrl() + "notes/" + noteData.getSelectedNote().getId();
     ClipboardUtils.copyString(url);
     return;
   } else if (!SwingUtilities.isLeftMouseButton(e)) {
     return;
   }
   Point clickPoint = e.getPoint();
   double snapDistance = 10;
   double minDistance = Double.MAX_VALUE;
   final int iconHeight = ImageProvider.ImageSizes.SMALLICON.getAdjustedHeight();
   Note closestNote = null;
   for (Note note : noteData.getNotes()) {
     Point notePoint = Main.map.mapView.getPoint(note.getLatLon());
     // move the note point to the center of the icon where users are most likely to click when
     // selecting
     notePoint.setLocation(notePoint.getX(), notePoint.getY() - iconHeight / 2);
     double dist = clickPoint.distanceSq(notePoint);
     if (minDistance > dist && clickPoint.distance(notePoint) < snapDistance) {
       minDistance = dist;
       closestNote = note;
     }
   }
   noteData.setSelectedNote(closestNote);
 }
Exemplo n.º 5
0
 public static CredentialDialog getOsmApiCredentialDialog(
     String username, String password, String host, String saveUsernameAndPasswordCheckboxText) {
   CredentialDialog dialog = new CredentialDialog(saveUsernameAndPasswordCheckboxText);
   if (Objects.equals(OsmApi.getOsmApi().getHost(), host)) {
     dialog.prepareForOsmApiCredentials(username, password);
   } else {
     dialog.prepareForOtherHostCredentials(username, password, host);
   }
   dialog.pack();
   return dialog;
 }
Exemplo n.º 6
0
 @Override
 protected void build() {
   super.build();
   tfUserName.setToolTipText(tr("Please enter the user name of your OSM account"));
   tfPassword.setToolTipText(tr("Please enter the password of your OSM account"));
   String apiUrl = OsmApi.getOsmApi().getBaseUrl();
   lblHeading.setText(
       "<html>"
           + tr(
               "Authenticating at the OSM API ''{0}'' failed. Please enter a valid username and a valid password.",
               apiUrl)
           + "</html>");
   updateWarningLabel(apiUrl);
 }
Exemplo n.º 7
0
  /**
   * Explains a {@link OsmApiException} which was thrown because the authentication at the OSM
   * server failed
   *
   * @param e the exception
   */
  public static void explainAuthenticationFailed(OsmApiException e) {
    String msg;
    if (OsmApi.isUsingOAuth()) {
      msg = ExceptionUtil.explainFailedOAuthAuthentication(e);
    } else {
      msg = ExceptionUtil.explainFailedBasicAuthentication(e);
    }

    HelpAwareOptionPane.showOptionDialog(
        Main.parent,
        msg,
        tr("Authentication Failed"),
        JOptionPane.ERROR_MESSAGE,
        ht("/ErrorMessages#AuthenticationFailed"));
  }
Exemplo n.º 8
0
  /** Saves the values to the preferences */
  public void saveToPreferences() {
    String old_url = Main.pref.get("osm-server.url", null);
    if (cbUseDefaultServerUrl.isSelected()) {
      Main.pref.put("osm-server.url", null);
    } else if (tfOsmServerUrl.getText().trim().equals(OsmApi.DEFAULT_API_URL)) {
      Main.pref.put("osm-server.url", null);
    } else {
      Main.pref.put("osm-server.url", tfOsmServerUrl.getText().trim());
    }
    String new_url = Main.pref.get("osm-server.url", null);

    // When API URL changes, re-initialize API connection so we may adjust
    // server-dependent settings.
    if ((old_url == null && new_url != null) || (old_url != null && !old_url.equals(new_url))) {
      try {
        OsmApi.getOsmApi().initialize(null);
      } catch (Exception x) {
        // ignore;
      }
    }
  }
Exemplo n.º 9
0
 protected MaxChangesetSizeExceededPolicy askMaxChangesetSizeExceedsPolicy() {
   ButtonSpec[] specs =
       new ButtonSpec[] {
         new ButtonSpec(
             tr("Continue uploading"),
             ImageProvider.get("upload"),
             tr("Click to continue uploading to additional new changesets"),
             null /* no specific help text */),
         new ButtonSpec(
             tr("Go back to Upload Dialog"),
             ImageProvider.get("dialogs", "uploadproperties"),
             tr("Click to return to the Upload Dialog"),
             null /* no specific help text */),
         new ButtonSpec(
             tr("Abort"),
             ImageProvider.get("cancel"),
             tr("Click to abort uploading"),
             null /* no specific help text */)
       };
   int numObjectsToUploadLeft = toUpload.getSize() - processedPrimitives.size();
   String msg1 =
       tr(
           "The server reported that the current changeset was closed.<br>"
               + "This is most likely because the changesets size exceeded the max. size<br>"
               + "of {0} objects on the server ''{1}''.",
           OsmApi.getOsmApi().getCapabilities().getMaxChangesetSize(),
           OsmApi.getOsmApi().getBaseUrl());
   String msg2 =
       trn(
           "There is {0} object left to upload.",
           "There are {0} objects left to upload.",
           numObjectsToUploadLeft,
           numObjectsToUploadLeft);
   String msg3 =
       tr(
           "Click ''<strong>{0}</strong>'' to continue uploading to additional new changesets.<br>"
               + "Click ''<strong>{1}</strong>'' to return to the upload dialog.<br>"
               + "Click ''<strong>{2}</strong>'' to abort uploading and return to map editing.<br>",
           specs[0].text, specs[1].text, specs[2].text);
   String msg = "<html>" + msg1 + "<br><br>" + msg2 + "<br><br>" + msg3 + "</html>";
   int ret =
       HelpAwareOptionPane.showOptionDialog(
           Main.parent,
           msg,
           tr("Changeset is full"),
           JOptionPane.WARNING_MESSAGE,
           null, /* no special icon */
           specs,
           specs[0],
           ht("/Action/Upload#ChangesetFull"));
   switch (ret) {
     case 0:
       return MaxChangesetSizeExceededPolicy.AUTOMATICALLY_OPEN_NEW_CHANGESETS;
     case 1:
       return MaxChangesetSizeExceededPolicy.FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG;
     case 2:
       return MaxChangesetSizeExceededPolicy.ABORT;
     case JOptionPane.CLOSED_OPTION:
       return MaxChangesetSizeExceededPolicy.ABORT;
   }
   // should not happen
   return null;
 }
Exemplo n.º 10
0
  @Override
  protected void realRun() throws SAXException, IOException {
    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 (OsmTransferCancelledException e) {
          e.printStackTrace();
          uploadCancelled = true;
          break uploadloop;
        } catch (OsmApiPrimitiveGoneException e) {
          // try to recover from  410 Gone
          //
          recoverFromGoneOnServer(e, getProgressMonitor());
        } catch (ChangesetClosedException e) {
          processedPrimitives.addAll(writer.getProcessedPrimitives());
          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 (Exception e) {
      if (uploadCancelled) {
        System.out.println(
            tr(
                "Ignoring caught exception because upload is canceled. Exception is: {0}",
                e.toString()));
      } else {
        lastException = e;
      }
    }
    if (uploadCancelled && processedPrimitives.isEmpty()) return;
    cleanupAfterUpload();
  }
  protected String buildStrategySummary() {
    if (spec == null) return "";
    // check whether we can use one changeset only or whether we have to use
    // multiple changesets
    //
    boolean useOneChangeset = true;
    int maxChunkSize = OsmApi.getOsmApi().getCapabilities().getMaxChangesetSize();
    if (maxChunkSize > 0 && numObjects > maxChunkSize) {
      useOneChangeset = false;
    }

    int numRequests = spec.getNumRequests(numObjects);
    String msg = null;
    if (useOneChangeset) {
      lblWarning.setVisible(false);
      if (numRequests == 0) {
        msg =
            trn(
                "Uploading <strong>{0} object</strong> to <strong>1 changeset</strong>",
                "Uploading <strong>{0} objects</strong> to <strong>1 changeset</strong>",
                numObjects,
                numObjects);
      } else if (numRequests == 1) {
        msg =
            trn(
                "Uploading <strong>{0} object</strong> to <strong>1 changeset</strong> using <strong>1 request</strong>",
                "Uploading <strong>{0} objects</strong> to <strong>1 changeset</strong> using <strong>1 request</strong>",
                numObjects,
                numObjects);
      } else if (numRequests > 1) {
        msg =
            tr(
                "Uploading <strong>{0} objects</strong> to <strong>1 changeset</strong> using <strong>{1} requests</strong>",
                numObjects, numRequests);
      }
      msg =
          msg
              + " (<a href=\"urn:advanced-configuration\">"
              + tr("advanced configuration")
              + "</a>)";
    } else {
      lblWarning.setVisible(true);
      if (numRequests == 0) {
        msg =
            tr(
                "{0} objects exceed the max. allowed {1} objects in a changeset on the server ''{2}''. Please <a href=\"urn:advanced-configuration\">configure</a> how to proceed with <strong>multiple changesets</strong>",
                numObjects, maxChunkSize, OsmApi.getOsmApi().getBaseUrl());
      } else if (numRequests > 1) {
        msg =
            tr(
                "Uploading <strong>{0} objects</strong> to <strong>multiple changesets</strong> using <strong>{1} requests</strong>",
                numObjects, numRequests);
        msg =
            msg
                + " (<a href=\"urn:advanced-configuration\">"
                + tr("advanced configuration")
                + "</a>)";
      }
    }
    return msg;
  }