コード例 #1
0
  public void selectNext() {
    Iterator i = new SelectionIterator(this);

    if (m_actives.size() == 1) {
      boolean isFound = false;

      // loop the iterator in reverse order of drawing
      while (i.hasNext()) {
        GlyphObject object = (GlyphObject) i.next();

        if (m_actives.isSelected(object)) {
          isFound = true;
          continue;
        } // if

        if (!isFound) {
          continue;
        } // if

        m_actives.unselectAll();
        m_actives.addActive(object);
        return;
      } // while i
    } // if

    i = new SelectionIterator(this);
    if (i.hasNext()) {
      GlyphObject object = (GlyphObject) i.next();
      m_actives.unselectAll();
      m_actives.addActive(object);
      return;
    } // if
  }
コード例 #2
0
ファイル: ZCM.java プロジェクト: ZeroCM/zcm
  /**
   * Remove this particular regex/subscriber pair (UNTESTED AND API MAY CHANGE). If regex is null,
   * all subscriptions for 'sub' are cancelled. If subscriber is null, any previous subscriptions
   * matching the regular expression will be cancelled. If both 'sub' and 'regex' are null, all
   * subscriptions will be cancelled.
   */
  public void unsubscribe(String regex, ZCMSubscriber sub) {
    if (this.closed) throw new IllegalStateException();

    synchronized (this) {
      for (Provider p : providers) p.unsubscribe(regex);
    }

    // TODO: providers don't seem to use anything beyond first channel

    synchronized (subscriptions) {

      // Find and remove subscriber from list
      for (Iterator<SubscriptionRecord> it = subscriptions.iterator(); it.hasNext(); ) {
        SubscriptionRecord sr = it.next();

        if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
          it.remove();
        }
      }

      // Find and remove subscriber from map
      for (String channel : subscriptionsMap.keySet()) {
        for (Iterator<SubscriptionRecord> it = subscriptionsMap.get(channel).iterator();
            it.hasNext(); ) {
          SubscriptionRecord sr = it.next();

          if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
            it.remove();
          }
        }
      }
    }
  }
コード例 #3
0
ファイル: Lexicon.java プロジェクト: kevinkissi/openccg
 // look up and apply coarts for given rels to each sign in result
 private void applyCoarts(List<String> coartRels, Collection<Sign> result) {
   List<Sign> inputSigns = new ArrayList<Sign>(result);
   result.clear();
   List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size());
   // for each rel, lookup coarts and apply to input signs, storing results in output signs
   for (Iterator<String> it = coartRels.iterator(); it.hasNext(); ) {
     String rel = it.next();
     Collection<String> preds = (Collection<String>) _coartRelsToPreds.get(rel);
     if (preds == null) continue; // not expected
     Collection<Sign> coartResult = getSignsFromRelAndPreds(rel, preds);
     if (coartResult == null) continue;
     for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) {
       Sign coartSign = it2.next();
       // apply to each input
       for (int j = 0; j < inputSigns.size(); j++) {
         Sign sign = inputSigns.get(j);
         grammar.rules.applyCoart(sign, coartSign, outputSigns);
       }
     }
     // switch output to input for next iteration
     inputSigns.clear();
     inputSigns.addAll(outputSigns);
     outputSigns.clear();
   }
   // add results back
   result.addAll(inputSigns);
 }
コード例 #4
0
  private void stepTimeout() {
    boolean updated = false;
    synchronized (channels) {
      Iterator<ChannelInfo> it = channels.values().iterator();
      while (it.hasNext()) {
        ChannelInfo channel = it.next();
        Iterator<UserInfo> removed = channel.stepTimeout(getTimeoutLimit());

        if (removed != null) {
          updated = true;
          String channelName = channel.getChannelName();
          while (removed.hasNext()) {
            UserInfo user = removed.next();
            ServerLogger.getInstance()
                .channelLeaved(channelName, user.getUserName(), user.getInetSocketAddress());
          }
          if (channel.isEmpty()) {
            it.remove();
            ServerLogger.getInstance().channelRemoved(channelName);
          }
        }
      }

      if (updated) {
        updateChannelsCache();
      }
    }
  }
