private static boolean checkDependants(
      final IdeaPluginDescriptor pluginDescriptor,
      final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor,
      final Condition<PluginId> check,
      final Set<PluginId> processed) {
    processed.add(pluginDescriptor.getPluginId());
    final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
    final Set<PluginId> optionalDependencies =
        new HashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds()));
    for (final PluginId dependentPluginId : dependentPluginIds) {
      if (processed.contains(dependentPluginId)) continue;

      // TODO[yole] should this condition be a parameter?
      if (isModuleDependency(dependentPluginId)
          && (ourAvailableModules.isEmpty()
              || ourAvailableModules.contains(dependentPluginId.getIdString()))) {
        continue;
      }
      if (!optionalDependencies.contains(dependentPluginId)) {
        if (!check.value(dependentPluginId)) {
          return false;
        }
        final IdeaPluginDescriptor dependantPluginDescriptor =
            pluginId2Descriptor.fun(dependentPluginId);
        if (dependantPluginDescriptor != null
            && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) {
          return false;
        }
      }
    }
    return true;
  }
예제 #2
0
 public Set<String> listResources(String subdir) {
   try {
     Set<String> result = new HashSet<String>();
     if (resourceURL != null) {
       String protocol = resourceURL.getProtocol();
       if (protocol.equals("jar")) {
         String resPath = resourceURL.getPath();
         int pling = resPath.lastIndexOf("!");
         URL jarURL = new URL(resPath.substring(0, pling));
         String resDirInJar = resPath.substring(pling + 2);
         String prefix = resDirInJar + subdir + "/";
         // System.out.printf("BaseMod.listResources: looking for names starting with %s\n",
         // prefix);
         JarFile jar = new JarFile(new File(jarURL.toURI()));
         Enumeration<JarEntry> entries = jar.entries();
         while (entries.hasMoreElements()) {
           String name = entries.nextElement().getName();
           if (name.startsWith(prefix) && !name.endsWith("/") && !name.contains("/.")) {
             // System.out.printf("BaseMod.listResources: name = %s\n", name);
             result.add(name.substring(prefix.length()));
           }
         }
       } else throw new RuntimeException("Resource URL protocol " + protocol + " not supported");
     }
     return result;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
예제 #3
0
  private void checkStartup(
      Map<String, ServiceData> map,
      List<ServiceData> start,
      ServiceData sd,
      Set<ServiceData> cyclic) {
    if (sd.after.isEmpty() || start.contains(sd)) return;

    if (cyclic.contains(sd)) {
      reporter.error("Cyclic dependency for " + sd.name);
      return;
    }

    cyclic.add(sd);

    for (String dependsOn : sd.after) {
      if (dependsOn.equals("boot")) continue;

      ServiceData deps = map.get(dependsOn);
      if (deps == null) {
        reporter.error("No such service " + dependsOn + " but " + sd.name + " depends on it");
      } else {
        checkStartup(map, start, deps, cyclic);
      }
    }
    start.add(sd);
  }
  private static void check(String what, MBeanNotificationInfo[] mbnis) {
    System.out.print(what + ": checking notification info: ");

    if (mbnis.length == 0) {
      System.out.println("NONE (suspicious)");
      suspicious.add(what);
      return;
    }

    // Each MBeanNotificationInfo.getName() should be an existent
    // Java class that is Notification or a subclass of it
    for (int j = 0; j < mbnis.length; j++) {
      String notifClassName = mbnis[j].getName();
      Class notifClass;
      try {
        notifClass = Class.forName(notifClassName);
      } catch (Exception e) {
        System.out.print("FAILED(" + notifClassName + ": " + e + ") ");
        failed.add(what);
        continue;
      }
      if (!Notification.class.isAssignableFrom(notifClass)) {
        System.out.print("FAILED(" + notifClassName + ": not a Notification) ");
        failed.add(what);
        continue;
      }
      System.out.print("OK(" + notifClassName + ") ");
    }
    System.out.println();
  }
예제 #5
0
 static {
   Set<EncodingRule> rules = new HashSet<EncodingRule>();
   rules.add(new EncodingRule("*", "%2A"));
   rules.add(new EncodingRule("+", "%20"));
   rules.add(new EncodingRule("%7E", "~"));
   ENCODING_RULES = Collections.unmodifiableSet(rules);
 }
예제 #6
0
  public static Set toSet(Model m) throws ModelException {

    Set s = new HashSet();
    Enumeration en = m.elements();
    while (en.hasMoreElements()) s.add(en.nextElement());
    return s;
  }
예제 #7
0
  // returns a macro adder for the given morph item
  private MacroAdder getMacAdder(MorphItem mi) {

    // check map
    MacroAdder retval = macAdderMap.get(mi);
    if (retval != null) return retval;

    // set up macro adder
    IntHashSetMap macrosFromLex = new IntHashSetMap();
    String[] newMacroNames = mi.getMacros();
    List<MacroItem> macroItems = new ArrayList<MacroItem>();
    for (int i = 0; i < newMacroNames.length; i++) {
      Set<FeatureStructure> featStrucs = (Set<FeatureStructure>) _macros.get(newMacroNames[i]);
      if (featStrucs != null) {
        for (Iterator<FeatureStructure> fsIt = featStrucs.iterator(); fsIt.hasNext(); ) {
          FeatureStructure fs = fsIt.next();
          macrosFromLex.put(fs.getIndex(), fs);
        }
      }
      MacroItem macroItem = _macroItems.get(newMacroNames[i]);
      if (macroItem != null) {
        macroItems.add(macroItem);
      } else {
        // should be checked earlier too
        System.err.println(
            "Warning: macro " + newMacroNames[i] + " not found for word '" + mi.getWord() + "'");
      }
    }
    retval = new MacroAdder(macrosFromLex, macroItems);

    // update map and return
    macAdderMap.put(mi, retval);
    return retval;
  }
  /** TODO */
  public AnnotatedLexicalEntry integrate(LexicalEntry e) {

    String gloss = e.getAnnotations().get(CrownAnnotations.Gloss.class);
    POS pos = e.getPos();

    List<Relation> relations = e.getAnnotations().get(CrownAnnotations.Relations.class);

    // Try getting a synonym operation first
    Set<String> synonyms = new HashSet<String>();
    for (Relation r : relations) {
      if (r.getType().equals(Relation.RelationType.SYNONYM)) synonyms.add(r.getTargetLemma());
    }
    if (synonyms.size() > 0) {
      Duple<CrownOperations.Reason, ISynset> synonymOp =
          getEstimatedSynonym(e.getLemma(), synonyms, pos, gloss);

      if (synonymOp != null && synonymOp.y != null) {
        AnnotatedLexicalEntry ale = new AnnotatedLexicalEntryImpl(e);
        ale.setOp(CrownOperations.Synonym.class, synonymOp.x, synonymOp.y);
        return ale;
      }
    }

    return null;
  }
  public Set<String> getOperatorClasses(String parent, String searchTerm)
      throws ClassNotFoundException {
    if (CollectionUtils.isEmpty(operatorClassNames)) {
      loadOperatorClass();
    }
    if (parent == null) {
      parent = Operator.class.getName();
    } else {
      if (!typeGraph.isAncestor(Operator.class.getName(), parent)) {
        throw new IllegalArgumentException("Argument must be a subclass of Operator class");
      }
    }

    Set<String> filteredClass =
        Sets.filter(
            operatorClassNames,
            new Predicate<String>() {
              @Override
              public boolean apply(String className) {
                OperatorClassInfo oci = classInfo.get(className);
                return oci == null || !oci.tags.containsKey("@omitFromUI");
              }
            });

    if (searchTerm == null && parent.equals(Operator.class.getName())) {
      return filteredClass;
    }

    if (searchTerm != null) {
      searchTerm = searchTerm.toLowerCase();
    }

    Set<String> result = new HashSet<String>();
    for (String clazz : filteredClass) {
      if (parent.equals(Operator.class.getName()) || typeGraph.isAncestor(parent, clazz)) {
        if (searchTerm == null) {
          result.add(clazz);
        } else {
          if (clazz.toLowerCase().contains(searchTerm)) {
            result.add(clazz);
          } else {
            OperatorClassInfo oci = classInfo.get(clazz);
            if (oci != null) {
              if (oci.comment != null && oci.comment.toLowerCase().contains(searchTerm)) {
                result.add(clazz);
              } else {
                for (Map.Entry<String, String> entry : oci.tags.entrySet()) {
                  if (entry.getValue().toLowerCase().contains(searchTerm)) {
                    result.add(clazz);
                    break;
                  }
                }
              }
            }
          }
        }
      }
    }
    return result;
  }
  public Set<String> getObjectChangeEventTypes() {

    Set<String> types = new HashSet();
    types.add(ResearchItem.URL);

    return types;
  }
예제 #11
0
 public static void main(String[] args) {
   try {
     if (args.length == 1) {
       URL url = new URL(args[0]);
       System.out.println("Content-Type: " + url.openConnection().getContentType());
       // 				Vector links = extractLinks(url);
       // 				for (int n = 0; n < links.size(); n++) {
       // 					System.out.println((String) links.elementAt(n));
       // 				}
       Set links = extractLinksWithText(url).entrySet();
       Iterator it = links.iterator();
       while (it.hasNext()) {
         Map.Entry en = (Map.Entry) it.next();
         String strLink = (String) en.getKey();
         String strText = (String) en.getValue();
         System.out.println(strLink + " \"" + strText + "\" ");
       }
       return;
     } else if (args.length == 2) {
       writeURLtoFile(new URL(args[0]), args[1]);
       return;
     }
   } catch (Exception e) {
     System.err.println("An error occured: ");
     e.printStackTrace();
     // 			System.err.println(e.toString());
   }
   System.err.println("Usage: java SaveURL <url> [<file>]");
   System.err.println("Saves a URL to a file.");
   System.err.println("If no file is given, extracts hyperlinks on url to console.");
 }
예제 #12
0
  /**
   * Parse a repository document.
   *
   * @param url
   * @throws IOException
   * @throws XmlPullParserException
   * @throws Exception
   */
  void parseDocument(URL url) throws IOException, XmlPullParserException, Exception {
    if (!visited.contains(url)) {
      visited.add(url);
      try {
        System.out.println("Visiting: " + url);
        InputStream in = null;

        if (url.getPath().endsWith(".zip")) {
          ZipInputStream zin = new ZipInputStream(url.openStream());
          ZipEntry entry = zin.getNextEntry();
          while (entry != null) {
            if (entry.getName().equals("repository.xml")) {
              in = zin;
              break;
            }
            entry = zin.getNextEntry();
          }
        } else {
          in = url.openStream();
        }
        Reader reader = new InputStreamReader(in);
        XmlPullParser parser = new KXmlParser();
        parser.setInput(reader);
        parseRepository(parser);
      } catch (MalformedURLException e) {
        System.out.println("Cannot create connection to url");
      }
    }
  }
예제 #13
0
 static {
   _reachableStoppers.add(HttpServer.class);
   _reachableStoppers.add(AppServer.class);
   _reachableStoppers.add(DBTCP.class);
   _reachableStoppers.add(Mongo.class);
   _reachableStoppers.add(WeakBag.class);
   _reachableStoppers.add(WeakValueMap.class);
 }
예제 #14
0
 private Collection<SharingPeer> getConnectedPeers() {
   Set<SharingPeer> result = new HashSet<SharingPeer>();
   for (SharingPeer peer : this.peers) {
     if (peer.isConnected()) {
       result.add(peer);
     }
   }
   return result;
 }
 private void addTovidName_UserMap(String user, String video) {
   if (vidName_UserMap.containsKey(video)) {
     vidName_UserMap.get(video).add(user);
   } else {
     Set<String> s = new HashSet<String>();
     s.add(user);
     vidName_UserMap.put(video, s);
   }
 }
예제 #16
0
    public void handleStreamEvent(StreamEvent event) {
      if (event.eventType == StreamEvent.Type.STREAM_PREPARED) {
        SessionInfo session = ((StreamEvent.SessionPreparedEvent) event).session;
        sessionsByHost.put(session.peer, session);
      } else if (event.eventType == StreamEvent.Type.FILE_PROGRESS) {
        ProgressInfo progressInfo = ((StreamEvent.ProgressEvent) event).progress;

        // update progress
        Set<ProgressInfo> progresses = progressByHost.get(progressInfo.peer);
        if (progresses == null) {
          progresses = Sets.newSetFromMap(new ConcurrentHashMap<ProgressInfo, Boolean>());
          progressByHost.put(progressInfo.peer, progresses);
        }
        if (progresses.contains(progressInfo)) progresses.remove(progressInfo);
        progresses.add(progressInfo);

        StringBuilder sb = new StringBuilder();
        sb.append("\rprogress: ");

        long totalProgress = 0;
        long totalSize = 0;
        for (Map.Entry<InetAddress, Set<ProgressInfo>> entry : progressByHost.entrySet()) {
          SessionInfo session = sessionsByHost.get(entry.getKey());

          long size = session.getTotalSizeToSend();
          long current = 0;
          int completed = 0;
          for (ProgressInfo progress : entry.getValue()) {
            if (progress.currentBytes == progress.totalBytes) completed++;
            current += progress.currentBytes;
          }
          totalProgress += current;
          totalSize += size;
          sb.append("[").append(entry.getKey());
          sb.append(" ").append(completed).append("/").append(session.getTotalFilesToSend());
          sb.append(" (").append(size == 0 ? 100L : current * 100L / size).append("%)] ");
        }
        long time = System.nanoTime();
        long deltaTime = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(time - lastTime));
        lastTime = time;
        long deltaProgress = totalProgress - lastProgress;
        lastProgress = totalProgress;

        sb.append("[total: ")
            .append(totalSize == 0 ? 100L : totalProgress * 100L / totalSize)
            .append("% - ");
        sb.append(mbPerSec(deltaProgress, deltaTime)).append("MB/s");
        sb.append(" (avg: ")
            .append(mbPerSec(totalProgress, TimeUnit.NANOSECONDS.toMillis(time - start)))
            .append("MB/s)]");

        System.out.print(sb.toString());
      }
    }
예제 #17
0
 /**
  * a DatagramChannel has data ready - process all the pending packets, whether its for a
  * rdpserversocket or rdpconnection.
  */
 void processActiveChannel(DatagramChannel dc) throws ClosedChannelException {
   RDPPacket packet;
   int count = 0;
   // read in the packet
   try {
     Set<RDPConnection> needsAckConnections = new HashSet<RDPConnection>();
     while ((packet = RDPServer.receivePacket(dc)) != null) {
       if (Log.loggingNet)
         Log.net(
             "RDPServer.processActiveChannel: Starting iteration with count of "
                 + count
                 + " packets");
       // see if there is a connection already for this packet
       InetAddress remoteAddr = packet.getInetAddress();
       int remotePort = packet.getPort();
       int localPort = dc.socket().getLocalPort();
       ConnectionInfo conInfo = new ConnectionInfo(remoteAddr, remotePort, localPort);
       RDPConnection con = RDPServer.getConnection(dc, conInfo);
       if (con != null) {
         if (Log.loggingNet)
           Log.net("RDPServer.processActiveChannel: found an existing connection: " + con);
         count++;
         if (processExistingConnection(con, packet)) needsAckConnections.add(con);
         // Prevent this from blocking getActiveChannels by
         // putting an upper bound on the number of packets
         // processed
         if (count >= 20) break;
         continue;
       } else {
         Log.net("RDPServer.processActiveChannel: did not find an existing connection");
       }
       // there is no connection,
       // see if there is a socket listening for new connection
       RDPServerSocket rdpSocket = RDPServer.getRDPSocket(dc);
       if (rdpSocket != null) {
         count++;
         processNewConnection(rdpSocket, packet);
         return;
       }
       return;
     }
     // Finally, send out the acks
     for (RDPConnection con : needsAckConnections) {
       RDPPacket replyPacket = new RDPPacket(con);
       con.sendPacketImmediate(replyPacket, false);
     }
   } catch (ClosedChannelException ex) {
     Log.error("RDPServer.processActiveChannel: ClosedChannel " + dc.socket());
     throw ex;
   } finally {
     if (Log.loggingNet)
       Log.net("RDPServer.processActiveChannel: Returning after processing " + count + " packets");
   }
 }
 /*
  * Clean up the temporary data used to run the tests.
  * This method is not intended to be called by clients, it will be called
  * automatically when the clients use a ReconcilerTestSuite.
  */
 public void cleanup() throws Exception {
   // rm -rf eclipse sub-dir
   boolean leaveDirty =
       Boolean.parseBoolean(TestActivator.getContext().getProperty("p2.tests.doNotClean"));
   if (leaveDirty) return;
   for (Iterator iter = toRemove.iterator(); iter.hasNext(); ) {
     File next = (File) iter.next();
     delete(next);
   }
   output = null;
   toRemove.clear();
 }
예제 #19
0
  // get signs using an additional arg for a target rel
  private Collection<Sign> getSignsFromPredAndTargetRel(String pred, String targetRel) {

    Collection<Word> words = (Collection<Word>) _predToWords.get(pred);
    String specialTokenConst = null;

    // for robustness, when using supertagger, add words for pred sans sense index
    int dotIndex = -1;
    if (_supertagger != null
        && !Character.isDigit(pred.charAt(0))
        && // skip numbers
        (dotIndex = pred.lastIndexOf('.')) > 0
        && pred.length() > dotIndex + 1
        && pred.charAt(dotIndex + 1) != '_') // skip titles, eg Mr._Smith
    {
      String barePred = pred.substring(0, dotIndex);
      Collection<Word> barePredWords = (Collection<Word>) _predToWords.get(barePred);
      if (words == null) words = barePredWords;
      else if (barePredWords != null) {
        Set<Word> unionWords = new HashSet<Word>(words);
        unionWords.addAll(barePredWords);
        words = unionWords;
      }
    }

    if (words == null) {
      specialTokenConst = tokenizer.getSpecialTokenConstant(tokenizer.isSpecialToken(pred));
      if (specialTokenConst == null) return null;
      // lookup words with pred = special token const
      Collection<Word> specialTokenWords = (Collection<Word>) _predToWords.get(specialTokenConst);
      // replace special token const with pred
      if (specialTokenWords == null) return null;
      words = new ArrayList<Word>(specialTokenWords.size());
      for (Iterator<Word> it = specialTokenWords.iterator(); it.hasNext(); ) {
        Word stw = it.next();
        Word w = Word.createSurfaceWord(stw, pred);
        words.add(w);
      }
    }

    List<Sign> retval = new ArrayList<Sign>();
    for (Iterator<Word> it = words.iterator(); it.hasNext(); ) {
      Word w = it.next();
      try {
        SignHash signs = getSignsFromWord(w, specialTokenConst, pred, targetRel);
        retval.addAll(signs.asSignSet());
      }
      // shouldn't happen
      catch (LexException exc) {
        System.err.println("Unexpected lex exception for word " + w + ": " + exc);
      }
    }
    return retval;
  }
  public Set<String> getAutoInstallPluginIDs() {
    Set<String> result = new HashSet<String>();

    Map m = getMostRecentVersionCheckData();

    if (m != null) {

      byte[] x = (byte[]) m.get("autoinstall_pids");

      if (x != null) {

        String str = new String(x);

        String latest = COConfigurationManager.getStringParameter("vc.autoinstall_pids.latest", "");

        if (!str.equals(latest)) {

          byte[] sig = (byte[]) m.get("autoinstall_pids_sig");

          if (sig == null) {

            Debug.out("autoinstall plugins sig missing");

            return (result);
          }

          try {
            AEVerifier.verifyData(str, sig);

            COConfigurationManager.setParameter("vc.autoinstall_pids.latest", str);

          } catch (Throwable e) {

            return (result);
          }
        }

        String[] bits = str.split(",");

        for (String b : bits) {

          b = b.trim();

          if (b.length() > 0) {

            result.add(b);
          }
        }
      }
    }

    return (result);
  }
예제 #21
0
  /**
   * Unchoke connected peers.
   *
   * <p>This is one of the "clever" places of the BitTorrent client. Every
   * OPTIMISTIC_UNCHOKING_FREQUENCY seconds, we decide which peers should be unchocked and
   * authorized to grab pieces from us.
   *
   * <p>Reciprocation (tit-for-tat) and upload capping is implemented here by carefully choosing
   * which peers we unchoke, and which peers we choke.
   *
   * <p>The four peers with the best download rate and are interested in us get unchoked. This
   * maximizes our download rate as we'll be able to get data from there four "best" peers quickly,
   * while allowing these peers to download from us and thus reciprocate their generosity.
   *
   * <p>Peers that have a better download rate than these four downloaders but are not interested
   * get unchoked too, we want to be able to download from them to get more data more quickly. If
   * one becomes interested, it takes a downloader's place as one of the four top downloaders (i.e.
   * we choke the downloader with the worst upload rate).
   *
   * @param optimistic Whether to perform an optimistic unchoke as well.
   */
  private synchronized void unchokePeers(boolean optimistic) {
    // Build a set of all connected peers, we don't care about peers we're
    // not connected to.
    List<SharingPeer> bound = new ArrayList<SharingPeer>(getConnectedPeers());
    Collections.sort(bound, this.getPeerRateComparator());
    Collections.reverse(bound);

    if (bound.size() == 0) {
      logger.trace("No connected peers, skipping unchoking.");
      return;
    } else {
      logger.trace("Running unchokePeers() on {} connected peers.", bound.size());
    }

    int downloaders = 0;
    Set<SharingPeer> choked = new HashSet<SharingPeer>();

    // We're interested in the top downloaders first, so use a descending
    // set.
    for (SharingPeer peer : bound) {
      if (downloaders < Client.MAX_DOWNLOADERS_UNCHOKE) {
        // Unchoke up to MAX_DOWNLOADERS_UNCHOKE interested peers
        if (peer.isChoking()) {
          if (peer.isInterested()) {
            downloaders++;
          }

          peer.unchoke();
        }
        continue;
      }
      // Choke everybody else
      choked.add(peer);
    }

    // Actually choke all chosen peers (if any), except the eventual
    // optimistic unchoke.
    if (choked.size() > 0) {
      SharingPeer randomPeer =
          choked.toArray(new SharingPeer[0])[this.random.nextInt(choked.size())];

      for (SharingPeer peer : choked) {
        if (optimistic && peer == randomPeer) {
          logger.debug("Optimistic unchoke of {}.", peer);
          continue;
        }

        peer.choke();
      }
    }
  }
 private static Set<String> findStandardMBeansFromJar(URL codeBase) throws Exception {
   InputStream is = codeBase.openStream();
   JarInputStream jis = new JarInputStream(is);
   Set<String> names = new TreeSet<String>();
   JarEntry entry;
   while ((entry = jis.getNextJarEntry()) != null) {
     String name = entry.getName();
     if (!name.endsWith(".class")) continue;
     name = name.substring(0, name.length() - 6);
     name = name.replace('/', '.');
     names.add(name);
   }
   return names;
 }
예제 #23
0
 static Set<RDPConnection> getAllConnections() {
   lock.lock();
   try {
     Set<RDPConnection> allCon = new HashSet<RDPConnection>();
     Iterator<Map<ConnectionInfo, RDPConnection>> iter = allConMap.values().iterator();
     while (iter.hasNext()) {
       Map<ConnectionInfo, RDPConnection> dcMap = iter.next();
       allCon.addAll(dcMap.values());
     }
     return allCon;
   } finally {
     lock.unlock();
   }
 }
예제 #24
0
  /**
   * Enumerates the resouces in a give package name. This works even if the resources are loaded
   * from a jar file!
   *
   * <p>Adapted from code by mikewse on the java.sun.com message boards.
   * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
   *
   * @param packageName The package to enumerate
   * @return A Set of Strings for each resouce in the package.
   */
  public static Set getResoucesInPackage(String packageName) throws IOException {
    String localPackageName;
    if (packageName.endsWith("/")) {
      localPackageName = packageName;
    } else {
      localPackageName = packageName + '/';
    }

    Enumeration dirEnum = ClassLoader.getSystemResources(localPackageName);

    Set names = new HashSet();

    // Loop CLASSPATH directories
    while (dirEnum.hasMoreElements()) {
      URL resUrl = (URL) dirEnum.nextElement();

      // Pointing to filesystem directory
      if (resUrl.getProtocol().equals("file")) {
        File dir = new File(resUrl.getFile());
        File[] files = dir.listFiles();
        if (files != null) {
          for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) continue;
            names.add(localPackageName + file.getName());
          }
        }

        // Pointing to Jar file
      } else if (resUrl.getProtocol().equals("jar")) {
        JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
        JarFile jfile = jconn.getJarFile();
        Enumeration entryEnum = jfile.entries();
        while (entryEnum.hasMoreElements()) {
          JarEntry entry = (JarEntry) entryEnum.nextElement();
          String entryName = entry.getName();
          // Exclude our own directory
          if (entryName.equals(localPackageName)) continue;
          String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1);
          if (!parentDirName.equals(localPackageName)) continue;
          names.add(entryName);
        }
      } else {
        // Invalid classpath entry
      }
    }

    return names;
  }
