public boolean isGlobalTransferBarShown() {
   if (!AzureusCoreFactory.isCoreRunning()) {
     return false;
   }
   return AllTransfersBar.getManager()
       .isOpen(AzureusCoreFactory.getSingleton().getGlobalManager());
 }
Пример #2
0
  /**
   * @param dl
   * @since 3.0.2.3
   */
  public static String getMediaServerContentURL(Download dl) {

    // TorrentListViewsUtils.debugDCAD("enter - getMediaServerContentURL");

    PluginManager pm = AzureusCoreFactory.getSingleton().getPluginManager();
    PluginInterface pi = pm.getPluginInterfaceByID("azupnpav", false);

    if (pi == null) {
      Logger.log(new LogEvent(LogIDs.UI3, "Media server plugin not found"));
      return null;
    }

    if (!pi.getPluginState().isOperational()) {
      Logger.log(new LogEvent(LogIDs.UI3, "Media server plugin not operational"));
      return null;
    }

    try {
      Program program = Program.findProgram(".qtl");
      boolean hasQuickTime =
          program == null ? false : (program.getName().toLowerCase().indexOf("quicktime") != -1);

      pi.getIPC().invoke("setQuickTimeAvailable", new Object[] {new Boolean(hasQuickTime)});

      Object url = pi.getIPC().invoke("getContentURL", new Object[] {dl});
      if (url instanceof String) {
        return (String) url;
      }
    } catch (Throwable e) {
      Logger.log(
          new LogEvent(LogIDs.UI3, LogEvent.LT_WARNING, "IPC to media server plugin failed", e));
    }

    return null;
  }
  public static void main(String[] args) {
    try {
      COConfigurationManager.initialise();

      boolean v6 = true;

      // Test connectivity.
      if (true) {
        // System.out.println( "UDP:  " + getSingleton().getExternalIpAddressUDP(null,0,v6));
        // System.out.println( "TCP:  " + getSingleton().getExternalIpAddressTCP(null,0,v6));
        // System.out.println( "HTTP: " + getSingleton().getExternalIpAddressHTTP(v6));
      }

      Map data = constructVersionCheckMessage(VersionCheckClient.REASON_UPDATE_CHECK_START);
      System.out.println("Sending (pre-initialisation):");
      printDataMap(data);
      System.out.println("-----------");

      System.out.println("Receiving (pre-initialisation):");
      printDataMap(
          getSingleton().getVersionCheckInfo(VersionCheckClient.REASON_UPDATE_CHECK_START));
      System.out.println("-----------");

      System.out.println();
      System.out.print("Initialising core... ");

      /**
       * Suppress all of these errors being displayed in the output.
       *
       * <p>These things should be temporary...
       */
      AzureusCoreImpl.SUPPRESS_CLASSLOADER_ERRORS = true;
      DownloadManagerStateImpl.SUPPRESS_FIXUP_ERRORS = true;

      AzureusCore core = AzureusCoreFactory.create();
      core.start();
      System.out.println("done.");
      System.out.println();
      System.out.println("-----------");

      data = constructVersionCheckMessage(VersionCheckClient.REASON_UPDATE_CHECK_START);
      System.out.println("Sending (post-initialisation):");
      printDataMap(data);
      System.out.println("-----------");

      System.out.println("Receiving (post-initialisation):");
      printDataMap(
          getSingleton().getVersionCheckInfo(VersionCheckClient.REASON_UPDATE_CHECK_START));
      System.out.println("-----------");
      System.out.println();

      System.out.print("Shutting down core... ");
      core.stop();
      System.out.println("done.");

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
Пример #4
0
  private static boolean canPlay(TOTorrent torrent, int file_index) {
    if (!PlatformTorrentUtils.isContent(torrent, false)) {
      return false;
    }

    if (!AzureusCoreFactory.isCoreRunning()) {
      return false;
    }

    GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager();
    DownloadManager dm = gm.getDownloadManager(torrent);

    if (dm != null) {
      return dm.getAssumedComplete() || canUseEMP(torrent, file_index);
    }
    return canUseEMP(torrent, file_index);
  }
Пример #5
0
 public ViewDownSpeedGraph() {
   AzureusCoreFactory.addCoreRunningListener(
       new AzureusCoreRunningListener() {
         public void azureusCoreRunning(AzureusCore core) {
           manager = core.getGlobalManager();
           stats = manager.getStats();
         }
       });
 }
Пример #6
0
  /** @return */
  public static boolean hasFullBurn() {

    PluginInterface pi =
        PluginInitializer.getDefaultInterface().getPluginState().isInitialisationComplete()
            ? AzureusCoreFactory.getSingleton()
                .getPluginManager()
                .getPluginInterfaceByID("azburn_v")
            : null;
    if (pi == null) {
      // maybe not added yet.. use featman
      Set<String> featuresInstalled = UtilitiesImpl.getFeaturesInstalled();
      return featuresInstalled.contains("dvdburn_trial") && !featuresInstalled.contains("dvdburn");
    }
    return pi.getPluginState().isOperational();
  }
Пример #7
0
  private static void writeTorrentIfExists(TOTorrent torrent) {
    AzureusCore core = AzureusCoreFactory.getSingleton();
    if (core == null || !core.isStarted()) {
      return;
    }

    GlobalManager gm = core.getGlobalManager();
    if (gm == null || gm.getDownloadManager(torrent) == null) {
      return;
    }

    try {
      TorrentUtils.writeToFile(torrent);
    } catch (TOTorrentException e) {
      Debug.out(e);
    }
  }
Пример #8
0
  public static boolean embeddedPlayerAvail() {
    // cache true, always recheck false in case plugin installs.
    if (embeddedPlayerAvail) {
      return true;
    }

    try {
      PluginInterface pi =
          AzureusCoreFactory.getSingleton()
              .getPluginManager()
              .getPluginInterfaceByID("azemp", true);
      if (pi != null) {
        embeddedPlayerAvail = true;
      }
    } catch (Throwable e1) {
    }

    return embeddedPlayerAvail;
  }
Пример #9
0
  private static final synchronized boolean loadEmpPluginClass() {
    if (piEmp != null && piEmp.getPluginState().isUnloaded()) {
      piEmp = null;
      triedLoadingEmpPluginClass = false;
      methodIsExternallyPlayable = null;
      methodIsExternallyPlayable2 = null;
    }

    if (!triedLoadingEmpPluginClass) {
      triedLoadingEmpPluginClass = true;

      try {
        piEmp =
            AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaceByID("azemp");

        if (piEmp == null) {

          return (false);
        }

        Class empPluginClass = piEmp.getPlugin().getClass();

        methodIsExternallyPlayable =
            empPluginClass.getMethod("isExternallyPlayable", new Class[] {TOTorrent.class});

        try {
          methodIsExternallyPlayable2 =
              empPluginClass.getMethod(
                  "isExternallyPlayable", new Class[] {TOTorrent.class, int.class});
        } catch (Throwable e) {
          Logger.log(new LogEvent(LogIDs.UI3, "isExternallyPlayable with file_index not found"));
        }

        // methodIsExternalPlayerInstalled = empPluginClass.getMethod("isExternalPlayerInstalled",
        // new Class[] {});

      } catch (Exception e1) {
        return false;
      }
    }
    return true;
  }
Пример #10
0
  public static boolean isExternallyPlayable(
      TOTorrent torrent, int file_index, boolean complete_only) {
    if (torrent == null) {
      return false;
    }
    try {
      Download download =
          AzureusCoreFactory.getSingleton()
              .getPluginManager()
              .getDefaultPluginInterface()
              .getDownloadManager()
              .getDownload(torrent.getHash());
      if (download != null) {
        return isExternallyPlayable(download, file_index, complete_only);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
Пример #11
0
  public static void registerWithFeatureManager() {
    if (!enabled) {
      return;
    }
    AzureusCoreFactory.addCoreRunningListener(
        new AzureusCoreRunningListener() {

          public void azureusCoreRunning(AzureusCore core) {
            PluginInterface pi = core.getPluginManager().getDefaultPluginInterface();
            featman = pi.getUtilities().getFeatureManager();

            fml = new FeatureManagerUIListener(featman);
            featman.addListener(fml);
            Licence[] licences = featman.getLicences();
            for (Licence licence : licences) {
              fml.licenceAdded(licence);
            }

            UIManager ui_manager = pi.getUIManager();

            ui_manager.addUIListener(
                new UIManagerListener() {
                  public void UIDetached(UIInstance instance) {}

                  public void UIAttached(UIInstance instance) {
                    if (!(instance instanceof UISWTInstance)) {
                      return;
                    }

                    if (!Utils.isAZ2UI()) {
                      addFreeBurnUI();
                    }
                  }
                });
          }
        });
  }
Пример #12
0
  public Composite configSectionCreate(final Composite parent) {
    ImageLoader imageLoader = ImageLoader.getInstance();
    Image imgOpenFolder = imageLoader.getImage("openFolderButton");

    GridData gridData;
    GridLayout layout;

    final Composite cBR = new Composite(parent, SWT.NULL);

    gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
    cBR.setLayoutData(gridData);
    layout = new GridLayout();
    layout.numColumns = 1;
    cBR.setLayout(layout);

    Label info_label = new Label(cBR, SWT.WRAP);
    Messages.setLanguageText(info_label, "ConfigView.section.br.overview");
    gridData = Utils.getWrappableLabelGridData(1, GridData.HORIZONTAL_ALIGN_FILL);

    info_label.setLayoutData(gridData);

    // wiki link

    final Label linkLabel = new Label(cBR, SWT.NULL);
    linkLabel.setText(MessageText.getString("ConfigView.label.please.visit.here"));
    linkLabel.setData("http://wiki.vuze.com/w/Backup_And_Restore");
    linkLabel.setCursor(linkLabel.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
    linkLabel.setForeground(Colors.blue);
    gridData = Utils.getWrappableLabelGridData(1, 0);
    linkLabel.setLayoutData(gridData);
    linkLabel.addMouseListener(
        new MouseAdapter() {
          public void mouseDoubleClick(MouseEvent arg0) {
            Utils.launch((String) ((Label) arg0.widget).getData());
          }

          public void mouseDown(MouseEvent arg0) {
            Utils.launch((String) ((Label) arg0.widget).getData());
          }
        });
    ClipboardCopy.addCopyToClipMenu(linkLabel);

    final BackupManager backup_manager =
        BackupManagerFactory.getManager(AzureusCoreFactory.getSingleton());

    // backup

    Group gBackup = new Group(cBR, SWT.NULL);
    Messages.setLanguageText(gBackup, "br.backup");
    layout = new GridLayout(2, false);
    gBackup.setLayout(layout);
    gBackup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    // info

    Label last_backup_label = new Label(gBackup, SWT.NULL);
    Messages.setLanguageText(last_backup_label, "br.backup.last.time");

    final Label last_backup_time = new Label(gBackup, SWT.NULL);

    Label last_backup_error_label = new Label(gBackup, SWT.NULL);
    Messages.setLanguageText(last_backup_error_label, "br.backup.last.error");

    final Label last_backup_error = new Label(gBackup, SWT.NULL);

    final Runnable stats_updater =
        new Runnable() {
          public void run() {
            long backup_time = backup_manager.getLastBackupTime();

            last_backup_time.setText(backup_time == 0 ? "" : String.valueOf(new Date(backup_time)));

            last_backup_error.setText(backup_manager.getLastBackupError());
          };
        };

    stats_updater.run();

    // manual button

    Label backup_manual_label = new Label(gBackup, SWT.NULL);
    Messages.setLanguageText(backup_manual_label, "br.backup.manual.info");

    Button backup_button = new Button(gBackup, SWT.PUSH);
    Messages.setLanguageText(backup_button, "br.backup");

    backup_button.addListener(
        SWT.Selection,
        new Listener() {
          public void handleEvent(Event event) {
            String def_dir = COConfigurationManager.getStringParameter("br.backup.folder.default");

            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);

            if (def_dir != null) {
              dialog.setFilterPath(def_dir);
            }

            dialog.setMessage(MessageText.getString("br.backup.folder.info"));
            dialog.setText(MessageText.getString("br.backup.folder.title"));

            String path = dialog.open();

            if (path != null) {

              COConfigurationManager.setParameter("br.backup.folder.default", path);

              runBackup(backup_manager, path, stats_updater);
            }
          }
        });

    final BooleanParameter auto_backup_enable =
        new BooleanParameter(gBackup, "br.backup.auto.enable", "br.backup.auto.enable");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    auto_backup_enable.setLayoutData(gridData);

    Composite gDefaultDir = new Composite(gBackup, SWT.NONE);
    layout = new GridLayout();
    layout.numColumns = 3;
    layout.marginHeight = 2;
    gDefaultDir.setLayout(layout);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    gDefaultDir.setLayoutData(gridData);

    Label lblDefaultDir = new Label(gDefaultDir, SWT.NONE);
    Messages.setLanguageText(lblDefaultDir, "ConfigView.section.file.defaultdir.ask");
    lblDefaultDir.setLayoutData(new GridData());

    gridData = new GridData(GridData.FILL_HORIZONTAL);
    final StringParameter pathParameter =
        new StringParameter(gDefaultDir, "br.backup.auto.dir", "");
    pathParameter.setLayoutData(gridData);

    if (pathParameter.getValue().length() == 0) {
      String def_dir = COConfigurationManager.getStringParameter("br.backup.folder.default");

      pathParameter.setValue(def_dir);
    }

    Button browse = new Button(gDefaultDir, SWT.PUSH);
    browse.setImage(imgOpenFolder);
    imgOpenFolder.setBackground(browse.getBackground());
    browse.setToolTipText(MessageText.getString("ConfigView.button.browse"));

    browse.addListener(
        SWT.Selection,
        new Listener() {
          /* (non-Javadoc)
           * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
           */
          public void handleEvent(Event event) {
            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);
            dialog.setFilterPath(pathParameter.getValue());
            dialog.setMessage(MessageText.getString("br.backup.auto.dir.select"));
            dialog.setText(MessageText.getString("ConfigView.section.file.defaultdir.ask"));
            String path = dialog.open();
            if (path != null) {
              pathParameter.setValue(path);

              COConfigurationManager.setParameter("br.backup.folder.default", path);
            }
          }
        });

    Label lbl_backup_days = new Label(gDefaultDir, SWT.NULL);
    Messages.setLanguageText(lbl_backup_days, "br.backup.auto.everydays");

    IntParameter backup_everydays =
        new IntParameter(gDefaultDir, "br.backup.auto.everydays", 1, Integer.MAX_VALUE);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    backup_everydays.setLayoutData(gridData);

    Label lbl_backup_retain = new Label(gDefaultDir, SWT.NULL);
    Messages.setLanguageText(lbl_backup_retain, "br.backup.auto.retain");

    IntParameter backup_retain =
        new IntParameter(gDefaultDir, "br.backup.auto.retain", 1, Integer.MAX_VALUE);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    backup_retain.setLayoutData(gridData);

    BooleanParameter chkNotify =
        new BooleanParameter(gDefaultDir, "br.backup.notify", "br.backup.notify");
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 3;
    chkNotify.setLayoutData(gridData);

    Label backup_auto_label = new Label(gDefaultDir, SWT.NULL);
    Messages.setLanguageText(backup_auto_label, "br.backup.auto.now");

    Button backup_auto_button = new Button(gDefaultDir, SWT.PUSH);
    Messages.setLanguageText(backup_auto_button, "br.test");

    backup_auto_button.addListener(
        SWT.Selection,
        new Listener() {
          public void handleEvent(Event event) {
            runBackup(backup_manager, null, stats_updater);
          }
        });

    auto_backup_enable.setAdditionalActionPerformer(
        new ChangeSelectionActionPerformer(gDefaultDir));

    // restore

    Group gRestore = new Group(cBR, SWT.NULL);
    Messages.setLanguageText(gRestore, "br.restore");
    layout = new GridLayout(2, false);
    gRestore.setLayout(layout);
    gRestore.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    Label restore_label = new Label(gRestore, SWT.NULL);
    Messages.setLanguageText(restore_label, "br.restore.info");

    Button restore_button = new Button(gRestore, SWT.PUSH);
    Messages.setLanguageText(restore_button, "br.restore");

    restore_button.addListener(
        SWT.Selection,
        new Listener() {
          public void handleEvent(Event event) {
            String def_dir = COConfigurationManager.getStringParameter("br.backup.folder.default");

            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);

            if (def_dir != null) {
              dialog.setFilterPath(def_dir);
            }

            dialog.setMessage(MessageText.getString("br.restore.folder.info"));

            dialog.setText(MessageText.getString("br.restore.folder.title"));

            final String path = dialog.open();

            if (path != null) {

              MessageBoxShell mb =
                  new MessageBoxShell(
                      SWT.ICON_WARNING | SWT.OK | SWT.CANCEL,
                      MessageText.getString("br.restore.warning.title"),
                      MessageText.getString("br.restore.warning.info"));

              mb.setDefaultButtonUsingStyle(SWT.CANCEL);
              mb.setParent(parent.getShell());

              mb.open(
                  new UserPrompterResultListener() {
                    public void prompterClosed(int returnVal) {
                      if (returnVal != SWT.OK) {
                        return;
                      }

                      final TextViewerWindow viewer =
                          new TextViewerWindow(
                              MessageText.getString("br.backup.progress"), null, "", true, true);

                      viewer.setEditable(false);

                      viewer.setOKEnabled(false);

                      backup_manager.restore(
                          new File(path),
                          new BackupManager.BackupListener() {
                            public boolean reportProgress(String str) {
                              return (append(str, false));
                            }

                            public void reportComplete() {
                              append("Restore Complete!", true);

                              Utils.execSWTThread(
                                  new AERunnable() {
                                    public void runSupport() {
                                      MessageBoxShell mb =
                                          new MessageBoxShell(
                                              SWT.ICON_INFORMATION | SWT.OK,
                                              MessageText.getString(
                                                  "ConfigView.section.security.restart.title"),
                                              MessageText.getString(
                                                  "ConfigView.section.security.restart.msg"));
                                      mb.setParent(parent.getShell());
                                      mb.open(
                                          new UserPrompterResultListener() {
                                            public void prompterClosed(int returnVal) {
                                              UIFunctionsSWT uiFunctions =
                                                  UIFunctionsManagerSWT.getUIFunctionsSWT();

                                              if (uiFunctions != null) {

                                                uiFunctions.dispose(true, false);
                                              }
                                            }
                                          });
                                    }
                                  });
                            }

                            public void reportError(Throwable error) {
                              append(
                                  "Restore Failed: " + Debug.getNestedExceptionMessage(error),
                                  true);
                            }

                            private boolean append(final String str, final boolean complete) {
                              if (viewer.isDisposed()) {

                                return (false);
                              }

                              Utils.execSWTThread(
                                  new AERunnable() {
                                    public void runSupport() {
                                      if (str.endsWith("...")) {

                                        viewer.append(str);

                                      } else {

                                        viewer.append(str + "\r\n");
                                      }

                                      if (complete) {

                                        viewer.setOKEnabled(true);
                                      }
                                    }
                                  });

                              return (true);
                            }
                          });

                      viewer.goModal();
                    }
                  });
            }
          }
        });

    return (cBR);
  }
Пример #13
0
  static final int openDocProc(int theAppleEvent, int reply, int handlerRefcon) {
    try {
      Object aeDesc = claAEDesc.newInstance();
      Object eventRecord = claEventRecord.newInstance();
      invoke(
          claOS,
          null,
          "ConvertEventRefToEventRecord",
          new Class[] {int.class, claEventRecord},
          new Object[] {theAppleEvent, eventRecord});
      try {
        int result =
            OSXAccess.AEGetParamDesc(theAppleEvent, kEventParamDirectObject, typeAEList, aeDesc);
        if (result != noErr) {
          Debug.out("OSX: Could call AEGetParamDesc. Error: " + result);
          return noErr;
        }
      } catch (java.lang.UnsatisfiedLinkError e) {
        Debug.out("OSX: AEGetParamDesc not available.  Can't open sent file");
        return noErr;
      }

      int[] count = new int[1];
      invoke(
          claOS,
          null,
          "AECountItems",
          new Class[] {claAEDesc, int[].class},
          new Object[] {aeDesc, count});
      // System.out.println("COUNT: " + count[0]);
      if (count[0] > 0) {
        final String[] fileNames = new String[count[0]];
        int maximumSize = 80; // size of FSRef
        int dataPtr =
            ((Number) invoke(claOS, null, "NewPtr", new Object[] {maximumSize})).intValue();
        int[] aeKeyword = new int[1];
        int[] typeCode = new int[1];
        int[] actualSize = new int[1];
        for (int i = 0; i < count[0]; i++) {
          try {
            // int AEGetNthPtr(AEDesc theAEDescList, int index, int desiredType,
            // int[] theAEKeyword, int[] typeCode, int dataPtr, int maximumSize, int[] actualSize);
            Class<?>[] sigAEGetNthPtr =
                new Class[] {
                  claAEDesc,
                  int.class,
                  int.class,
                  int[].class,
                  int[].class,
                  int.class,
                  int.class,
                  int[].class
                };
            int ret =
                ((Number)
                        invoke(
                            claOS,
                            null,
                            "AEGetNthPtr",
                            sigAEGetNthPtr,
                            new Object[] {
                              aeDesc,
                              i + 1,
                              typeFSRef,
                              aeKeyword,
                              typeCode,
                              dataPtr,
                              maximumSize,
                              actualSize
                            }))
                    .intValue();
            if (ret == noErr) {
              byte[] fsRef = new byte[actualSize[0]];
              memmove(fsRef, dataPtr, actualSize[0]);
              int dirUrl =
                  ((Number)
                          invoke(
                              claOS,
                              null,
                              "CFURLCreateFromFSRef",
                              new Object[] {kCFAllocatorDefault, fsRef}))
                      .intValue();
              int dirString =
                  ((Number)
                          invoke(
                              claOS,
                              null,
                              "CFURLCopyFileSystemPath",
                              new Object[] {dirUrl, kCFURLPOSIXPathStyle}))
                      .intValue();
              int length =
                  ((Number) invoke(claOS, null, "CFStringGetLength", new Object[] {dirString}))
                      .intValue();
              char[] buffer = new char[length];
              Object range = claCFRange.newInstance();
              claCFRange.getField("length").setInt(range, length);
              invoke(
                  claOS,
                  null,
                  "CFStringGetCharacters",
                  new Class[] {int.class, claCFRange, char[].class},
                  new Object[] {dirString, range, buffer});
              fileNames[i] = new String(buffer);
              invoke(claOS, null, "CFRelease", new Object[] {dirString});
              invoke(claOS, null, "CFRelease", new Object[] {dirUrl});
            } else {
              ret =
                  ((Number)
                          invoke(
                              claOS,
                              null,
                              "AEGetNthPtr",
                              sigAEGetNthPtr,
                              new Object[] {
                                aeDesc,
                                i + 1,
                                typeText,
                                aeKeyword,
                                typeCode,
                                dataPtr,
                                2048,
                                actualSize
                              }))
                      .intValue();

              if (ret == noErr) {
                byte[] urlRef = new byte[actualSize[0]];
                memmove(urlRef, dataPtr, actualSize[0]);
                fileNames[i] = new String(urlRef);
              }
            }
          } catch (Throwable t) {
            Debug.out(t);
          }
          // System.out.println(fileNames[i]);
        }

        AzureusCoreFactory.addCoreRunningListener(
            new AzureusCoreRunningListener() {
              public void azureusCoreRunning(AzureusCore core) {
                TorrentOpener.openTorrents(fileNames);
              }
            });
      }

      return noErr;
    } catch (Throwable e) {
      Debug.out(e);
    }
    return eventNotHandledErr;
  }
  // @see com.aelitis.azureus.ui.swt.UIFunctionsSWT#showCoreWaitDlg()
  public Shell showCoreWaitDlg() {
    final SkinnedDialog closeDialog =
        new SkinnedDialog(
            "skin3_dlg_coreloading",
            "coreloading.body",
            SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);

    closeDialog.setTitle(MessageText.getString("dlg.corewait.title"));
    SWTSkin skin = closeDialog.getSkin();
    SWTSkinObjectButton soButton = (SWTSkinObjectButton) skin.getSkinObject("close");

    final SWTSkinObjectText soWaitTask = (SWTSkinObjectText) skin.getSkinObject("task");

    final SWTSkinObject soWaitProgress = skin.getSkinObject("progress");
    if (soWaitProgress != null) {
      soWaitProgress
          .getControl()
          .addPaintListener(
              new PaintListener() {
                public void paintControl(PaintEvent e) {
                  Control c = (Control) e.widget;
                  Point size = c.getSize();
                  e.gc.setBackground(ColorCache.getColor(e.display, "#23a7df"));
                  Object data = soWaitProgress.getData("progress");
                  if (data instanceof Long) {
                    int waitProgress = ((Long) data).intValue();
                    int breakX = size.x * waitProgress / 100;
                    e.gc.fillRectangle(0, 0, breakX, size.y);
                    e.gc.setBackground(ColorCache.getColor(e.display, "#cccccc"));
                    e.gc.fillRectangle(breakX, 0, size.x - breakX, size.y);
                  }
                }
              });
    }

    if (!AzureusCoreFactory.isCoreRunning()) {
      final Initializer initializer = Initializer.getLastInitializer();
      if (initializer != null) {
        initializer.addListener(
            new InitializerListener() {
              public void reportPercent(final int percent) {
                Utils.execSWTThread(
                    new AERunnable() {
                      public void runSupport() {
                        if (soWaitProgress != null && !soWaitProgress.isDisposed()) {
                          soWaitProgress.setData("progress", new Long(percent));
                          soWaitProgress.getControl().redraw();
                          soWaitProgress.getControl().update();
                        }
                      }
                    });
                if (percent > 100) {
                  initializer.removeListener(this);
                }
              }

              public void reportCurrentTask(String currentTask) {
                if (soWaitTask != null && !soWaitTask.isDisposed()) {
                  soWaitTask.setText(currentTask);
                }
              }
            });
      }
    }

    if (soButton != null) {
      soButton.addSelectionListener(
          new ButtonListenerAdapter() {
            public void pressed(
                SWTSkinButtonUtility buttonUtility, SWTSkinObject skinObject, int stateMask) {
              closeDialog.close();
            }
          });
    }

    closeDialog.addCloseListener(
        new SkinnedDialogClosedListener() {
          public void skinDialogClosed(SkinnedDialog dialog) {}
        });

    closeDialog.open();
    return closeDialog.getShell();
  }
  public boolean addTorrentWithOptions(boolean force, final TorrentOpenOptions torrentOptions) {

    if (AzureusCoreFactory.isCoreRunning()) {
      GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager();
      // Check if torrent already exists in gm, and add if not
      DownloadManager existingDownload = gm.getDownloadManager(torrentOptions.getTorrent());

      if (existingDownload != null) {

        final String fExistingName = existingDownload.getDisplayName();
        final DownloadManager fExistingDownload = existingDownload;

        fExistingDownload.fireGlobalManagerEvent(GlobalManagerEvent.ET_REQUEST_ATTENTION);

        Utils.execSWTThread(
            new AERunnable() {
              public void runSupport() {
                boolean can_merge =
                    TorrentUtils.canMergeAnnounceURLs(
                        torrentOptions.getTorrent(), fExistingDownload.getTorrent());

                Shell mainShell = UIFunctionsManagerSWT.getUIFunctionsSWT().getMainShell();

                if ((Display.getDefault().getActiveShell() == null
                        || !mainShell.isVisible()
                        || mainShell.getMinimized())
                    && (!can_merge)) {

                  new MessageSlideShell(
                      Display.getCurrent(),
                      SWT.ICON_INFORMATION,
                      MSG_ALREADY_EXISTS,
                      null,
                      new String[] {
                        ":" + torrentOptions.sOriginatingLocation,
                        fExistingName,
                        MessageText.getString(MSG_ALREADY_EXISTS_NAME),
                      },
                      new Object[] {fExistingDownload},
                      -1);
                } else {

                  if (can_merge) {

                    String text =
                        MessageText.getString(
                            MSG_ALREADY_EXISTS + ".text",
                            new String[] {
                              ":" + torrentOptions.sOriginatingLocation,
                              fExistingName,
                              MessageText.getString(MSG_ALREADY_EXISTS_NAME),
                            });

                    text +=
                        "\n\n" + MessageText.getString("openTorrentWindow.mb.alreadyExists.merge");

                    MessageBoxShell mb =
                        new MessageBoxShell(
                            SWT.YES | SWT.NO,
                            MessageText.getString(MSG_ALREADY_EXISTS + ".title"),
                            text);

                    mb.open(
                        new UserPrompterResultListener() {
                          public void prompterClosed(int result) {
                            if (result == SWT.YES) {

                              TorrentUtils.mergeAnnounceURLs(
                                  torrentOptions.getTorrent(), fExistingDownload.getTorrent());
                            }
                          }
                        });
                  } else {
                    MessageBoxShell mb =
                        new MessageBoxShell(
                            SWT.OK,
                            MSG_ALREADY_EXISTS,
                            new String[] {
                              ":" + torrentOptions.sOriginatingLocation,
                              fExistingName,
                              MessageText.getString(MSG_ALREADY_EXISTS_NAME),
                            });
                    mb.open(null);
                  }
                }
              }
            });

        if (torrentOptions.bDeleteFileOnCancel) {
          File torrentFile = new File(torrentOptions.sFileName);
          torrentFile.delete();
        }
        return true;
      }
    }

    if (!force) {
      String showAgainMode =
          COConfigurationManager.getStringParameter(
              ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS);
      if (showAgainMode != null
          && ((showAgainMode.equals(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS_NEVER))
              || (showAgainMode.equals(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS_MANY)
                  && torrentOptions.getFiles() != null
                  && torrentOptions.getFiles().length == 1))) {

        // we're about to silently add the download - ensure that it is going to be saved somewhere
        // vaguely sensible
        // as the current save location is simply taken from the 'default download' config which can
        // be blank (for example)

        boolean looks_good = false;

        String save_loc = torrentOptions.getParentDir().trim();

        if (save_loc.length() == 0) {

          // blank :(

        } else if (save_loc.startsWith(".")) {

          // relative to who knows where
        } else {

          File f = new File(save_loc);

          if (!f.exists()) {

            f.mkdirs();
          }

          if (f.isDirectory() && FileUtil.canWriteToDirectory(f)) {

            if (!f.equals(AETemporaryFileHandler.getTempDirectory())) {

              looks_good = true;
            }
          }
        }

        if (looks_good) {

          return TorrentOpener.addTorrent(torrentOptions);

        } else {

          torrentOptions.setParentDir("");

          MessageBoxShell mb =
              new MessageBoxShell(
                  SWT.OK | SWT.ICON_ERROR,
                  "OpenTorrentWindow.mb.invaliddefsave",
                  new String[] {save_loc});

          mb.open(
              new UserPrompterResultListener() {
                public void prompterClosed(int result) {
                  OpenTorrentOptionsWindow.addTorrent(torrentOptions);
                }
              });

          return (true);
        }
      }
    }

    OpenTorrentOptionsWindow.addTorrent(torrentOptions);

    return true;
  }
  protected Map getVersionCheckInfoSupport(
      String reason, boolean only_if_cached, boolean force, boolean v6) {
    try {
      synchronized (listeners) {
        if (REASON_UPDATE_CHECK_START.equals(reason)) {
          startCheckRan = true;
        }
        for (VersionCheckClientListener l : listeners) {
          l.versionCheckStarted(reason);
        }
      }
    } catch (Throwable t) {
      Debug.out(t);
    }
    if (v6) {

      if (enable_v6) {

        try {
          check_mon.enter();

          long time_diff = SystemTime.getCurrentTime() - last_check_time_v6;

          force = force || time_diff > CACHE_PERIOD || time_diff < 0;

          if (last_check_data_v6 == null || last_check_data_v6.size() == 0 || force) {
            // if we've never checked before then we go ahead even if the "only_if_cached"
            // flag is set as its had not chance of being cached yet!
            if (only_if_cached && last_check_data_v6 != null) {
              return (new HashMap());
            }
            try {
              last_check_data_v6 =
                  performVersionCheck(constructVersionCheckMessage(reason), true, true, true);

              if (last_check_data_v6 != null && last_check_data_v6.size() > 0) {

                COConfigurationManager.setParameter("versioncheck.cache.v6", last_check_data_v6);
              }
            } catch (SocketException t) {
              // internet is broken
              // Debug.out(t.getClass().getName() + ": " + t.getMessage());
            } catch (UnknownHostException t) {
              // dns is broken
              // Debug.out(t.getClass().getName() + ": " + t.getMessage());
            } catch (Throwable t) {
              Debug.out(t);
              last_check_data_v6 = new HashMap();
            }
          } else {
            Logger.log(
                new LogEvent(
                    LOGID,
                    "VersionCheckClient is using "
                        + "cached version check info. Using "
                        + last_check_data_v6.size()
                        + " reply keys."));
          }
        } finally {
          check_mon.exit();
        }
      }

      if (last_check_data_v6 == null) last_check_data_v6 = new HashMap();

      return last_check_data_v6;

    } else {

      try {
        check_mon.enter();

        long time_diff = SystemTime.getCurrentTime() - last_check_time_v4;

        force = force || time_diff > CACHE_PERIOD || time_diff < 0;

        if (last_check_data_v4 == null || last_check_data_v4.size() == 0 || force) {
          // if we've never checked before then we go ahead even if the "only_if_cached"
          // flag is set as its had not chance of being cached yet!
          if (only_if_cached && last_check_data_v4 != null) {
            return (new HashMap());
          }
          try {
            last_check_data_v4 =
                performVersionCheck(constructVersionCheckMessage(reason), true, true, false);

            if (last_check_data_v4 != null && last_check_data_v4.size() > 0) {

              COConfigurationManager.setParameter("versioncheck.cache.v4", last_check_data_v4);
            }

            // clear down any plugin-specific data that has successfully been sent to the version
            // server

            try {
              if (AzureusCoreFactory.isCoreAvailable()) {

                // installed plugin IDs
                PluginInterface[] plugins =
                    AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces();

                for (int i = 0; i < plugins.length; i++) {

                  PluginInterface plugin = plugins[i];

                  Map data =
                      plugin
                          .getPluginconfig()
                          .getPluginMapParameter("plugin.versionserver.data", null);

                  if (data != null) {

                    plugin
                        .getPluginconfig()
                        .setPluginMapParameter("plugin.versionserver.data", new HashMap());
                  }
                }
              }
            } catch (Throwable e) {
            }
          } catch (UnknownHostException t) {
            // no internet
            Debug.outNoStack(
                "VersionCheckClient - " + t.getClass().getName() + ": " + t.getMessage());
          } catch (IOException t) {
            // General connection problem.
            Debug.outNoStack(
                "VersionCheckClient - " + t.getClass().getName() + ": " + t.getMessage());
          } catch (Throwable t) {
            Debug.out(t);
            last_check_data_v4 = new HashMap();
          }
        } else {
          if (Logger.isEnabled())
            Logger.log(
                new LogEvent(
                    LOGID,
                    "VersionCheckClient is using "
                        + "cached version check info. Using "
                        + last_check_data_v4.size()
                        + " reply keys."));
        }
      } finally {
        check_mon.exit();
      }

      if (last_check_data_v4 == null) last_check_data_v4 = new HashMap();

      last_feature_flag_cache_time = 0;

      return last_check_data_v4;
    }
  }
Пример #17
0
  private static void updateMetaData_handleReply(
      TOTorrent torrent, String hash, String replyType, Map mapHashes) {
    if (hash == null && torrent != null) {
      try {
        hash = torrent.getHashWrapper().toBase32String();
      } catch (Exception e) {
      }
    }

    GlobalManager gm = AzureusCoreFactory.getSingleton().getGlobalManager();
    DownloadManager dm = gm.getDownloadManager(new HashWrapper(Base32.decode(hash)));

    if (torrent == null && dm != null) {
      torrent = dm.getTorrent();
    }
    Map contentMap = PlatformTorrentUtils.getContentMap(torrent);

    final TOTorrent torrentFinal = torrent;

    if (replyType.equals(PlatformMessenger.REPLY_EXCEPTION)) {
      if (torrent != null) {
        // try again in a bit
        log(torrent, "Exception, retrying later");
        SimpleTimer.addEvent(
            "Update MD Retry",
            SystemTime.getCurrentTime() + RETRY_METADATA,
            new TimerEventPerformer() {
              public void perform(TimerEvent event) {
                log(torrentFinal, "retry time");
                PlatformTorrentUtils.updateMetaData(torrentFinal, 15000);
              }
            });
      }
    } else {
      Map jsonMapMetaData = hash == null ? null : (Map) mapHashes.get(hash);
      if (jsonMapMetaData != null) {
        long oldLastUpdated = getContentLastUpdated(torrent);
        long expireyMins = 0;

        for (Iterator iter = jsonMapMetaData.keySet().iterator(); iter.hasNext(); ) {
          String key = (String) iter.next();
          Object value = jsonMapMetaData.get(key);

          if (value == null || value.equals(null)) {
            contentMap.remove(key);
          } else if ((key.equals("Thumbnail") || key.endsWith(".B64")) && value instanceof String) {
            contentMap.put(key, Base64.decode((String) value));
          } else if (key.equals("expires-in-mins") && value instanceof Long) {
            expireyMins = ((Long) value).longValue();
          } else {
            contentMap.put(key, value);
          }
          writeTorrentIfExists(torrent);
        }

        // crappy way of updating the display name
        if (dm != null) {
          String title = PlatformTorrentUtils.getContentTitle(torrent);
          if (title != null
              && title.length() > 0
              && dm.getDownloadState().getDisplayName() == null) {
            dm.getDownloadState().setDisplayName(title);
          }
        }
        triggerMetaDataUpdateListeners(torrent);

        if (torrent != null) {
          // setup next refresh

          long refreshOn;
          if (expireyMins > 0) {
            refreshOn = SystemTime.getCurrentTime() + (expireyMins * 60 * 1000L);
          } else {
            long newLastUpdated = getContentLastUpdated(torrent);

            long diff = newLastUpdated - oldLastUpdated;
            log(
                torrent,
                "Last Updated: new "
                    + new Date(newLastUpdated)
                    + ";old "
                    + new Date(oldLastUpdated)
                    + ";diff="
                    + diff);
            if (diff > 0 && oldLastUpdated != 0) {
              diff *= 2;
              if (diff < MIN_MD_REFRESH_MS) {
                diff = MIN_MD_REFRESH_MS;
              } else if (diff > MAX_MD_REFRESH_MS) {
                diff = MAX_MD_REFRESH_MS;
              }
              refreshOn = SystemTime.getOffsetTime(diff);
            } else {
              refreshOn = SystemTime.getCurrentTime() + (7 * 24 * 60 * 60 * 1000L);
            }
          }

          log(torrent, "got MD. Next refresh in " + (refreshOn - SystemTime.getCurrentTime()));
          setMetaDataRefreshOn(torrent, refreshOn);
          SimpleTimer.addEvent(
              "Update MD",
              refreshOn,
              new TimerEventPerformer() {
                public void perform(TimerEvent event) {
                  PlatformTorrentUtils.updateMetaData(torrentFinal, 15000);
                }
              });
        }
      } else if (torrent != null) {
        long refreshOn = SystemTime.getCurrentTime() + (30 * 24 * 60 * 60 * 1000L);
        setMetaDataRefreshOn(torrent, refreshOn);
        log(torrent, "no hash in reply. Next refresh on " + new Date(refreshOn));
      }
    }
  }
Пример #18
0
  public static void launch(String[] args) {
    if (Launcher.checkAndLaunch(PluginLauncherImpl.class, args)) return;
    // This *has* to be done first as it sets system properties that are read and cached by Java

    COConfigurationManager.preInitialise();

    final LoggerChannelListener listener =
        new LoggerChannelListener() {
          public void messageLogged(int type, String content) {
            log(content, false);
          }

          public void messageLogged(String str, Throwable error) {
            log(str, true);

            StringWriter sw = new StringWriter();

            PrintWriter pw = new PrintWriter(sw);

            error.printStackTrace(pw);

            pw.flush();

            log(sw.toString(), true);
          }

          protected synchronized void log(String str, boolean stdout) {
            File log_file = getApplicationFile("launch.log");

            PrintWriter pw = null;

            try {
              pw = new PrintWriter(new FileWriter(log_file, true));

              if (str.endsWith("\n")) {

                if (stdout) {
                  System.err.print("PluginLauncher: " + str);
                }

                pw.print(str);

              } else {

                if (stdout) {
                  System.err.println("PluginLauncher: " + str);
                }

                pw.println(str);
              }

            } catch (Throwable e) {

            } finally {

              if (pw != null) {

                pw.close();
              }
            }
          }
        };

    LaunchablePlugin[] launchables = findLaunchablePlugins(listener);

    if (launchables.length == 0) {

      listener.messageLogged(LoggerChannel.LT_ERROR, "No launchable plugins found");

      return;

    } else if (launchables.length > 1) {

      listener.messageLogged(
          LoggerChannel.LT_ERROR, "Multiple launchable plugins found, running first");
    }

    try {
      // set default details for restarter

      SystemProperties.setApplicationEntryPoint("org.gudy.azureus2.plugins.PluginLauncher");

      launchables[0].setDefaults(args);

      // see if we're a secondary instance

      if (PluginSingleInstanceHandler.process(listener, args)) {

        return;
      }
      // we have to run the core startup on a separate thread and then effectively pass "this
      // thread"
      // through to the launchable "process" method

      Thread core_thread =
          new Thread("PluginLauncher") {
            public void run() {
              try {
                // give 'process' call below some time to start up

                Thread.sleep(500);

                AzureusCore azureus_core = AzureusCoreFactory.create();

                azureus_core.start();

              } catch (Throwable e) {

                listener.messageLogged("PluginLauncher: launch fails", e);
              }
            }
          };

      core_thread.setDaemon(true);

      core_thread.start();

      boolean restart = false;

      boolean process_succeeded = false;

      try {
        restart = launchables[0].process();

        process_succeeded = true;

      } finally {

        try {
          if (restart) {

            AzureusCoreFactory.getSingleton().restart();

          } else {

            AzureusCoreFactory.getSingleton().stop();
          }
        } catch (Throwable e) {

          // only report this exception if we're not already failing

          if (process_succeeded) {

            throw (e);
          }
        }
      }

    } catch (Throwable e) {

      listener.messageLogged("PluginLauncher: launch fails", e);
    }
  }
Пример #19
0
  protected void testMessaging() {
    try {
      AzureusCoreFactory.getSingleton()
          .getCryptoManager()
          .addPasswordHandler(
              new CryptoManagerPasswordHandler() {
                public int getHandlerType() {
                  return (HANDLER_TYPE_USER);
                }

                public passwordDetails getPassword(
                    int handler_type, int action_type, boolean last_pw_incorrect, String reason) {
                  System.out.println("CryptoPassword (" + reason + ")");

                  return (new passwordDetails() {
                    public char[] getPassword() {
                      return ("changeit".toCharArray());
                    }

                    public int getPersistForSeconds() {
                      return (0);
                    }
                  });
                }

                public void passwordOK(int handler_type, passwordDetails details) {}
              });

      final SESecurityManager sec_man = plugin_interface.getUtilities().getSecurityManager();

      final SEPublicKey my_key = sec_man.getPublicKey(SEPublicKey.KEY_TYPE_ECC_192, "test");

      final int stream_crypto = MessageManager.STREAM_ENCRYPTION_RC4_REQUIRED;
      final boolean use_sts = true;
      final int block_crypto = SESecurityManager.BLOCK_ENCRYPTION_AES;

      GenericMessageRegistration reg =
          plugin_interface
              .getMessageManager()
              .registerGenericMessageType(
                  "GENTEST",
                  "Gen test desc",
                  stream_crypto,
                  new GenericMessageHandler() {
                    public boolean accept(GenericMessageConnection connection)
                        throws MessageException {
                      System.out.println("accept");

                      try {
                        if (use_sts) {

                          connection =
                              sec_man.getSTSConnection(
                                  connection,
                                  my_key,
                                  new SEPublicKeyLocator() {
                                    public boolean accept(Object context, SEPublicKey other_key) {
                                      System.out.println("acceptKey");

                                      return (true);
                                    }
                                  },
                                  "test",
                                  block_crypto);
                        }

                        connection.addListener(
                            new GenericMessageConnectionListener() {
                              public void connected(GenericMessageConnection connection) {}

                              public void receive(
                                  GenericMessageConnection connection, PooledByteBuffer message)
                                  throws MessageException {
                                System.out.println("receive: " + message.toByteArray().length);

                                PooledByteBuffer reply =
                                    plugin_interface
                                        .getUtilities()
                                        .allocatePooledByteBuffer(
                                            new byte[connection.getMaximumMessageSize()]);

                                connection.send(reply);
                              }

                              public void failed(
                                  GenericMessageConnection connection, Throwable error)
                                  throws MessageException {
                                System.out.println("Responder connection error:");

                                error.printStackTrace();
                              }
                            });

                      } catch (Throwable e) {

                        connection.close();

                        e.printStackTrace();
                      }

                      return (true);
                    }
                  });

      InetSocketAddress tcp_target = new InetSocketAddress("127.0.0.1", 6889);
      InetSocketAddress udp_target = new InetSocketAddress("212.159.18.92", 6881);

      GenericMessageEndpoint endpoint = reg.createEndpoint(tcp_target);

      endpoint.addTCP(tcp_target);
      endpoint.addUDP(udp_target);

      while (true) {

        try {
          for (int i = 0; i < 1000; i++) {

            System.out.println("Test: initiating connection");

            final AESemaphore sem = new AESemaphore("wait!");

            GenericMessageConnection con = reg.createConnection(endpoint);

            if (use_sts) {

              con =
                  sec_man.getSTSConnection(
                      con,
                      my_key,
                      new SEPublicKeyLocator() {
                        public boolean accept(Object context, SEPublicKey other_key) {
                          System.out.println("acceptKey");

                          return (true);
                        }
                      },
                      "test",
                      block_crypto);
            }

            con.addListener(
                new GenericMessageConnectionListener() {
                  public void connected(GenericMessageConnection connection) {
                    System.out.println("connected");

                    PooledByteBuffer data =
                        plugin_interface.getUtilities().allocatePooledByteBuffer("1234".getBytes());

                    try {
                      connection.send(data);

                    } catch (Throwable e) {

                      e.printStackTrace();
                    }
                  }

                  public void receive(GenericMessageConnection connection, PooledByteBuffer message)
                      throws MessageException {
                    System.out.println("receive: " + message.toByteArray().length);

                    try {
                      Thread.sleep(30000);
                    } catch (Throwable e) {

                    }

                    /*
                    PooledByteBuffer	reply =
                    	plugin_interface.getUtilities().allocatePooledByteBuffer( new byte[16*1024]);


                    connection.send( reply );
                    */

                    System.out.println("closing connection");

                    connection.close();

                    sem.release();
                  }

                  public void failed(GenericMessageConnection connection, Throwable error)
                      throws MessageException {
                    System.out.println("Initiator connection error:");

                    error.printStackTrace();

                    sem.release();
                  }
                });

            con.connect();

            sem.reserve();

            Thread.sleep(1000);
          }

        } catch (Throwable e) {

          e.printStackTrace();

          try {
            System.out.println("Sleeping before retrying");

            Thread.sleep(30000);

          } catch (Throwable f) {
          }
        }
      }
    } catch (Throwable e) {

      e.printStackTrace();
    }
  }
  /**
   * Construct the default version check message.
   *
   * @return message to send
   */
  public static Map constructVersionCheckMessage(String reason) {

    // only send if anonymous-check flag is not set

    boolean send_info = COConfigurationManager.getBooleanParameter("Send Version Info");

    Map message = new HashMap();

    // always send
    message.put("appid", SystemProperties.getApplicationIdentifier());
    message.put("appname", SystemProperties.getApplicationName());
    message.put("version", Constants.AZUREUS_VERSION);

    String sub_ver = Constants.AZUREUS_SUBVER;

    if (sub_ver.length() > 0) {
      message.put("subver", sub_ver);
    }

    if (COConfigurationManager.getBooleanParameter("Beta Programme Enabled")) {

      message.put("beta_prog", "true");
    }

    message.put("ui", COConfigurationManager.getStringParameter("ui", "unknown"));
    message.put("os", Constants.OSName);
    message.put("os_version", System.getProperty("os.version"));
    message.put(
        "os_arch", System.getProperty("os.arch")); // see http://lopica.sourceforge.net/os.html

    boolean using_phe =
        COConfigurationManager.getBooleanParameter("network.transport.encrypted.require");
    message.put("using_phe", using_phe ? new Long(1) : new Long(0));

    // swt stuff
    try {
      Class c = Class.forName("org.eclipse.swt.SWT");

      String swt_platform =
          (String) c.getMethod("getPlatform", new Class[] {}).invoke(null, new Object[] {});
      message.put("swt_platform", swt_platform);

      Integer swt_version =
          (Integer) c.getMethod("getVersion", new Class[] {}).invoke(null, new Object[] {});
      message.put("swt_version", new Long(swt_version.longValue()));

      if (send_info) {
        c = Class.forName("org.gudy.azureus2.ui.swt.mainwindow.MainWindow");
        if (c != null) {
          c.getMethod("addToVersionCheckMessage", new Class[] {Map.class})
              .invoke(null, new Object[] {message});
        }
      }
    } catch (ClassNotFoundException e) {
      /* ignore */
    } catch (NoClassDefFoundError er) {
      /* ignore */
    } catch (InvocationTargetException err) {
      /* ignore */
    } catch (Throwable t) {
      t.printStackTrace();
    }

    int last_send_time = COConfigurationManager.getIntParameter("Send Version Info Last Time", -1);
    int current_send_time = (int) (SystemTime.getCurrentTime() / 1000);
    COConfigurationManager.setParameter("Send Version Info Last Time", current_send_time);

    String id = COConfigurationManager.getStringParameter("ID", null);

    if (id != null && send_info) {
      message.put("id", id);

      try {
        byte[] id2 = CryptoManagerFactory.getSingleton().getSecureID();

        message.put("id2", id2);

      } catch (Throwable e) {
      }

      if (last_send_time != -1 && last_send_time < current_send_time) {
        // time since last
        message.put("tsl", new Long(current_send_time - last_send_time));
      }

      message.put("reason", reason);

      String java_version = System.getProperty("java.version");
      if (java_version == null) {
        java_version = "unknown";
      }
      message.put("java", java_version);

      String java_vendor = System.getProperty("java.vm.vendor");
      if (java_vendor == null) {
        java_vendor = "unknown";
      }
      message.put("javavendor", java_vendor);

      long max_mem = Runtime.getRuntime().maxMemory() / (1024 * 1024);
      message.put("javamx", new Long(max_mem));

      String java_rt_name = System.getProperty("java.runtime.name");
      if (java_rt_name != null) {
        message.put("java_rt_name", java_rt_name);
      }

      String java_rt_version = System.getProperty("java.runtime.version");
      if (java_rt_version != null) {
        message.put("java_rt_version", java_rt_version);
      }

      OverallStats stats = StatsFactory.getStats();

      if (stats != null) {

        // long total_bytes_downloaded 	= stats.getDownloadedBytes();
        // long total_bytes_uploaded		= stats.getUploadedBytes();
        long total_uptime = stats.getTotalUpTime();

        // removed due to complaints about anonymous stats collection
        // message.put( "total_bytes_downloaded", new Long( total_bytes_downloaded ) );
        // message.put( "total_bytes_uploaded", new Long( total_bytes_uploaded ) );
        message.put("total_uptime", new Long(total_uptime));
        // message.put( "dlstats", stats.getDownloadStats());
      }

      try {
        NetworkAdminASN current_asn = NetworkAdmin.getSingleton().getCurrentASN();

        String as = current_asn.getAS();

        message.put("ip_as", current_asn.getAS());

        String asn = current_asn.getASName();

        if (asn.length() > 64) {

          asn = asn.substring(0, 64);
        }

        message.put("ip_asn", asn);

      } catch (Throwable e) {

        Debug.out(e);
      }

      // send locale, so we can determine which languages need attention
      message.put("locale", Locale.getDefault().toString());
      String originalLocale =
          System.getProperty("user.language") + "_" + System.getProperty("user.country");
      String variant = System.getProperty("user.variant");
      if (variant != null && variant.length() > 0) {
        originalLocale += "_" + variant;
      }
      message.put("orig_locale", originalLocale);

      // We may want to reply differently if the user is in Beginner mode vs Advanced
      message.put("user_mode", COConfigurationManager.getIntParameter("User Mode", -1));

      Set<String> features = UtilitiesImpl.getFeaturesInstalled();

      if (features.size() > 0) {

        String str = "";

        for (String f : features) {
          str += (str.length() == 0 ? "" : ",") + f;
        }

        message.put("vzfeatures", str);
      }

      try {
        if (AzureusCoreFactory.isCoreAvailable()) {

          // installed plugin IDs
          PluginInterface[] plugins =
              AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces();

          List pids = new ArrayList();

          List vs_data = new ArrayList();

          for (int i = 0; i < plugins.length; i++) {

            PluginInterface plugin = plugins[i];

            String pid = plugin.getPluginID();

            String info = plugin.getPluginconfig().getPluginStringParameter("plugin.info");

            // filter out built-in and core ones
            if ((info != null && info.length() > 0)
                || (!pid.startsWith("<")
                    && !pid.startsWith("azbp")
                    && !pid.startsWith("azupdater")
                    && !pid.startsWith("azplatform")
                    && !pids.contains(pid))) {

              if (info != null && info.length() > 0) {

                if (info.length() < 256) {

                  pid += ":" + info;

                } else {

                  Debug.out("Plugin '" + pid + "' reported excessive info string '" + info + "'");
                }
              }

              pids.add(pid);
            }

            Map data =
                plugin.getPluginconfig().getPluginMapParameter("plugin.versionserver.data", null);

            if (data != null) {

              Map payload = new HashMap();

              byte[] data_bytes = BEncoder.encode(data);

              if (data_bytes.length > 16 * 1024) {

                Debug.out(
                    "Plugin '"
                        + pid
                        + "' reported excessive version server data (length="
                        + data_bytes.length
                        + ")");

                payload.put("error", "data too long: " + data_bytes.length);

              } else {

                payload.put("data", data_bytes);
              }

              payload.put("id", pid);
              payload.put("version", plugin.getPluginVersion());

              vs_data.add(payload);
            }
          }
          message.put("plugins", pids);

          if (vs_data.size() > 0) {

            message.put("plugin_data", vs_data);
          }
        }
      } catch (Throwable e) {

        Debug.out(e);
      }
    }

    return message;
  }