コード例 #5
0
ファイル: Lexicon.java プロジェクト: kevinkissi/openccg
  // 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;
  }
コード例 #6
0
ファイル: FnHttpTest.java プロジェクト: james-jw/basex
  /**
   * Tests RequestParser.parse() with multipart request.
   *
   * @throws IOException I/O Exception
   * @throws QueryException query exception
   */
  @Test
  public void parseMultipartReq() throws IOException, QueryException {
    final String multiReq =
        "<http:request "
            + "xmlns:http='http://expath.org/ns/http-client' "
            + "method='POST' href='"
            + REST_ROOT
            + "'>"
            + "<http:header name='hdr1' value='hdr1val'/>"
            + "<http:header name='hdr2' value='hdr2val'/>"
            + "<http:multipart media-type='multipart/mixed' boundary='xxxx'>"
            + "<http:header name='p1hdr1' value='p1hdr1val'/>"
            + "<http:header name='p1hdr2' value='p1hdr2val'/>"
            + "<http:body media-type='text/plain'>"
            + "Part1"
            + "</http:body>"
            + "<http:header name='p2hdr1' value='p2hdr1val'/>"
            + "<http:body media-type='text/plain'>"
            + "Part2"
            + "</http:body>"
            + "<http:body media-type='text/plain'>"
            + "Part3"
            + "</http:body>"
            + "</http:multipart>"
            + "</http:request>";

    final DBNode dbNode1 = new DBNode(new IOContent(multiReq));
    final HttpRequestParser rp = new HttpRequestParser(null);
    final HttpRequest r = rp.parse(dbNode1.children().next(), null);

    assertEquals(2, r.attributes.size());
    assertEquals(2, r.headers.size());
    assertTrue(r.isMultipart);
    assertEquals(3, r.parts.size());

    // check parts
    final Iterator<Part> i = r.parts.iterator();
    Part part = i.next();
    assertEquals(2, part.headers.size());
    assertEquals(1, part.bodyContent.size());
    assertEquals(1, part.bodyAttrs.size());

    part = i.next();
    assertEquals(1, part.headers.size());
    assertEquals(1, part.bodyContent.size());
    assertEquals(1, part.bodyAttrs.size());

    part = i.next();
    assertEquals(0, part.headers.size());
    assertEquals(1, part.bodyContent.size());
    assertEquals(1, part.bodyAttrs.size());
  }
コード例 #7
0
  public void testStoreNodeState() throws Exception {
    TimeBase.setSimulated(100);
    CachedUrlSet mcus =
        new MockCachedUrlSet(mau, new RangeCachedUrlSetSpec("http://www.example.com"));
    CrawlState crawl = new CrawlState(1, 2, 123);
    List polls = new ArrayList(2);
    PollState poll1 = new PollState(1, "sdf", "jkl", 2, 123, Deadline.at(456), false);
    PollState poll2 = new PollState(2, "abc", "def", 3, 321, Deadline.at(654), false);
    polls.add(poll1);
    polls.add(poll2);
    NodeState nodeState = new NodeStateImpl(mcus, 123321, crawl, polls, repository);
    ((NodeStateImpl) nodeState).setState(NodeState.DAMAGE_AT_OR_BELOW);
    repository.storeNodeState(nodeState);
    String filePath = LockssRepositoryImpl.mapAuToFileLocation(tempDirPath, mau);
    filePath =
        LockssRepositoryImpl.mapUrlToFileLocation(
            filePath, "http://www.example.com/" + HistoryRepositoryImpl.NODE_FILE_NAME);
    File xmlFile = new File(filePath);
    assertTrue(xmlFile.exists());

    nodeState = null;
    nodeState = repository.loadNodeState(mcus);
    assertSame(mcus, nodeState.getCachedUrlSet());

    assertEquals(123321, nodeState.getAverageHashDuration());
    assertEquals(1, nodeState.getCrawlState().getType());
    assertEquals(2, nodeState.getCrawlState().getStatus());
    assertEquals(123, nodeState.getCrawlState().getStartTime());
    assertEquals(NodeState.DAMAGE_AT_OR_BELOW, nodeState.getState());

    Iterator pollIt = nodeState.getActivePolls();
    assertTrue(pollIt.hasNext());
    PollState loadedPoll = (PollState) pollIt.next();
    assertEquals(1, loadedPoll.getType());
    assertEquals("sdf", loadedPoll.getLwrBound());
    assertEquals("jkl", loadedPoll.getUprBound());
    assertEquals(2, loadedPoll.getStatus());
    assertEquals(123, loadedPoll.getStartTime());
    assertEquals(456, loadedPoll.getDeadline().getExpirationTime());

    assertTrue(pollIt.hasNext());
    loadedPoll = (PollState) pollIt.next();
    assertEquals(2, loadedPoll.getType());
    assertEquals("abc", loadedPoll.getLwrBound());
    assertEquals("def", loadedPoll.getUprBound());
    assertEquals(3, loadedPoll.getStatus());
    assertEquals(321, loadedPoll.getStartTime());
    assertEquals(654, loadedPoll.getDeadline().getExpirationTime());
    assertFalse(pollIt.hasNext());

    TimeBase.setReal();
  }
