Example #1
0
 /**
  * Initialize the program
  *
  * @param map Flag to reset configuration
  */
 private void initialize(final Map<String, Object> map) {
   // Check for a configuration option
   if (map.containsKey("dir")) {
     final File file = new File(map.get("dir").toString());
     if (!file.exists()) {
       file.mkdirs();
     }
     Util.setWorkingDirectory(file);
   }
   // Verify the directory
   final File local = Util.getWorkingDirectory();
   if (!local.exists()) {
     local.mkdirs();
   }
   // Load the Release info
   final URL releaseUrl = Util.getResourceByName("/org/sleeksnap/release.json");
   JSONObject releaseInfo = new JSONObject();
   if (releaseUrl != null) {
     try {
       releaseInfo = new JSONObject(new JSONTokener(releaseUrl.openStream()));
     } catch (final IOException e) {
       e.printStackTrace();
     }
   }
   // Set the UI skin
   try {
     UIManager.setLookAndFeel(
         releaseInfo.getString("uiClass", UIManager.getSystemLookAndFeelClassName()));
   } catch (final Exception e) {
     e.printStackTrace();
   }
   // Then start
   try {
     LoggingManager.configure();
   } catch (final IOException e) {
     logger.log(
         Level.WARNING,
         "Unable to configure logger, file logging and logging panel will not work.",
         e);
     JOptionPane.showMessageDialog(
         null,
         "Unable to configure logger, file logging and logging panel will not work.",
         "Error",
         JOptionPane.ERROR_MESSAGE);
   }
   logger.info("Loading plugins...");
   try {
     loadUploaders();
     loadFilters();
   } catch (final Exception e) {
     logger.log(Level.SEVERE, "Failed to load plugins!", e);
   }
   // Load the settings
   logger.info("Loading settings...");
   try {
     loadSettings(map.containsKey("resetconfig"));
   } catch (final Exception e) {
     logger.log(Level.SEVERE, "Failed to load settings!", e);
   }
   // Load the selected language
   try {
     Language.load(
         map.containsKey("language")
             ? map.get("language").toString()
             : configuration.getString("language", Constants.Configuration.DEFAULT_LANGUAGE));
   } catch (final IOException e) {
     logger.log(Level.SEVERE, "Failed to load language file!", e);
   }
   // Check the update mode
   final UpdaterMode mode = configuration.getEnumValue("updateMode", UpdaterMode.class);
   if (mode != UpdaterMode.MANUAL) {
     final UpdaterReleaseType type =
         configuration.getEnumValue("updateReleaseType", UpdaterReleaseType.class);
     final Updater updater = new Updater();
     if (updater.checkUpdate(type, mode == UpdaterMode.PROMPT)) {
       return;
     }
   }
   // Load the history
   logger.info("Loading history...");
   final File historyFile = new File(local, "history.json");
   history = new History(historyFile);
   if (historyFile.exists()) {
     logger.info("Using existing history file.");
     try {
       history.load();
     } catch (final Exception e) {
       logger.log(Level.WARNING, "Failed to load history", e);
     }
   } else {
     logger.info("Using new history file.");
   }
   // Validate settings
   if (!configuration.contains("hotkeys") || !configuration.contains("uploaders")) {
     promptConfigurationReset();
   }
   // Register the hotkeys
   logger.info("Registering keys...");
   keyManager = new HotkeyManager(this);
   keyManager.initializeInput();
   logger.info("Opening tray icon...");
   initializeTray();
   logger.info("Ready.");
 }
Example #2
0
  /**
   * Execute an upload
   *
   * @param object The object to upload
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void executeUpload(Upload object) {
    // Run the object through the filters
    if (filters.containsKey(object.getClass())) {
      for (final UploadFilter filter : filters.get(object.getClass())) {
        try {
          object = filter.filter(object);
        } catch (final FilterException e) {
          // FilterExceptions when thrown should interrupt the upload.
          showException(e, e.getErrorMessage());
          return;
        }
      }
    }
    // Then upload it
    final Uploader uploader = uploaderAssociations.get(object.getClass());
    if (uploader != null) {
      try {
        String url = uploader.upload(object);
        if (url != null) {
          if (configuration.getBoolean("shortenurls")) {
            final Uploader shortener = uploaderAssociations.get(URL.class);
            if (shortener != null) {
              url = shortener.upload(new URLUpload(url));
            }
          }
          if (object instanceof ImageUpload) {
            if (configuration.getBoolean("savelocal")
                && !(uploader instanceof ImageLocalFileUploader)) {
              final FileOutputStream output =
                  new FileOutputStream(getLocalFile(DateUtil.getCurrentDate() + ".png"));
              try {
                ImageIO.write(((ImageUpload) object).getImage(), "png", output);
              } finally {
                output.close();
              }
            }
            ((ImageUpload) object).getImage().flush();
            ((ImageUpload) object).setImage(null);
          }
          url = url.trim();

          retries = 0;

          ClipboardUtil.setClipboard(url);

          lastUrl = url;
          history.addEntry(new HistoryEntry(url, uploader.getName()));
          icon.displayMessage(
              Language.getString("uploadComplete"),
              Language.getString("uploadedTo", url),
              TrayIcon.MessageType.INFO);
          logger.info("Upload completed, url: " + url);
        } else {
          icon.displayMessage(
              Language.getString("uploadFailed"),
              Language.getString("uploadFailedError"),
              TrayIcon.MessageType.ERROR);
          logger.severe("Upload failed to execute due to an unknown error");
        }
      } catch (final UploaderConfigurationException e) {
        icon.displayMessage(
            Language.getString("uploaderConfigError"),
            Language.getString("uploaderConfigErrorMessage"),
            TrayIcon.MessageType.ERROR);
        logger.log(Level.SEVERE, "Upload failed to execute", e);
      } catch (final Exception e) {
        // Retry until retries > max
        final StringBuilder msg = new StringBuilder("The upload failed to execute: ");
        msg.append(e.getMessage());
        final int max =
            configuration.getInteger("max_retries", Constants.Configuration.DEFAULT_MAX_RETRIES);
        if (retries++ < max) {
          logger.info("Retrying upload (" + retries + " of " + max + " retries)...");
          msg.append("\nRetrying...");
          upload(object);
        } else {
          msg.append("\nReached retry limit, upload aborted.");
          logger.log(Level.SEVERE, "Upload failed to execute, retries: " + retries, e);
          retries = 0;
        }
        icon.displayMessage(
            Language.getString("uploadFailed"), msg.toString(), TrayIcon.MessageType.ERROR);
      }
    }
  }