public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) {
    if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) {
      return IdeaPluginDescriptorImpl.EMPTY_ARRAY;
    }

    final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>();

    int pluginsCount =
        countPlugins(PathManager.getPluginsPath())
            + countPlugins(PathManager.getPreinstalledPluginsPath());
    loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount);
    Application application = ApplicationManager.getApplication();
    boolean fromSources = false;
    if (application == null || !application.isUnitTestMode()) {
      int size = result.size();
      loadDescriptors(PathManager.getPreinstalledPluginsPath(), result, progress, pluginsCount);
      fromSources = size == result.size();
    }

    loadDescriptorsFromProperty(result);

    loadDescriptorsFromClassPath(result, fromSources ? progress : null);

    IdeaPluginDescriptorImpl[] pluginDescriptors =
        result.toArray(new IdeaPluginDescriptorImpl[result.size()]);
    try {
      Arrays.sort(pluginDescriptors, new PluginDescriptorComparator(pluginDescriptors));
    } catch (Exception e) {
      prepareLoadingPluginsErrorMessage(
          IdeBundle.message("error.plugins.were.not.loaded", e.getMessage()));
      getLogger().info(e);
      return findCorePlugin(pluginDescriptors);
    }
    return pluginDescriptors;
  }
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
 protected int runEclipse(String message, File location, String[] args, File extensions) {
   File root = new File(Activator.getBundleContext().getProperty("java.home"));
   root = new File(root, "bin");
   File exe = new File(root, "javaw.exe");
   if (!exe.exists()) exe = new File(root, "java");
   assertTrue("Java executable not found in: " + exe.getAbsolutePath(), exe.exists());
   List<String> command = new ArrayList<String>();
   Collections.addAll(
       command,
       new String[] {
         (new File(location == null ? output : location, getExeFolder() + "eclipse"))
             .getAbsolutePath(),
         "--launcher.suppressErrors",
         "-nosplash",
         "-vm",
         exe.getAbsolutePath()
       });
   Collections.addAll(command, args);
   Collections.addAll(command, new String[] {"-vmArgs", "-Dosgi.checkConfiguration=true"});
   // command-line if you want to run and allow a remote debugger to connect
   if (debug)
     Collections.addAll(
         command,
         new String[] {
           "-Xdebug", "-Xnoagent", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787"
         });
   int result = run(message, command.toArray(new String[command.size()]));
   // 13 means that we wrote something out in the log file.
   // so try and parse it and fail via that message if we can.
   if (result == 13) parseExitdata(message);
   return result;
 }
 /*
  * Run the reconciler to discover changes in the drop-ins folder and update the system state.
  */
 public void reconcile(String message, boolean clean) {
   List<String> args = new ArrayList<String>();
   args.add("-application");
   args.add("org.eclipse.equinox.p2.reconciler.application");
   if (clean) args.add("-clean");
   runEclipse(message, args.toArray(new String[args.size()]));
 }
Пример #5
0
  /**
   * Loads the declarations of the script engines declared in a property set
   *
   * @param props property set containing the configuration
   * @throws ConfigurationException if the scripting languages cannot be loaded
   */
  private void loadScriptingLanguages(Properties props) throws ConfigurationException {
    String strEngineList = loadProperty(props, SCRIPT_ENGINE_LIST_P);

    for (StringTokenizer engineTokenizer = new StringTokenizer(strEngineList);
        engineTokenizer.hasMoreTokens(); ) {
      String engineBaseItem = engineTokenizer.nextToken();
      String engineName = props.getProperty(engineBaseItem + ".name"); // $NON-NLS-1$
      String engineClass = props.getProperty(engineBaseItem + ".class"); // $NON-NLS-1$
      String engineExtProps = props.getProperty(engineBaseItem + ".extensions"); // $NON-NLS-1$
      String[] extArray = null;
      if (engineExtProps != null) {
        List<String> extList = new ArrayList<String>();
        for (StringTokenizer extTokenizer = new StringTokenizer(engineExtProps);
            extTokenizer.hasMoreTokens(); ) {
          String extension = extTokenizer.nextToken();
          ext = extension;
          extList.add(extension);
        }
        extArray = extList.toArray(new String[0]);
      }
      BSFManager.registerScriptingEngine(engineName, engineClass, extArray);
      System.out.println("Script " + engineName + " loaded"); // $NON-NLS-1$ //$NON-NLS-2$
    }

    defaultEngineName = loadProperty(props, DFLT_SCRIPT_ENGINE_P);
  }
 public Resolution(ExtendedResolver eres, Message query) {
   List l = eres.resolvers;
   resolvers = (Resolver[]) l.toArray(new Resolver[l.size()]);
   if (eres.loadBalance) {
     int nresolvers = resolvers.length;
     /*
      * Note: this is not synchronized, since the
      * worst thing that can happen is a random
      * ordering, which is ok.
      */
     int start = eres.lbStart++ % nresolvers;
     if (eres.lbStart > nresolvers) eres.lbStart %= nresolvers;
     if (start > 0) {
       Resolver[] shuffle = new Resolver[nresolvers];
       for (int i = 0; i < nresolvers; i++) {
         int pos = (i + start) % nresolvers;
         shuffle[i] = resolvers[pos];
       }
       resolvers = shuffle;
     }
   }
   sent = new int[resolvers.length];
   inprogress = new Object[resolvers.length];
   retries = eres.retries;
   this.query = query;
 }