コード例 #8
0
ファイル: MersManager.java プロジェクト: won-woo/Helloworld
  public List<MersHPVO> mersHPData() {
    List<MersHPVO> list = new ArrayList<MersHPVO>();
    try {
      Document doc = Jsoup.connect("http://www.cdc.go.kr/CDC/cms/content/16/63316_view.html").get();
      // System.out.println(doc);
      Elements trs = doc.select("table tbody tr");
      // System.out.println(trs);
      String data = "";

      for (Element tr : trs) {
        Iterator<Element> it = tr.getElementsByTag("td").iterator();
        int size = tr.getElementsByTag("td").size();
        MersHPVO vo = new MersHPVO();
        if (size == 5) {
          it.next().html();
          vo.setGugun(it.next().html());
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
        } else {
          vo.setGugun(it.next().html());
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
        }
        list.add(vo);
        // if(i==2) break;
        /*while(it.hasNext())
        {

         MersHPVO vo=new MersHPVO();
         String str=it.next().html();
         if(str.startsWith("<strong>"))
         {
          vo.setGugun(it.next().html());
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
         }
         else
         {
          vo.setGugun(str);
          vo.setName(it.next().html());
          vo.setDuration(it.next().html());
          vo.setNum(it.next().html());
         }
         list.add(vo);
        }*/

      }
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
    return list;
  }
コード例 #9
0
    public void run() {
      super.run();

      // save the last set of active JVMs
      Set lastActiveVms = activeVms;

      try {
        // get the current set of active JVMs
        activeVms = (HashSet) vmManager.activeVms();

      } catch (MonitorException e) {
        // XXX: use logging api
        System.err.println("MonitoredHostProvider: polling task " + "caught MonitorException:");
        e.printStackTrace();

        // mark the HostManager as errored and notify listeners
        setLastException(e);
        fireDisconnectedEvents();
      }

      if (activeVms.isEmpty()) {
        return;
      }

      Set startedVms = new HashSet();
      Set terminatedVms = new HashSet();

      for (Iterator i = activeVms.iterator(); i.hasNext(); /* empty */ ) {
        Integer vmid = (Integer) i.next();
        if (!lastActiveVms.contains(vmid)) {
          // a new file has been detected, add to set
          startedVms.add(vmid);
        }
      }

      for (Iterator i = lastActiveVms.iterator(); i.hasNext();
      /* empty */ ) {
        Object o = i.next();
        if (!activeVms.contains(o)) {
          // JVM has terminated, remove it from the active list
          terminatedVms.add(o);
        }
      }

      if (!startedVms.isEmpty() || !terminatedVms.isEmpty()) {
        fireVmStatusChangedEvents(activeVms, startedVms, terminatedVms);
      }
    }
コード例 #10
0
  void close() {
    try {
      if (mySelector != null) mySelector.close();
    } catch (IOException e) {
    }
    mySelector = null;

    // run down open connections and sockets.
    Iterator<ServerSocketChannel> i = Acceptors.values().iterator();
    while (i.hasNext()) {
      try {
        i.next().close();
      } catch (IOException e) {
      }
    }

    // 29Sep09: We create an ArrayList of the existing connections, then iterate over
    // that to call unbind on them. This is because an unbind can trigger a reconnect,
    // which will add to the Connections HashMap, causing a ConcurrentModificationException.
    // XXX: The correct behavior here would be to latch the various reactor methods to return
    // immediately if the reactor is shutting down.
    ArrayList<EventableChannel> conns = new ArrayList<EventableChannel>();
    Iterator<EventableChannel> i2 = Connections.values().iterator();
    while (i2.hasNext()) {
      EventableChannel ec = i2.next();
      if (ec != null) {
        conns.add(ec);
      }
    }
    Connections.clear();

    ListIterator<EventableChannel> i3 = conns.listIterator(0);
    while (i3.hasNext()) {
      EventableChannel ec = i3.next();
      eventCallback(ec.getBinding(), EM_CONNECTION_UNBOUND, null);
      ec.close();

      EventableSocketChannel sc = (EventableSocketChannel) ec;
      if (sc != null && sc.isAttached()) DetachedConnections.add(sc);
    }

    ListIterator<EventableSocketChannel> i4 = DetachedConnections.listIterator(0);
    while (i4.hasNext()) {
      EventableSocketChannel ec = i4.next();
      ec.cleanup();
    }
    DetachedConnections.clear();
  }
コード例 #11
0
ファイル: Lexicon.java プロジェクト: kevinkissi/openccg
  // 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;
  }