예제 #25
0
  static void test() throws Exception {
    ServerSocketChannel ssc = null;
    SocketChannel sc = null;
    SocketChannel peer = null;
    try {
      ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));

      // loopback connection
      InetAddress lh = InetAddress.getLocalHost();
      sc = SocketChannel.open(new InetSocketAddress(lh, ssc.socket().getLocalPort()));
      peer = ssc.accept();

      // peer sends message so that "sc" will be readable
      int n = peer.write(ByteBuffer.wrap("Hello".getBytes()));
      assert n > 0;

      sc.configureBlocking(false);

      Selector selector = Selector.open();
      SelectionKey key = sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

      boolean done = false;
      int failCount = 0;
      while (!done) {
        int nSelected = selector.select();
        if (nSelected > 0) {
          if (nSelected > 1) throw new RuntimeException("More than one channel selected");
          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> iterator = keys.iterator();
          while (iterator.hasNext()) {
            key = iterator.next();
            iterator.remove();
            if (key.isWritable()) {
              failCount++;
              if (failCount > 10) throw new RuntimeException("Test failed");
              Thread.sleep(250);
            }
            if (key.isReadable()) {
              done = true;
            }
          }
        }
      }
    } finally {
      if (peer != null) peer.close();
      if (sc != null) sc.close();
      if (ssc != null) ssc.close();
    }
  }