Пример #7
0
 protected void fireDone(File fileDest) throws Exception {
   Object[] ls;
   synchronized (listeners) {
     ls = listeners.toArray();
   }
   for (int i = 0; i < ls.length; i++) {
     ((DownloadProgressEventListener) ls[i]).done(fileDest);
   }
 }
Пример #8
0
 protected void fireException(Exception ex) {
   Object[] ls;
   synchronized (listeners) {
     ls = listeners.toArray();
   }
   for (int i = 0; i < ls.length; i++) {
     ((DownloadProgressEventListener) ls[i]).exception(ex);
   }
 }
Пример #9
0
 protected void fireStarted() {
   Object[] ls;
   synchronized (listeners) {
     ls = listeners.toArray();
   }
   for (int i = 0; i < ls.length; i++) {
     ((DownloadProgressEventListener) ls[i]).started();
   }
 }
Пример #10
0
 protected void fireProgressChange(int progress, int max) {
   Object[] ls;
   synchronized (listeners) {
     ls = listeners.toArray();
   }
   for (int i = 0; i < ls.length; i++) {
     ((DownloadProgressEventListener) ls[i]).progressChange(progress, max);
   }
 }
 public static void initClassLoader(
     @NotNull ClassLoader parentLoader, @NotNull IdeaPluginDescriptorImpl descriptor) {
   final List<File> classPath = descriptor.getClassPath();
   final ClassLoader loader =
       createPluginClassLoader(
           classPath.toArray(new File[classPath.size()]),
           new ClassLoader[] {parentLoader},
           descriptor);
   descriptor.setLoader(loader, false);
 }
Пример #12
0
  /**
   * Gets the <tt>WebRtcDataStreamListener</tt>s added to this instance.
   *
   * @return the <tt>WebRtcDataStreamListener</tt>s added to this instance or <tt>null</tt> if there
   *     are no <tt>WebRtcDataStreamListener</tt>s added to this instance
   */
  private WebRtcDataStreamListener[] getChannelListeners() {
    WebRtcDataStreamListener[] ls;

    synchronized (listeners) {
      if (listeners.isEmpty()) {
        ls = null;
      } else {
        ls = listeners.toArray(new WebRtcDataStreamListener[listeners.size()]);
      }
    }
    return ls;
  }
Пример #13
0
 public static String[] split(String txt, char splitter) {
   if (txt == null || txt.equals("")) return new String[0];
   int n = txt.length();
   List<String> parts = new ArrayList<String>();
   for (int at = 0; at < n; ) {
     int i = txt.indexOf(splitter, at);
     if (i < 0) i = n;
     parts.add(txt.substring(at, i));
     at = i + 1;
   }
   return parts.toArray(new String[parts.size()]);
 }