コード例 #12
0
ファイル: Lexicon.java プロジェクト: kevinkissi/openccg
  // get signs with additional args for a known special token const, target pred and target rel
  private SignHash getSignsFromWord(
      Word w, String specialTokenConst, String targetPred, String targetRel) throws LexException {

    Collection<MorphItem> morphItems =
        (specialTokenConst == null) ? (Collection<MorphItem>) _words.get(w) : null;

    if (morphItems == null) {
      // check for special tokens
      if (specialTokenConst == null) {
        specialTokenConst =
            tokenizer.getSpecialTokenConstant(tokenizer.isSpecialToken(w.getForm()));
        targetPred = w.getForm();
      }
      if (specialTokenConst != null) {
        Word key = Word.createSurfaceWord(w, specialTokenConst);
        morphItems = (Collection<MorphItem>) _words.get(key);
      }
      // otherwise throw lex exception
      if (morphItems == null) throw new LexException(w + " not in lexicon");
    }

    SignHash result = new SignHash();

    for (Iterator<MorphItem> MI = morphItems.iterator(); MI.hasNext(); ) {
      getWithMorphItem(w, MI.next(), targetPred, targetRel, result);
    }

    return result;
  }
コード例 #13
0
ファイル: Lexicon.java プロジェクト: kevinkissi/openccg
 // look up and apply coarts for w to each sign in result
 @SuppressWarnings("unchecked")
 private void applyCoarts(Word w, SignHash result) throws LexException {
   List<Sign> inputSigns = new ArrayList<Sign>(result.asSignSet());
   result.clear();
   List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size());
   // for each surface attr, lookup coarts and apply to input signs, storing results in output
   // signs
   for (Iterator<Pair<String, String>> it = w.getSurfaceAttrValPairs(); it.hasNext(); ) {
     Pair<String, String> p = it.next();
     String attr = (String) p.a;
     if (!_indexedCoartAttrs.contains(attr)) continue;
     String val = (String) p.b;
     Word coartWord = Word.createWord(attr, val);
     SignHash coartResult = getSignsFromWord(coartWord, null, null, null);
     for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) {
       Sign coartSign = it2.next();
       // apply to each input
       for (int j = 0; j < inputSigns.size(); j++) {
         Sign sign = inputSigns.get(j);
         grammar.rules.applyCoart(sign, coartSign, outputSigns);
       }
     }
     // switch output to input for next iteration
     inputSigns.clear();
     inputSigns.addAll(outputSigns);
     outputSigns.clear();
   }
   // add results back
   result.addAll(inputSigns);
 }