예제 #26
0
  /**
   * Decodes a response recursively from MessagePackObject to a normal Java object
   *
   * @param src MessagePack response
   * @return decoded object
   */
  private static Object unMsg(Object src) {
    Object out = src;
    if (src instanceof ArrayType) {
      List l = ((ArrayType) src).asList();
      List outList = new ArrayList(l.size());
      out = outList;
      for (Object o : l) outList.add(unMsg(o));
    } else if (src instanceof BooleanType) {
      out = ((BooleanType) src).asBoolean();
    } else if (src instanceof FloatType) {
      out = ((FloatType) src).asFloat();
    } else if (src instanceof IntegerType) {
      try {
        out = ((IntegerType) src).asInt();
      } catch (Exception ex) {
        /* this is a bandaid until I have a chance to further examine what's happening */
        out = ((IntegerType) src).asLong();
      }
    } else if (src instanceof MapType) {
      Set ents = ((MapType) src).asMap().entrySet();
      out = new HashMap();
      for (Object ento : ents) {
        Map.Entry ent = (Map.Entry) ento;
        Object key = unMsg(ent.getKey());
        Object val = ent.getValue();
        // Hack - keep bytes of generated or encoded payload
        if (ents.size() == 1
            && val instanceof RawType
            && (key.equals("payload") || key.equals("encoded")))
          val = ((RawType) val).asByteArray();
        else val = unMsg(val);
        ((Map) out).put(key + "", val);
      }

      if (((Map) out).containsKey("error") && ((Map) out).containsKey("error_class")) {
        armitage.ArmitageMain.print_error(
            "Metasploit Framework Exception: "
                + ((Map) out).get("error_message").toString()
                + "\n"
                + ((Map) out).get("error_backtrace"));
        throw new RuntimeException(((Map) out).get("error_message").toString());
      }
    } else if (src instanceof NilType) {
      out = null;
    } else if (src instanceof RawType) {
      out = ((RawType) src).asString();
    }
    return out;
  }