Пример #14
0
 // get licensing features, with appropriate defaults
 @SuppressWarnings("unchecked")
 private void loadLicensingFeatures(Element licensingElt) {
   List<LicensingFeature> licensingFeats = new ArrayList<LicensingFeature>();
   boolean containsLexFeat = false;
   if (licensingElt != null) {
     for (Iterator<Element> it = licensingElt.getChildren("feat").iterator(); it.hasNext(); ) {
       Element featElt = it.next();
       String attr = featElt.getAttributeValue("attr");
       if (attr.equals("lex")) containsLexFeat = true;
       String val = featElt.getAttributeValue("val");
       List<String> alsoLicensedBy = null;
       String alsoVals = featElt.getAttributeValue("also-licensed-by");
       if (alsoVals != null) {
         alsoLicensedBy = Arrays.asList(alsoVals.split("\\s+"));
       }
       boolean licenseEmptyCats = true;
       boolean licenseMarkedCats = false;
       boolean instantiate = true;
       byte loc = LicensingFeature.BOTH;
       String lmc = featElt.getAttributeValue("license-marked-cats");
       if (lmc != null) {
         licenseMarkedCats = Boolean.valueOf(lmc).booleanValue();
         // change defaults
         licenseEmptyCats = false;
         loc = LicensingFeature.TARGET_ONLY;
         instantiate = false;
       }
       String lec = featElt.getAttributeValue("license-empty-cats");
       if (lec != null) {
         licenseEmptyCats = Boolean.valueOf(lec).booleanValue();
       }
       String inst = featElt.getAttributeValue("instantiate");
       if (inst != null) {
         instantiate = Boolean.valueOf(inst).booleanValue();
       }
       String locStr = featElt.getAttributeValue("location");
       if (locStr != null) {
         if (locStr.equals("target-only")) loc = LicensingFeature.TARGET_ONLY;
         if (locStr.equals("args-only")) loc = LicensingFeature.ARGS_ONLY;
         if (locStr.equals("both")) loc = LicensingFeature.BOTH;
       }
       licensingFeats.add(
           new LicensingFeature(
               attr, val, alsoLicensedBy, licenseEmptyCats, licenseMarkedCats, instantiate, loc));
     }
   }
   if (!containsLexFeat) {
     licensingFeats.add(LicensingFeature.defaultLexFeature);
   }
   _licensingFeatures = new LicensingFeature[licensingFeats.size()];
   licensingFeats.toArray(_licensingFeatures);
 }
Пример #15
0
 private static final URL[] locateProtocolJars() {
   File protocolsDirectory = new File("protocols");
   File[] files = protocolsDirectory.listFiles();
   if (files == null || files.length == 0) return new URL[0];
   List<URL> urls = new ArrayList<>();
   for (File file : files)
     if (file.getName().endsWith(".jar"))
       try {
         urls.add(file.toURI().toURL());
       } catch (MalformedURLException exception) {
       }
   return urls.toArray(new URL[urls.size()]);
 }
Пример #16
0
  /**
   * Loads the package information from configuration file and builds the list of the package to
   * load by default
   *
   * @param props the property set containing the package information
   */
  private void loadPackageInfo(Properties props) throws ConfigurationException {
    importPackageCmd = loadProperty(props, IMPORT_PKG_CMD_P);
    addClassPathCmd = loadProperty(props, ADD_CLASSPATH_CMD_P);
    parameterTag = loadProperty(props, PARAMETER_TAG_P);

    List<String> pkgList = new ArrayList<String>();
    for (StringTokenizer pkgTokenizer = new StringTokenizer(IMPORT_PKG_LST, IMPORT_PKG_LST_SEP);
        pkgTokenizer.hasMoreTokens(); ) {
      String packageName = pkgTokenizer.nextToken();
      pkgList.add(packageName);
    }
    if (defaultLanguage) pkgList.add("org.colombbus.tangara.en.*");
    else pkgList.add("org.colombbus.tangara." + getLanguage() + ".*");
    scriptImportPkgList = pkgList.toArray(scriptImportPkgList);
  }