コード例 #14
0
  protected String getRallyAPIError(String responseXML) {
    String errorMsg = "";

    try {

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Errors");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Element item = (Element) iter.next();
        errorMsg = item.getChildText("OperationResultError");
      }

    } catch (Exception e) {
      errorMsg = e.toString();
    }

    return errorMsg;
  }
コード例 #15
0
ファイル: TestV3LcapMessage.java プロジェクト: ravn/lockss
  private V3LcapMessage makeTestVoteMessage(Collection voteBlocks) throws IOException {
    mPollMgr.setStateDir("key", tempDir);
    V3LcapMessage msg =
        new V3LcapMessage(
            "ArchivalID_2",
            "key",
            "Plug42",
            m_testBytes,
            m_testBytes,
            V3LcapMessage.MSG_VOTE,
            987654321,
            m_testID,
            tempDir,
            theDaemon);

    // Set msg vote blocks.
    for (Iterator ix = voteBlocks.iterator(); ix.hasNext(); ) {
      msg.addVoteBlock((VoteBlock) ix.next());
    }

    msg.setHashAlgorithm(LcapMessage.getDefaultHashAlgorithm());
    msg.setArchivalId(m_archivalID);
    msg.setPluginVersion("PlugVer42");
    return msg;
  }
コード例 #16
0
 /**
  * Find a matching client SUBSCRIBE to the incoming notify. NOTIFY requests are matched to such
  * SUBSCRIBE requests if they contain the same "Call-ID", a "To" header "tag" parameter which
  * matches the "From" header "tag" parameter of the SUBSCRIBE, and the same "Event" header field.
  * Rules for comparisons of the "Event" headers are described in section 7.2.1. If a matching
  * NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates a new
  * subscription and a new dialog (unless they have already been created by a matching response, as
  * described above).
  *
  * @param notifyMessage
  */
 public SIPClientTransaction findSubscribeTransaction(SIPRequest notifyMessage) {
   synchronized (clientTransactions) {
     Iterator<SIPClientTransaction> it = clientTransactions.iterator();
     String thisToTag = notifyMessage.getTo().getTag();
     if (thisToTag == null) return null;
     Event eventHdr = (Event) notifyMessage.getHeader(EventHeader.NAME);
     if (eventHdr == null) return null;
     while (it.hasNext()) {
       SIPClientTransaction ct = (SIPClientTransaction) it.next();
       // SIPRequest sipRequest = ct.getOriginalRequest();
       String fromTag = ct.from.getTag();
       Event hisEvent = ct.event;
       // Event header is mandatory but some slopply clients
       // dont include it.
       if (hisEvent == null) continue;
       if (ct.method.equals(Request.SUBSCRIBE)
           && fromTag.equalsIgnoreCase(thisToTag)
           && hisEvent != null
           && eventHdr.match(hisEvent)
           && notifyMessage.getCallId().getCallId().equalsIgnoreCase(ct.callId.getCallId()))
         return ct;
     }
   }
   return null;
 }