예제 #27
0
 public static ConnectionStatistics[] getPoolStatistics() {
   Set<ConnectionStatistics> stats = new HashSet<ConnectionStatistics>();
   Iterator<TcpConnectionManager> it = poolTable_.values().iterator();
   while (it.hasNext()) {
     TcpConnectionManager cp = it.next();
     ConnectionStatistics cs =
         new ConnectionStatistics(
             cp.getLocalEndPoint(),
             cp.getRemoteEndPoint(),
             cp.getPoolSize(),
             cp.getConnectionsInUse());
     stats.add(cs);
   }
   return stats.toArray(new ConnectionStatistics[0]);
 }
  private static String[] findStandardMBeans(URL codeBase) throws Exception {
    Set<String> names;
    if (codeBase.getProtocol().equalsIgnoreCase("file") && codeBase.toString().endsWith("/"))
      names = findStandardMBeansFromDir(codeBase);
    else names = findStandardMBeansFromJar(codeBase);

    Set<String> standardMBeanNames = new TreeSet<String>();
    for (String name : names) {
      if (name.endsWith("MBean")) {
        String prefix = name.substring(0, name.length() - 5);
        if (names.contains(prefix)) standardMBeanNames.add(prefix);
      }
    }
    return standardMBeanNames.toArray(new String[0]);
  }
  @RequestMapping(value = CLIENT_CONNECT_PATH, method = RequestMethod.POST)
  public @ResponseBody int connectClient(@RequestBody String allVid) {
    try {
      int reply = FAILED;
      String[] videos = allVid.split(",");
      String uName = videos[0].trim();
      videos = java.util.Arrays.copyOfRange(videos, 1, videos.length);
      // System.out.println("Client connect"+hostAdder+" "+uName+" "+ Arrays.asList(videos));
      int ans = masterService.psConnectClient(hostAdder, uName, videos);
      // System.out.println("ans =" +ans +" "+FAILED);
      while (ans == PS_NOT_CONNECTED) {
        reconnectToMS();
        ans = masterService.psConnectClient(hostAdder, uName, videos);
      }
      if (ans == FAILED) return FAILED;
      // System.out.println("Clinet "+ uName + " connected");

      if (user_vidNameMap.containsKey(uName)) {
        reply = CLIENT_ALREADY_CONNECTED;
      } else {
        reply = CLIENT_CONNECTED;
        user_vidNameMap.put(uName, new HashSet<String>());
      }
      // System.out.println("Clinet "+ uName + " connected");

      Set<String> vidSet = user_vidNameMap.get(uName);
      for (int i = 0; i < videos.length; i++) {
        String temp = videos[i].trim();
        // System.out.println("add video");

        if (!temp.equals("")) {
          vidSet.add(temp);
          addTovidName_UserMap(uName, temp);
        }
      }
      // System.out.println("Clinet "+ uName + " connected");

      userAliveMap.put(uName, new Long(System.currentTimeMillis() + TTL));
      // System.out.println("Clinet "+ uName + " connected");

      activeUsers.add(uName);
      System.out.println("Clinet " + uName + " connected");
      return reply;
    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
      return FAILED;
    }
  }
예제 #30
0
  /**
   * Parse the repository.
   *
   * @param parser
   * @throws Exception
   */
  private void parseRepository(XmlPullParser parser) throws Exception {
    try {
      parser.require(XmlPullParser.START_DOCUMENT, null, null);
      parser.nextTag();
      if (parser.getName().equals("bundles")) parseOscar(parser);
      else {
        parser.require(XmlPullParser.START_TAG, null, "repository");
        date = parser.getAttributeValue(null, "lastmodified");
        name = parser.getAttributeValue(null, "name");
        if (name == null) name = "Untitled";

        while (parser.nextTag() == XmlPullParser.START_TAG) {
          if (parser.getName().equals("resource")) {
            ResourceImpl resource = new ResourceImpl(this, parser);
            resources.add(resource);
          } else if (parser.getName().equals("referral")) referral(parser);
          else
            throw new IllegalArgumentException(
                "Invalid tag in repository: " + url + " " + parser.getName());
        }
        parser.require(XmlPullParser.END_TAG, null, "repository");
      }
    } catch (XmlPullParserException e) {
      e.printStackTrace();
      throw new IllegalArgumentException(
          "XML unregognized around: " + e.getLineNumber() + " " + e.getMessage());
    }
  }