Пример #17
0
  /**
   * Specifies the domains which will be appended to unqualified names before beginning the lookup
   * process. If this is not set, FindServer will be used. Unlike the Lookup setSearchPath function,
   * this will silently ignore invalid names.
   *
   * @see FindServer
   */
  public static synchronized void setSearchPath(String[] domains) {
    if (domains == null || domains.length == 0) {
      Lookup.setDefaultSearchPath((Name[]) null);
      return;
    }

    List l = new ArrayList();
    for (int i = 0; i < domains.length; i++) {
      try {
        l.add(Name.fromString(domains[i], Name.root));
      } catch (TextParseException e) {
      }
    }
    searchPath = (Name[]) l.toArray(new Name[l.size()]);
    Lookup.setDefaultSearchPath(searchPath);
  }
  static ClassLoader[] getParentLoaders(
      Map<PluginId, ? extends IdeaPluginDescriptor> idToDescriptorMap, PluginId[] pluginIds) {
    if (isUnitTestMode()) return new ClassLoader[0];
    final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
    for (final PluginId id : pluginIds) {
      IdeaPluginDescriptor pluginDescriptor = idToDescriptorMap.get(id);
      if (pluginDescriptor == null) {
        continue; // Might be an optional dependency
      }

      final ClassLoader loader = pluginDescriptor.getPluginClassLoader();
      if (loader == null) {
        getLogger().error("Plugin class loader should be initialized for plugin " + id);
      }
      classLoaders.add(loader);
    }
    return classLoaders.toArray(new ClassLoader[classLoaders.size()]);
  }
  @FXML
  private void OK_click(ActionEvent event) {
    logger.entry();
    FederateHandle federateHandle;
    LogEntry log = new LogEntry("4.9", "Join Federation Execution service");
    try {
      if (!FederateName.getText().isEmpty()) {
        log.getSuppliedArguments()
            .add(new ClassValuePair("Federate Name", String.class, FederateName.getText()));
      }
      log.getSuppliedArguments()
          .add(new ClassValuePair("Federate Type", String.class, FederateType.getText()));
      log.getSuppliedArguments()
          .add(
              new ClassValuePair(
                  "Federation Execution Name", String.class, FederationExecutionName.getText()));
      List<URL> foms = new ArrayList<>();
      int i = 1;
      for (File file : FomModuleDesignators.getFiles()) {
        foms.add(file.toURI().toURL());
        log.getSuppliedArguments()
            .add(
                new ClassValuePair(
                    "FOM Module Deisgnator " + i++, URL.class, file.toURI().toURL().toString()));
      }
      if (FederateName.getText().isEmpty() && FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(), FederationExecutionName.getText());
      } else if (FomModuleDesignators.getFileNames().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(), FederateType.getText(), FederationExecutionName.getText());
      } else if (FederateName.getText().isEmpty()) {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      } else {
        federateHandle =
            rtiAmb.joinFederationExecution(
                FederateName.getText(),
                FederateType.getText(),
                FederationExecutionName.getText(),
                foms.toArray(new URL[foms.size()]));
      }
      log.getReturnedArguments()
          .add(
              new ClassValuePair(
                  "Federate Handle", FederateHandle.class, federateHandle.toString()));
      log.setDescription("Federate joined federation execution successfully");
      log.setLogType(LogEntryType.REQUEST);
      logicalTimeFactory = rtiAmb.getTimeFactory();
      currentLogicalTime = logicalTimeFactory.makeInitial();

      // subscribe to HLAcurrentFDD to retrieve FDD
      ObjectClassHandle FederationHandle =
          rtiAmb.getObjectClassHandle("HLAobjectRoot.HLAmanager.HLAfederation");
      currentFDDHandle = rtiAmb.getAttributeHandle(FederationHandle, "HLAcurrentFDD");
      AttributeHandleSet set = rtiAmb.getAttributeHandleSetFactory().create();
      set.add(currentFDDHandle);
      rtiAmb.subscribeObjectClassAttributes(FederationHandle, set);
      rtiAmb.requestAttributeValueUpdate(FederationHandle, set, null);
      // In case of HLA_EVOKED we require this line to receive the FDD
      rtiAmb.evokeMultipleCallbacks(
          .05,
          1); // evoke one callback will not be enough because the reflect attribute is the second
              // one
    } catch (CouldNotCreateLogicalTimeFactory
        | CallNotAllowedFromWithinCallback
        | CouldNotOpenFDD
        | ErrorReadingFDD
        | InconsistentFDD
        | FederateNameAlreadyInUse
        | FederateAlreadyExecutionMember
        | FederationExecutionDoesNotExist
        | SaveInProgress
        | RestoreInProgress
        | NotConnected
        | RTIinternalError ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.ERROR);
      logger.log(Level.ERROR, ex.getMessage(), ex);
    } catch (Exception ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.FATAL);
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logEntries.add(log);
    ((Stage) FederationExecutionName.getScene().getWindow()).close();
    logger.exit();
  }
  static void initializePlugins(@Nullable StartupProgress progress) {
    configureExtensions();

    final IdeaPluginDescriptorImpl[] pluginDescriptors = loadDescriptors(progress);

    final Class callerClass = ReflectionUtil.findCallerClass(1);
    assert callerClass != null;
    final ClassLoader parentLoader = callerClass.getClassLoader();

    final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>();
    final HashMap<String, String> disabledPluginNames = new HashMap<String, String>();
    for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) {
      if (descriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID)) {
        final List<String> modules = descriptor.getModules();
        if (modules != null) {
          ourAvailableModules.addAll(modules);
        }
      }

      if (!shouldSkipPlugin(descriptor, pluginDescriptors)) {
        result.add(descriptor);
      } else {
        descriptor.setEnabled(false);
        disabledPluginNames.put(descriptor.getPluginId().getIdString(), descriptor.getName());
        initClassLoader(parentLoader, descriptor);
      }
    }

    prepareLoadingPluginsErrorMessage(filterBadPlugins(result, disabledPluginNames));

    final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap =
        new HashMap<PluginId, IdeaPluginDescriptorImpl>();
    for (final IdeaPluginDescriptorImpl descriptor : result) {
      idToDescriptorMap.put(descriptor.getPluginId(), descriptor);
    }

    final IdeaPluginDescriptor corePluginDescriptor =
        idToDescriptorMap.get(PluginId.getId(CORE_PLUGIN_ID));
    assert corePluginDescriptor != null
        : CORE_PLUGIN_ID
            + " not found; platform prefix is "
            + System.getProperty(PlatformUtilsCore.PLATFORM_PREFIX_KEY);
    for (IdeaPluginDescriptorImpl descriptor : result) {
      if (descriptor != corePluginDescriptor) {
        descriptor.insertDependency(corePluginDescriptor);
      }
    }

    mergeOptionalConfigs(idToDescriptorMap);

    // sort descriptors according to plugin dependencies
    Collections.sort(result, getPluginDescriptorComparator(idToDescriptorMap));

    for (int i = 0; i < result.size(); i++) {
      ourId2Index.put(result.get(i).getPluginId(), i);
    }

    int i = 0;
    for (final IdeaPluginDescriptorImpl pluginDescriptor : result) {
      if (pluginDescriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID)
          || pluginDescriptor.isUseCoreClassLoader()) {
        pluginDescriptor.setLoader(parentLoader, true);
      } else {
        final List<File> classPath = pluginDescriptor.getClassPath();
        final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
        final ClassLoader[] parentLoaders = getParentLoaders(idToDescriptorMap, dependentPluginIds);

        final ClassLoader pluginClassLoader =
            createPluginClassLoader(
                classPath.toArray(new File[classPath.size()]),
                parentLoaders.length > 0 ? parentLoaders : new ClassLoader[] {parentLoader},
                pluginDescriptor);
        pluginDescriptor.setLoader(pluginClassLoader, true);
      }

      pluginDescriptor.registerExtensions();
      if (progress != null) {
        progress.showProgress(
            "", PLUGINS_PROGRESS_MAX_VALUE + (i++ / (float) result.size()) * 0.35f);
      }
    }

    ourPlugins = pluginDescriptors;
  }