コード例 #17
0
ファイル: CIManagerImpl.java プロジェクト: manoj-s/framework
 private void deleteJsonJobs(ApplicationInfo appInfo, List<CIJob> selectedJobs)
     throws PhrescoException {
   try {
     if (CollectionUtils.isEmpty(selectedJobs)) {
       return;
     }
     Gson gson = new Gson();
     List<CIJob> jobs = getJobs(appInfo);
     if (CollectionUtils.isEmpty(jobs)) {
       return;
     }
     // all values
     Iterator<CIJob> iterator = jobs.iterator();
     // deletable values
     for (CIJob selectedInfo : selectedJobs) {
       while (iterator.hasNext()) {
         CIJob itrCiJob = iterator.next();
         if (itrCiJob.getName().equals(selectedInfo.getName())) {
           iterator.remove();
           break;
         }
       }
     }
     writeJsonJobs(appInfo, jobs, CI_CREATE_NEW_JOBS);
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
コード例 #18
0
ファイル: RepositoryImpl.java プロジェクト: snambi/bindex
 public Resource getResource(String id) {
   for (Iterator i = getResourceList().iterator(); i.hasNext(); ) {
     ResourceImpl resource = (ResourceImpl) i.next();
     if (resource.getId().equals(id)) return resource;
   }
   return null;
 }
コード例 #19
0
 public void display(Graphics2D g, AffineTransform a_trans) {
   Iterator i = createIterator();
   while (i.hasNext()) {
     GlyphObject object = (GlyphObject) i.next();
     object.display(g, a_trans);
   } // while
 }
  public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) {
    final String S_ProcName = "CFInternetMssCFIterateTSecGroupIncByGroup.enumerateDetails() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()");
    }

    List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>();

    if (genDef instanceof ICFInternetTSecGroupObj) {
      Iterator<ICFSecurityTSecGroupIncludeObj> elements =
          ((ICFInternetTSecGroupObj) genDef).getRequiredChildrenIncByGroup().iterator();
      while (elements.hasNext()) {
        list.add(elements.next());
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFInternetTSecGroupObj");
    }

    return (list.listIterator());
  }
コード例 #21
0
  public synchronized void messageReceived(int to, Message m) {

    DrainMsg mhMsg = (DrainMsg) m;

    log.debug(
        "incoming: localDest: "
            + to
            + " type:"
            + mhMsg.get_type()
            + " hops:"
            + (16 - mhMsg.get_ttl())
            + " seqNo:"
            + mhMsg.get_seqNo()
            + " source:"
            + mhMsg.get_source()
            + " finalDest:"
            + mhMsg.get_dest());

    // lets assume that the network cannot buffer more than 25 drain msgs from a single source at a
    // time (should be more than reasonable)
    if (seqNos.containsKey(new Integer(mhMsg.get_source()))) {
      int oldSeqNo = ((Integer) seqNos.get(new Integer(mhMsg.get_source()))).intValue();
      int upperBound = mhMsg.get_seqNo() + 25;
      int wrappedUpperBound = 25 - (255 - mhMsg.get_seqNo());
      if ((oldSeqNo >= mhMsg.get_seqNo() && oldSeqNo < upperBound)
          || (oldSeqNo >= 0 && oldSeqNo < wrappedUpperBound)) {
        log.debug(
            "Dropping message from "
                + mhMsg.get_source()
                + " with duplicate seqNo: "
                + mhMsg.get_seqNo());
        return;
      }
    }
    seqNos.put(new Integer(mhMsg.get_source()), new Integer(mhMsg.get_seqNo()));

    if (to != spAddr && to != MoteIF.TOS_BCAST_ADDR && to != TOS_UART_ADDR) {
      log.debug("Dropping message not for me.");
      return;
    }

    HashSet promiscuousSet = (HashSet) idTable.get(new Integer(BCAST_ID));
    HashSet listenerSet = (HashSet) idTable.get(new Integer(mhMsg.get_type()));

    if (listenerSet != null && promiscuousSet != null) {
      listenerSet.addAll(promiscuousSet);
    } else if (listenerSet == null && promiscuousSet != null) {
      listenerSet = promiscuousSet;
    }

    if (listenerSet == null) {
      log.debug("No Listener for type: " + mhMsg.get_type());
      return;
    }

    for (Iterator it = listenerSet.iterator(); it.hasNext(); ) {
      MessageListener ml = (MessageListener) it.next();
      ml.messageReceived(to, mhMsg);
    }
  }
コード例 #22
0
  /**
   * Processes the messages from the server
   *
   * @param message
   */
  private synchronized void processServerMessage(String message) {
    SAXBuilder builder = new SAXBuilder();
    String what = new String();
    Document doc = null;

    try {
      doc = builder.build(new StringReader(message));
      Element root = doc.getRootElement();
      List childs = root.getChildren();
      Iterator i = childs.iterator();
      what = ((Element) i.next()).getName();
    } catch (Exception e) {
    }

    if (what.equalsIgnoreCase("LOGIN") == true) _login(doc);
    else if (what.equalsIgnoreCase("LOGOUT") == true) _logout(doc);
    else if (what.equalsIgnoreCase("MESSAGE") == true) _message(doc);
    else if (what.equalsIgnoreCase("WALL") == true) _wall(doc);
    else if (what.equalsIgnoreCase("CREATEGROUP") == true) _creategroup(doc);
    else if (what.equalsIgnoreCase("JOINGROUP") == true) _joingroup(doc);
    else if (what.equalsIgnoreCase("PARTGROUP") == true) _partgroup(doc);
    else if (what.equalsIgnoreCase("GROUPMESSAGE") == true) _groupmessage(doc);
    else if (what.equalsIgnoreCase("KICK") == true) _kick(doc);
    else if (what.equalsIgnoreCase("LISTUSER") == true) _listuser(doc);
    else if (what.equalsIgnoreCase("LISTGROUP") == true) _listgroup(doc);
  }
  public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) {
    final String S_ProcName = "CFBamMssCFIterateNumberTypeRef.enumerateDetails() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()");
    }

    List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>();

    if (genDef instanceof ICFBamNumberTypeObj) {
      Iterator<ICFBamTableColObj> elements =
          ((ICFBamNumberTypeObj) genDef).getOptionalChildrenRef().iterator();
      while (elements.hasNext()) {
        list.add(elements.next());
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFBamNumberTypeObj");
    }

    return (list.listIterator());
  }
コード例 #24
0
  public AuthenticatorWindow() {
    SESecurityManager.addPasswordListener(this);

    // System.out.println( "AuthenticatorWindow");

    Map cache = COConfigurationManager.getMapParameter(CONFIG_PARAM, new HashMap());

    try {
      Iterator it = cache.entrySet().iterator();

      while (it.hasNext()) {

        Map.Entry entry = (Map.Entry) it.next();

        String key = (String) entry.getKey();
        Map value = (Map) entry.getValue();

        String user = new String((byte[]) value.get("user"), "UTF-8");
        char[] pw = new String((byte[]) value.get("pw"), "UTF-8").toCharArray();

        auth_cache.put(key, new authCache(key, new PasswordAuthentication(user, pw), true));
      }

    } catch (Throwable e) {

      COConfigurationManager.setParameter(CONFIG_PARAM, new HashMap());

      Debug.printStackTrace(e);
    }
  }
コード例 #25
0
ファイル: SaveURL.java プロジェクト: tchipwanya/cs458-f12
 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.");
 }
コード例 #26
0
ファイル: JobTracker.java プロジェクト: bruthe/hadoop-0.1r
    /**
     * The run method lives for the life of the JobTracker, and removes Jobs that are not still
     * running, but which finished a long time ago.
     */
    public void run() {
      while (shouldRun) {
        try {
          Thread.sleep(RETIRE_JOB_CHECK_INTERVAL);
        } catch (InterruptedException ie) {
        }

        synchronized (jobs) {
          synchronized (jobInitQueue) {
            synchronized (jobsByArrival) {
              for (Iterator it = jobs.keySet().iterator(); it.hasNext(); ) {
                String jobid = (String) it.next();
                JobInProgress job = (JobInProgress) jobs.get(jobid);

                if (job.getStatus().getRunState() != JobStatus.RUNNING
                    && job.getStatus().getRunState() != JobStatus.PREP
                    && (job.getFinishTime() + RETIRE_JOB_INTERVAL < System.currentTimeMillis())) {
                  it.remove();

                  jobInitQueue.remove(job);
                  jobsByArrival.remove(job);
                }
              }
            }
          }
        }
      }
    }