Пример #21
0
  public static URL[][] getAnnounceURLs() {
    String tracker_host = COConfigurationManager.getStringParameter("Tracker IP", "");

    List urls = new ArrayList();

    if (tracker_host.length() > 0) {

      if (COConfigurationManager.getBooleanParameter("Tracker Port Enable")) {

        int port = COConfigurationManager.getIntParameter("Tracker Port", TRHost.DEFAULT_PORT);

        try {
          List l = new ArrayList();

          l.add(
              new URL(
                  "http://" + UrlUtils.convertIPV6Host(tracker_host) + ":" + port + "/announce"));

          List ports =
              stringToPorts(COConfigurationManager.getStringParameter("Tracker Port Backups"));

          for (int i = 0; i < ports.size(); i++) {

            l.add(
                new URL(
                    "http://"
                        + UrlUtils.convertIPV6Host(tracker_host)
                        + ":"
                        + ((Integer) ports.get(i)).intValue()
                        + "/announce"));
          }

          urls.add(l);

        } catch (MalformedURLException e) {

          Debug.printStackTrace(e);
        }
      }

      if (COConfigurationManager.getBooleanParameter("Tracker Port SSL Enable")) {

        int port =
            COConfigurationManager.getIntParameter("Tracker Port SSL", TRHost.DEFAULT_PORT_SSL);

        try {
          List l = new ArrayList();

          l.add(
              new URL(
                  "https://" + UrlUtils.convertIPV6Host(tracker_host) + ":" + port + "/announce"));

          List ports =
              stringToPorts(COConfigurationManager.getStringParameter("Tracker Port SSL Backups"));

          for (int i = 0; i < ports.size(); i++) {

            l.add(
                new URL(
                    "https://"
                        + UrlUtils.convertIPV6Host(tracker_host)
                        + ":"
                        + ((Integer) ports.get(i)).intValue()
                        + "/announce"));
          }

          urls.add(l);

        } catch (MalformedURLException e) {

          Debug.printStackTrace(e);
        }
      }

      if (COConfigurationManager.getBooleanParameter("Tracker Port UDP Enable")) {

        int port = COConfigurationManager.getIntParameter("Tracker Port", TRHost.DEFAULT_PORT);

        boolean auth =
            COConfigurationManager.getBooleanParameter("Tracker Password Enable Torrent");

        try {
          List l = new ArrayList();

          l.add(
              new URL(
                  "udp://"
                      + UrlUtils.convertIPV6Host(tracker_host)
                      + ":"
                      + port
                      + "/announce"
                      + (auth ? "?auth" : "")));

          urls.add(l);

        } catch (MalformedURLException e) {

          Debug.printStackTrace(e);
        }
      }
    }

    URL[][] res = new URL[urls.size()][];

    for (int i = 0; i < urls.size(); i++) {

      List l = (List) urls.get(i);

      URL[] u = new URL[l.size()];

      l.toArray(u);

      res[i] = u;
    }

    return (res);
  }
  protected Object[] handleAnnounceAndScrape(
      String client_ip_address, PRUDPPacketRequest request, int request_type) throws Exception {
    if (!checkConnectionId(client_ip_address, request.getConnectionId())) {

      return (null);
    }

    List hashbytes = new ArrayList();
    HashWrapper peer_id = null;
    int port = 0;
    String event = null;

    long uploaded = 0;
    long downloaded = 0;
    long left = 0;
    int num_want = -1;

    String key = null;

    if (request_type == TRTrackerServerRequest.RT_ANNOUNCE) {

      if (PRUDPPacketTracker.VERSION == 1) {
        PRUDPPacketRequestAnnounce announce = (PRUDPPacketRequestAnnounce) request;

        hashbytes.add(announce.getHash());

        peer_id = new HashWrapper(announce.getPeerId());

        port = announce.getPort();

        int i_event = announce.getEvent();

        switch (i_event) {
          case PRUDPPacketRequestAnnounce.EV_STARTED:
            {
              event = "started";
              break;
            }
          case PRUDPPacketRequestAnnounce.EV_STOPPED:
            {
              event = "stopped";
              break;
            }
          case PRUDPPacketRequestAnnounce.EV_COMPLETED:
            {
              event = "completed";
              break;
            }
        }

        uploaded = announce.getUploaded();

        downloaded = announce.getDownloaded();

        left = announce.getLeft();

        num_want = announce.getNumWant();

        int i_ip = announce.getIPAddress();

        if (i_ip != 0) {

          client_ip_address = PRHelpers.intToAddress(i_ip);
        }
      } else {

        PRUDPPacketRequestAnnounce2 announce = (PRUDPPacketRequestAnnounce2) request;

        hashbytes.add(announce.getHash());

        peer_id = new HashWrapper(announce.getPeerId());

        port = announce.getPort();

        int i_event = announce.getEvent();

        switch (i_event) {
          case PRUDPPacketRequestAnnounce.EV_STARTED:
            {
              event = "started";
              break;
            }
          case PRUDPPacketRequestAnnounce.EV_STOPPED:
            {
              event = "stopped";
              break;
            }
          case PRUDPPacketRequestAnnounce.EV_COMPLETED:
            {
              event = "completed";
              break;
            }
        }

        uploaded = announce.getUploaded();

        downloaded = announce.getDownloaded();

        left = announce.getLeft();

        num_want = announce.getNumWant();

        int i_ip = announce.getIPAddress();

        if (i_ip != 0) {

          client_ip_address = PRHelpers.intToAddress(i_ip);
        }

        key = "" + announce.getKey();
      }
    } else {

      PRUDPPacketRequestScrape scrape = (PRUDPPacketRequestScrape) request;

      hashbytes.addAll(scrape.getHashes());
    }

    Map[] root_out = new Map[1];
    TRTrackerServerPeerImpl[] peer_out = new TRTrackerServerPeerImpl[1];

    TRTrackerServerTorrentImpl torrent =
        processTrackerRequest(
            server,
            "",
            root_out,
            peer_out,
            request_type,
            (byte[][]) hashbytes.toArray(new byte[0][0]),
            null,
            null,
            peer_id,
            false,
            TRTrackerServerTorrentImpl.COMPACT_MODE_NONE,
            key, // currently no "no_peer_id" / "compact" in the packet and anyway they aren't
                 // returned / key
            event,
            false,
            port,
            0,
            0,
            client_ip_address,
            client_ip_address,
            downloaded,
            uploaded,
            left,
            num_want,
            TRTrackerServerPeer.CRYPTO_NONE,
            (byte) 1,
            0,
            null);

    Map root = root_out[0];

    if (request_type == TRTrackerServerRequest.RT_ANNOUNCE) {

      if (PRUDPPacketTracker.VERSION == 1) {
        PRUDPPacketReplyAnnounce reply = new PRUDPPacketReplyAnnounce(request.getTransactionId());

        reply.setInterval(((Long) root.get("interval")).intValue());

        List peers = (List) root.get("peers");

        int[] addresses = new int[peers.size()];
        short[] ports = new short[addresses.length];

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

          Map peer = (Map) peers.get(i);

          addresses[i] = PRHelpers.addressToInt(new String((byte[]) peer.get("ip")));

          ports[i] = (short) ((Long) peer.get("port")).shortValue();
        }

        reply.setPeers(addresses, ports);

        return (new Object[] {reply, torrent});

      } else {

        PRUDPPacketReplyAnnounce2 reply = new PRUDPPacketReplyAnnounce2(request.getTransactionId());

        reply.setInterval(((Long) root.get("interval")).intValue());

        boolean local_scrape = client_ip_address.equals("127.0.0.1");

        Map scrape_details = torrent.exportScrapeToMap("", client_ip_address, !local_scrape);

        int seeders = ((Long) scrape_details.get("complete")).intValue();
        int leechers = ((Long) scrape_details.get("incomplete")).intValue();

        reply.setLeechersSeeders(leechers, seeders);

        List peers = (List) root.get("peers");

        int[] addresses = new int[peers.size()];
        short[] ports = new short[addresses.length];

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

          Map peer = (Map) peers.get(i);

          addresses[i] = PRHelpers.addressToInt(new String((byte[]) peer.get("ip")));

          ports[i] = (short) ((Long) peer.get("port")).shortValue();
        }

        reply.setPeers(addresses, ports);

        return (new Object[] {reply, torrent});
      }

    } else {

      if (PRUDPPacketTracker.VERSION == 1) {

        PRUDPPacketReplyScrape reply = new PRUDPPacketReplyScrape(request.getTransactionId());

        /*
        Long	interval = (Long)root.get("interval");

        if ( interval != null ){

        	reply.setInterval(interval.intValue());
        }
        */

        Map files = (Map) root.get("files");

        byte[][] hashes = new byte[files.size()][];
        int[] s_complete = new int[hashes.length];
        int[] s_downloaded = new int[hashes.length];
        int[] s_incomplete = new int[hashes.length];

        Iterator it = files.keySet().iterator();

        int pos = 0;

        while (it.hasNext()) {

          String hash_str = (String) it.next();

          hashes[pos] = hash_str.getBytes(Constants.BYTE_ENCODING);

          Map details = (Map) files.get(hash_str);

          s_complete[pos] = ((Long) details.get("complete")).intValue();
          s_incomplete[pos] = ((Long) details.get("incomplete")).intValue();
          s_downloaded[pos] = ((Long) details.get("downloaded")).intValue();

          pos++;
        }

        reply.setDetails(hashes, s_complete, s_downloaded, s_incomplete);

        return (new Object[] {reply, torrent});

      } else {

        PRUDPPacketReplyScrape2 reply = new PRUDPPacketReplyScrape2(request.getTransactionId());

        /*
        Long	interval = (Long)root.get("interval");

        if ( interval != null ){

        	reply.setInterval(interval.intValue());
        }
        */

        Map files = (Map) root.get("files");

        int[] s_complete = new int[files.size()];
        int[] s_downloaded = new int[s_complete.length];
        int[] s_incomplete = new int[s_complete.length];

        Iterator it = files.keySet().iterator();

        int pos = 0;

        while (it.hasNext()) {

          String hash_str = (String) it.next();

          Map details = (Map) files.get(hash_str);

          s_complete[pos] = ((Long) details.get("complete")).intValue();
          s_incomplete[pos] = ((Long) details.get("incomplete")).intValue();
          s_downloaded[pos] = ((Long) details.get("downloaded")).intValue();

          pos++;
        }

        reply.setDetails(s_complete, s_downloaded, s_incomplete);

        return (new Object[] {reply, torrent});
      }
    }
  }
Пример #23
0
  private static LaunchablePlugin[] findLaunchablePlugins(LoggerChannelListener listener) {
    // CAREFUL - this is called BEFORE any AZ initialisation has been performed and must
    // therefore NOT use anything that relies on this (such as logging, debug....)

    List res = new ArrayList();

    File app_dir = getApplicationFile("plugins");

    if (!(app_dir.exists()) && app_dir.isDirectory()) {

      listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' not found");

      return (new LaunchablePlugin[0]);
    }

    File[] plugins = app_dir.listFiles();

    if (plugins == null || plugins.length == 0) {

      listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' empty");

      return (new LaunchablePlugin[0]);
    }

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

      File plugin_dir = plugins[i];

      if (!plugin_dir.isDirectory()) {

        continue;
      }

      try {

        ClassLoader classLoader = PluginLauncherImpl.class.getClassLoader();

        ClassLoader root_cl = classLoader;

        File[] contents = plugin_dir.listFiles();

        if (contents == null || contents.length == 0) {

          continue;
        }

        // take only the highest version numbers of jars that look versioned

        String[] plugin_version = {null};
        String[] plugin_id = {null};

        contents = getHighestJarVersions(contents, plugin_version, plugin_id, true);

        for (int j = 0; j < contents.length; j++) {

          classLoader = addFileToClassPath(root_cl, classLoader, contents[j]);
        }

        Properties props = new Properties();

        File properties_file = new File(plugin_dir, "plugin.properties");

        // if properties file exists on its own then override any properties file
        // potentially held within a jar

        if (properties_file.exists()) {

          FileInputStream fis = null;

          try {
            fis = new FileInputStream(properties_file);

            props.load(fis);

          } finally {

            if (fis != null) {

              fis.close();
            }
          }
        } else {

          if (classLoader instanceof URLClassLoader) {

            URLClassLoader current = (URLClassLoader) classLoader;

            URL url = current.findResource("plugin.properties");

            if (url != null) {

              props.load(url.openStream());
            }
          }
        }

        String plugin_class = (String) props.get("plugin.class");

        // don't support multiple launchable plugins

        if (plugin_class == null || plugin_class.indexOf(';') != -1) {

          continue;
        }

        Class c = classLoader.loadClass(plugin_class);

        Plugin plugin = (Plugin) c.newInstance();

        if (plugin instanceof LaunchablePlugin) {

          preloaded_plugins.put(plugin_class, plugin);

          res.add(plugin);
        }
      } catch (Throwable e) {

        listener.messageLogged("Load of plugin in '" + plugin_dir + "' fails", e);
      }
    }

    LaunchablePlugin[] x = new LaunchablePlugin[res.size()];

    res.toArray(x);

    return (x);
  }