コード例 #27
0
 private void writeContent(final int end, final List childElements, final int depth)
     throws IOException {
   // sets index to end
   for (final Iterator i = childElements.iterator(); i.hasNext(); ) {
     final Element element = (Element) i.next();
     final int elementBegin = element.begin;
     if (elementBegin >= end) break;
     if (indentAllElements) {
       writeText(elementBegin, depth);
       writeElement(element, depth, end, false, false);
     } else {
       if (inlinable(element)) continue; // skip over elements that can be inlined.
       writeText(elementBegin, depth);
       final String elementName = element.getName();
       if (elementName == HTMLElementName.PRE || elementName == HTMLElementName.TEXTAREA) {
         writeElement(element, depth, end, true, true);
       } else if (elementName == HTMLElementName.SCRIPT) {
         writeElement(element, depth, end, true, false);
       } else {
         writeElement(
             element,
             depth,
             end,
             false,
             !removeLineBreaks && containsOnlyInlineLevelChildElements(element));
       }
     }
   }
   writeText(end, depth);
 }
コード例 #28
0
  @Override
  public void notifyResult(AuctionItem item) {
    if (registeredUsers.containsKey(item.getCreator_id())) {
      RMIClientIntf creator = registeredUsers.get(item.getCreator_id());
      try {
        creator.callBack("Your Auction has produced the following results :\n ");
        creator.callBack(item.getResult());
      } catch (RemoteException e) {
        System.out.println("Creator no longer online\n");
      }
    } else {
      System.out.println("Creator id does not exist\n");
    } // Normally an auction with no creator registered should not exist but since this is a
    // simplified implementation
    // We allow bids on auctions with no creator (usually the initialised ones) for testing
    // purposes.
    if (item.numberOfBids() != 0) {
      System.out.println("Notifying bidders");
      Iterator<Bid> it = item.getBidders();
      while (it.hasNext()) {
        Bid bidder = it.next();
        if (registeredUsers.containsKey(bidder.getUserId())) {
          RMIClientIntf client = registeredUsers.get(bidder.getUserId());
          try {
            client.callBack(item.getResult());
          } catch (RemoteException e) {
            System.out.println("Bidder with id " + bidder.getUserId() + " no longer online\n");
          }

        } else {
          System.out.println("User id does not exist\n");
        }
      }
    }
  }
  public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) {
    final String S_ProcName = "CFAsteriskMssCFIterateHostNodeConfFile.enumerateDetails() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()");
    }

    List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>();

    if (genDef instanceof ICFAsteriskHostNodeObj) {
      Iterator<ICFAsteriskConfigurationFileObj> elements =
          ((ICFAsteriskHostNodeObj) genDef).getOptionalComponentsConfFile().iterator();
      while (elements.hasNext()) {
        list.add(elements.next());
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFAsteriskHostNodeObj");
    }

    return (list.listIterator());
  }
コード例 #30
0
 /** Closes all open sockets and stops the internal server thread that processes messages. */
 public void close() {
   ServerThread st = server;
   if (st != null) {
     st.close();
     try {
       st.join();
     } catch (InterruptedException ex) {
       logger.warn(ex);
     }
     server = null;
     for (Iterator it = sockets.values().iterator(); it.hasNext(); ) {
       SocketEntry entry = (SocketEntry) it.next();
       try {
         synchronized (entry) {
           entry.getSocket().close();
         }
         logger.debug("Socket to " + entry.getPeerAddress() + " closed");
       } catch (IOException iox) {
         // ingore
         logger.debug(iox);
       }
     }
     if (socketCleaner != null) {
       socketCleaner.cancel();
     }
     socketCleaner = null;
   }
 }