Пример #24
0
  public static File[] getHighestJarVersions(
      File[] files,
      String[] version_out,
      String[] id_out, // currently the version of last versioned jar found...
      boolean discard_non_versioned_when_versioned_found) {
    // WARNING!!!!
    // don't use Debug/lglogger here as we can be called before AZ has been initialised

    List res = new ArrayList();
    Map version_map = new HashMap();

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

      File f = files[i];

      String name = f.getName().toLowerCase();

      if (name.endsWith(".jar")) {

        int cvs_pos = name.lastIndexOf("_cvs");

        int sep_pos;

        if (cvs_pos <= 0) sep_pos = name.lastIndexOf("_");
        else sep_pos = name.lastIndexOf("_", cvs_pos - 1);

        if (sep_pos == -1
            || sep_pos == name.length() - 1
            || !Character.isDigit(name.charAt(sep_pos + 1))) {

          // not a versioned jar

          res.add(f);

        } else {

          String prefix = name.substring(0, sep_pos);

          String version =
              name.substring(sep_pos + 1, (cvs_pos <= 0) ? name.length() - 4 : cvs_pos);

          String prev_version = (String) version_map.get(prefix);

          if (prev_version == null) {

            version_map.put(prefix, version);

          } else {

            if (PluginUtils.comparePluginVersions(prev_version, version) < 0) {

              version_map.put(prefix, version);
            }
          }
        }
      }
    }

    // If any of the jars are versioned then the assumption is that all of them are
    // For migration purposes (i.e. on the first real introduction of the update versioning
    // system) we drop all non-versioned jars from the set

    if (version_map.size() > 0 && discard_non_versioned_when_versioned_found) {

      res.clear();
    }

    // fix a problem we had with the rating plugin. It went out as rating_x.jar when it should
    // have been azrating_x.jar. If there are any azrating entries then we remove any rating ones
    // to avoid load problems

    if (version_map.containsKey("azrating")) {

      version_map.remove("rating");
    }

    Iterator it = version_map.keySet().iterator();

    while (it.hasNext()) {

      String prefix = (String) it.next();
      String version = (String) version_map.get(prefix);

      String target = prefix + "_" + version;

      version_out[0] = version;
      id_out[0] = prefix;

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

        File f = files[i];

        String lc_name = f.getName().toLowerCase();

        if (lc_name.equals(target + ".jar") || lc_name.equals(target + "_cvs.jar")) {

          res.add(f);

          break;
        }
      }
    }

    File[] res_array = new File[res.size()];

    res.toArray(res_array);

    return (res_array);
  }
 /** Returns all resolvers used by this ExtendedResolver */
 public Resolver[] getResolvers() {
   return (Resolver[]) resolvers.toArray(new Resolver[resolvers.size()]);
 }