Exemplo n.º 1
0
  /**
   * return the contents of the buffer. The order of the chunks returned is determined by the
   * ejection policy, such that the chunk most likely to be given the book is first.
   */
  @Override
  protected Collection<IChunk> getSourceChunksInternal(Collection<IChunk> container) {
    /*
     * there is nothing to return..
     */
    if (_sourceChunks.size() == 0) return container;

    List<IChunk> list = null;
    if (container instanceof List) list = (List<IChunk>) container;
    else list = new ArrayList<IChunk>(_sourceChunks.size());

    list.addAll(_sourceChunks.values());

    switch (getEjectionPolicy()) {
      case MostRecentlyAdded:
      case MostRecentlyMatched:
      case MostRecentlyUsed:
        Collections.reverse(list);
        break;
    }

    if (!(container instanceof List)) container.addAll(list);

    return container;
  }
 public void testSubMapContents2() {
   ConcurrentNavigableMap map = map5();
   SortedMap sm = map.subMap(two, three);
   assertEquals(1, sm.size());
   assertEquals(two, sm.firstKey());
   assertEquals(two, sm.lastKey());
   assertFalse(sm.containsKey(one));
   assertTrue(sm.containsKey(two));
   assertFalse(sm.containsKey(three));
   assertFalse(sm.containsKey(four));
   assertFalse(sm.containsKey(five));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(two, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(two));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(three), null);
   assertEquals(4, map.size());
 }
 public void testDescendingSubMapContents2() {
   ConcurrentNavigableMap map = dmap5();
   SortedMap sm = map.subMap(m2, m3);
   assertEquals(1, sm.size());
   assertEquals(m2, sm.firstKey());
   assertEquals(m2, sm.lastKey());
   assertFalse(sm.containsKey(m1));
   assertTrue(sm.containsKey(m2));
   assertFalse(sm.containsKey(m3));
   assertFalse(sm.containsKey(m4));
   assertFalse(sm.containsKey(m5));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m2, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(m2));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(m3), null);
   assertEquals(4, map.size());
 }
  @Override
  public void report(
      SortedMap<String, Gauge> gauges,
      SortedMap<String, Counter> counters,
      SortedMap<String, Histogram> histograms,
      SortedMap<String, Meter> meters,
      SortedMap<String, Timer> timers) {
    final Date timestamp = new Date(clock.getTime());

    List<DBObject> docs =
        Lists.newArrayListWithExpectedSize(
            gauges.size() + counters.size() + histograms.size() + meters.size() + timers.size());

    collectGaugeReports(docs, gauges, timestamp);
    collectCounterReports(docs, counters, timestamp);
    collectHistogramReports(docs, histograms, timestamp);
    collectMeterReports(docs, meters, timestamp);
    collectTimerReports(docs, timers, timestamp);

    try {
      final DBCollection collection =
          mongoConnection.getDatabase().getCollection("graylog2_metrics");
      // don't hang on to the data for too long.
      final BasicDBObject indexField = new BasicDBObject("timestamp", 1);
      final BasicDBObject indexOptions = new BasicDBObject("expireAfterSeconds", 5 * 60);
      collection.createIndex(indexField, indexOptions);

      collection.insert(docs, WriteConcern.UNACKNOWLEDGED);
    } catch (Exception e) {
      LOG.warn("Unable to write graylog2 metrics to mongodb. Ignoring this error.", e);
    }
  }
Exemplo n.º 5
0
    @Override
    protected void reportInContext(
        MetricContext context,
        SortedMap<String, Gauge> gauges,
        SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms,
        SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

      Assert.assertEquals(context.getName(), CONTEXT_NAME);

      Assert.assertEquals(gauges.size(), 1);
      Assert.assertTrue(gauges.containsKey(QUEUE_SIZE));

      Assert.assertEquals(counters.size(), 1);
      Assert.assertTrue(counters.containsKey(RECORDS_PROCESSED));

      Assert.assertEquals(histograms.size(), 1);
      Assert.assertTrue(histograms.containsKey(RECORD_SIZE_DISTRIBUTION));

      Assert.assertEquals(meters.size(), 1);
      Assert.assertTrue(meters.containsKey(RECORD_PROCESS_RATE));

      Assert.assertEquals(timers.size(), 2);
      Assert.assertTrue(timers.containsKey(TOTAL_DURATION));
    }
Exemplo n.º 6
0
  private void registerProcess(HiveMetaStoreBridge dgiBridge, HiveEventContext event)
      throws Exception {
    Set<ReadEntity> inputs = event.getInputs();
    Set<WriteEntity> outputs = event.getOutputs();

    // Even explain CTAS has operation name as CREATETABLE_AS_SELECT
    if (inputs.isEmpty() && outputs.isEmpty()) {
      LOG.info("Explain statement. Skipping...");
      return;
    }

    if (event.getQueryId() == null) {
      LOG.info("Query id/plan is missing for {}", event.getQueryStr());
    }

    final SortedMap<Entity, Referenceable> source = new TreeMap<>(entityComparator);
    final SortedMap<Entity, Referenceable> target = new TreeMap<>(entityComparator);

    final Set<String> dataSets = new HashSet<>();
    final Set<Referenceable> entities = new LinkedHashSet<>();

    boolean isSelectQuery = isSelectQuery(event);

    // filter out select queries which do not modify data
    if (!isSelectQuery) {
      for (ReadEntity readEntity : event.getInputs()) {
        processHiveEntity(dgiBridge, event, readEntity, dataSets, source, entities);
      }

      for (WriteEntity writeEntity : event.getOutputs()) {
        processHiveEntity(dgiBridge, event, writeEntity, dataSets, target, entities);
      }

      if (source.size() > 0 || target.size() > 0) {
        Referenceable processReferenceable =
            getProcessReferenceable(dgiBridge, event, source, target);
        entities.add(processReferenceable);
        event.addMessage(
            new HookNotification.EntityUpdateRequest(event.getUser(), new ArrayList<>(entities)));
      } else {
        LOG.info(
            "Skipped query {} since it has no getInputs() or resulting getOutputs()",
            event.getQueryStr());
      }
    } else {
      LOG.info("Skipped query {} for processing since it is a select query ", event.getQueryStr());
    }
  }
  /** Cleanup references to committed transactions that are no longer needed. */
  synchronized void removeUnNeededCommitedTransactions() {
    Integer minStartSeqNumber = getMinStartSequenceNumber();
    if (minStartSeqNumber == null) {
      minStartSeqNumber = Integer.MAX_VALUE; // Remove all
    }

    int numRemoved = 0;
    // Copy list to avoid conc update exception
    for (Entry<Integer, TransactionState> entry :
        new LinkedList<Entry<Integer, TransactionState>>(
            commitedTransactionsBySequenceNumber.entrySet())) {
      if (entry.getKey() >= minStartSeqNumber) {
        break;
      }
      numRemoved =
          numRemoved
              + (commitedTransactionsBySequenceNumber.remove(entry.getKey()) == null ? 0 : 1);
      numRemoved++;
    }

    if (LOG.isDebugEnabled()) {
      StringBuilder debugMessage = new StringBuilder();
      if (numRemoved > 0) {
        debugMessage.append("Removed [").append(numRemoved).append("] commited transactions");

        if (minStartSeqNumber == Integer.MAX_VALUE) {
          debugMessage.append(" with any sequence number.");
        } else {
          debugMessage.append(" with sequence lower than [").append(minStartSeqNumber).append("].");
        }
        if (!commitedTransactionsBySequenceNumber.isEmpty()) {
          debugMessage
              .append(" Still have [")
              .append(commitedTransactionsBySequenceNumber.size())
              .append("] left.");
        } else {
          debugMessage.append(" None left.");
        }
        LOG.debug(debugMessage.toString());
      } else if (commitedTransactionsBySequenceNumber.size() > 0) {
        debugMessage
            .append("Could not remove any transactions, and still have ")
            .append(commitedTransactionsBySequenceNumber.size())
            .append(" left");
        LOG.debug(debugMessage.toString());
      }
    }
  }
Exemplo n.º 8
0
  /**
   * 1st column is Element (Sequence/OTU/tree leaf), 2nd is taxid
   *
   * @param inFilePath
   * @return
   * @throws IOException
   */
  public static SortedMap<String, Taxon> importElementTaxonomyMap(Path inFilePath)
      throws IOException, XMLStreamException {
    SortedMap<String, Taxon> otuTaxaMap = new TreeMap<>();
    BufferedReader reader = getReader(inFilePath, "Element taxonomy mapping");

    Separator lineSeparator = new Separator("\t");
    String line = reader.readLine();
    while (line != null) {
      if (hasContent(line)) { // not comments or empty
        String[] items = lineSeparator.parse(line);
        if (items.length < 2)
          throw new IllegalArgumentException(
              "Invalid file format for Element taxonomy mapping, line : " + line);
        if (otuTaxaMap.containsKey(items[0]))
          throw new IllegalArgumentException("Find duplicate name for " + items[0]);

        Taxon taxon = TaxonomyPool.getAndAddTaxIdByMemory(items[1]);
        otuTaxaMap.put(items[0], taxon);
      }

      line = reader.readLine();
    }
    reader.close();

    if (otuTaxaMap.size() < 1) throw new IllegalArgumentException("OTU taxonomy map is empty !");

    return otuTaxaMap;
  }
Exemplo n.º 9
0
 /**
  * Convert buffer name to editor object before call back to command executable
  *
  * @see
  *     com.mulgasoft.emacsplus.minibuffer.WithMinibuffer#executeResult(org.eclipse.ui.texteditor.ITextEditor,
  *     java.lang.Object)
  */
 @Override
 protected boolean executeResult(ITextEditor editor, Object minibufferResult) {
   String bufferName = (String) minibufferResult;
   IEditorReference result = null;
   if (bufferName != null && bufferName.length() > 0) {
     // get the editor reference by name
     result = getBufferList().get(bufferName);
     if (result == null) {
       try {
         // Attempt auto-completion if name fetch failed
         SortedMap<String, IEditorReference> viewTree = getBuffers(bufferName, false, false);
         if (viewTree.size() == 1) {
           bufferName = viewTree.firstKey();
           result = viewTree.get(bufferName);
         }
       } catch (Exception e) {
         // Could be a java.util.regex.PatternSyntaxException on weird input
         // when looking for a match; just ignore and command will abort
       }
     }
   } else if (defaultFile != null) {
     result = defaultFile;
   }
   if (result != null) {
     addToHistory(result.getName());
     setExecuting(true);
     // remember the executable as getEditor(true), if it has to restore the editor,
     // will automatically give it focus, which results in a call to out focusLost....
     IMinibufferExecutable ex = getExecutable();
     super.executeResult(editor, ex, result.getEditor(true));
   } else {
     beep();
   }
   return true;
 }
Exemplo n.º 10
0
 /**
  * Loads images into this container. You must call {@link #setContext(Context)} first to set the
  * context for loading images.
  */
 public synchronized void init() {
   if (null != images) return;
   // store images sorted by their file name suffix
   SortedMap<String, Integer> builtinImageIds = new TreeMap<String, Integer>();
   for (Field field : R.drawable.class.getFields())
     try {
       if (Modifier.STATIC == (field.getModifiers() & Modifier.STATIC)
           && Integer.TYPE == field.getType()
           && field.getName().startsWith(IMAGE_FILE_PREFIX)) {
         String suffix = field.getName().substring(IMAGE_FILE_PREFIX.length());
         int id = field.getInt(null);
         builtinImageIds.put(suffix, id);
       }
     } catch (IllegalAccessException skipNoAccess) {
     }
   images = new ImageEntry[builtinImageIds.size()];
   int i = 0;
   // add built-in images
   for (Map.Entry<String, Integer> entry : builtinImageIds.entrySet()) {
     Integer id = entry.getValue();
     Integer difficulty = null;
     try {
       difficulty = Integer.valueOf(entry.getKey());
     } catch (NumberFormatException ignored) {
     }
     ImageEntry image;
     if (null != difficulty && 0 <= difficulty && 3 > difficulty)
       image = new ImageEntry(id, difficulty + 3);
     else image = new ImageEntry(id);
     images[i++] = image;
   }
   updateUserImages();
 }
  @Override
  public void select(
      final String statementName, final Object parameterObject, final ResultHandler handler) {
    if (isSqlAuditorBehaviorEnabled()) {
      getSqlAuditor()
          .audit(
              statementName,
              getSqlByStatementName(statementName, parameterObject),
              parameterObject);
    }
    if (isPartitioningBehaviorEnabled()) {
      SortedMap<String, DataSource> dsMap =
          lookupDataSourcesByRouter(statementName, parameterObject);
      if (dsMap != null && !dsMap.isEmpty()) {
        SqlSessionCallback action =
            new SqlSessionCallback() {
              @Override
              public Object doInSession(SqlSession sqlSession) {
                sqlSession.select(statementName, parameterObject, handler);
                return null;
              }
            };

        if (dsMap.size() == 1) {
          executeWith(dsMap.get(dsMap.firstKey()), action);
        } else {
          executeInConcurrency(action, dsMap);
        }
      }
    }
    super.select(statementName, parameterObject, handler);
  }
Exemplo n.º 12
0
  /** @see it.matrix.aod.postel.at.ATParserImpl#getRigheDettaglio(java.util.SortedMap) */
  @Override
  public Dettaglio[] getRigheDettaglio(SortedMap<Integer, String> _map) {
    Dettaglio[] righeDettaglio = new Dettaglio[_map.size()];
    Iterator<Entry<Integer, String>> mit = _map.entrySet().iterator();
    int i = 0;
    while (mit.hasNext()) {
      Entry<Integer, String> entry = (Entry<Integer, String>) mit.next();
      String value = entry.getValue();
      String record = value;
      Dettaglio rigaDettaglio = new Dettaglio();
      rigaDettaglio.setPeriodoRiferimento("");
      if (!record.equals("") && record.length() >= 55) {

        rigaDettaglio.setDescrizione(value.substring(0, 55));
        value = value.substring(rigaDettaglio.getDescrizione().length()).trim();

        if (record.charAt(61) != ' ') {
          rigaDettaglio.setPrezzo(value.substring(0, value.indexOf(' ')));
          value = value.substring(rigaDettaglio.getPrezzo().length()).trim();
        } else {
          rigaDettaglio.setPrezzo("");
        }
        if (record.charAt(68) != ' ') {
          rigaDettaglio.setQuantita(value.substring(0, value.indexOf(' ')));
          value = value.substring(rigaDettaglio.getQuantita().length()).trim();
        } else {
          rigaDettaglio.setQuantita("");
        }
        if (record.charAt(70) != ' ') {
          rigaDettaglio.setAliquotaIva(value.substring(0, value.indexOf(' ')));
          value = value.substring(rigaDettaglio.getQuantita().length()).trim();
        } else {
          rigaDettaglio.setAliquotaIva(value.substring(0, value.indexOf(' ')));
        }

        value = value.substring(rigaDettaglio.getAliquotaIva().length()).trim();
        rigaDettaglio.setImporto(value);

      } else if (!record.equals("") && record.length() < 55) {
        rigaDettaglio.setAliquotaIva("");
        rigaDettaglio.setImporto("");
        rigaDettaglio.setPrezzo("");
        rigaDettaglio.setPeriodoRiferimento("");
        rigaDettaglio.setQuantita("");
        rigaDettaglio.setDescrizione(record.trim());

      } else {
        rigaDettaglio.setAliquotaIva("");
        rigaDettaglio.setDescrizione("");
        rigaDettaglio.setImporto("");
        rigaDettaglio.setPrezzo("");
        rigaDettaglio.setPeriodoRiferimento("");
        rigaDettaglio.setQuantita("");
      }
      righeDettaglio[i] = rigaDettaglio;
      i++;
    }

    return righeDettaglio;
  }
Exemplo n.º 13
0
  /**
   * set the status slots after insertion
   *
   * @param insertedChunk
   */
  protected void chunkInserted(IChunk insertedChunk) {
    if (isCapacityReached()) setBufferChunk(getFullChunk());
    else setStatusSlotContent(IStatusBuffer.BUFFER_SLOT, _sourceChunks.size());

    setStateChunk(getFreeChunk());
    setErrorChunk(null);
  }
Exemplo n.º 14
0
  /**
   * 增加一个新节点 @Title: addCacheNode
   *
   * @author: zzh
   * @date: 2016年12月2日 下午8:56:38
   * @version: v1.0.0
   */
  private static void addCacheNode() {

    // 添加到真实Node列表
    CacheNode newNode = new CacheNode("10.9.1.100");
    realNodeList.add(newNode);
    // 生成虚拟节点
    List<VisualCacheNode> addVisualNodeList = genVisualCacheNode(newNode);

    // 查询哪些节点受到影响,即数据需要分散
    for (VisualCacheNode vnode : addVisualNodeList) {
      String nodeName = vnode.getNodeName();
      String md5VisualNodeKey = DigestUtils.md5Hex(nodeName); // 使用common-codec工具包
      int hashNodeName = DJBHash(md5VisualNodeKey);
      SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName + 1); // 排除掉自己。
      VisualCacheNode nodeInfo = null;
      if (vs != null && vs.size() > 0) {
        int affectVnshash = vs.firstKey();
        nodeInfo = visualNodeMap.get(affectVnshash);
      } else {
        nodeInfo = visualNodeMap.get(visualNodeMap.firstKey());
      }
      System.out.println("新添节点,受到影响的虚拟节点:" + nodeInfo);
    }

    // 将虚拟节点加入到hash环中
    addVisualCacheNodeIntoCircle(addVisualNodeList);
  }
Exemplo n.º 15
0
  /**
   * 删除节点。 @Title: removeCacheNode
   *
   * @author: zzh
   * @date: 2016年12月4日 下午8:34:15
   * @version: v1.0.0
   */
  private static void removeCacheNode(String nodeIp) {

    // 删除当前IP的虚拟节点信息
    CacheNode cacheNode = new CacheNode(nodeIp);
    // 获取当前节点的虚拟节点信息
    List<VisualCacheNode> vNodesList = genVisualCacheNode(cacheNode);
    // 从hash环中删除虚拟节点信息
    for (VisualCacheNode c : vNodesList) {
      String vNodeName = c.getNodeName();
      String md5VisualNodeKey = DigestUtils.md5Hex(vNodeName); // 使用common-codec工具包
      int hashNodeName = DJBHash(md5VisualNodeKey);

      visualNodeMap.remove(hashNodeName);

      System.out.println("删除虚拟节点,虚拟节点名称:" + vNodeName + ",真实节点:" + c.getRealCacheNode());

      // 删除后,受到影响的节点:即数据和流量需要迁移到的节点信息
      SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName);
      VisualCacheNode nodeInfo = null;
      if (vs != null && vs.size() > 0) {
        int affectVnshash = vs.firstKey();
        nodeInfo = visualNodeMap.get(affectVnshash);
      } else {
        nodeInfo = visualNodeMap.get(visualNodeMap.firstKey());
      }
      System.out.println("删除当前虚拟节点" + vNodeName + " , 受到影响的虚拟节点(原本虚拟节点的数据和流量将迁移到此节点):" + nodeInfo);
    }

    // 踢出真实节点
    removeRealCache(nodeIp);
  }
Exemplo n.º 16
0
  /** {@inheritDoc} */
  public Sync[] getAndWriteLockAllSyncForKeys(long timeout, Object... keys)
      throws TimeoutException {
    SortedMap<ReadWriteLockSync, AtomicInteger> locks = getLockMap(keys);

    boolean lockHeld;
    List<ReadWriteLockSync> heldLocks = new ArrayList<ReadWriteLockSync>();

    Sync[] syncs = new Sync[locks.size()];
    int i = 0;
    for (Map.Entry<ReadWriteLockSync, AtomicInteger> entry : locks.entrySet()) {
      while (entry.getValue().getAndDecrement() > 0) {
        try {
          ReadWriteLockSync writeLockSync = entry.getKey();
          lockHeld = writeLockSync.tryLock(LockType.WRITE, timeout);
          if (lockHeld) {
            heldLocks.add(writeLockSync);
          }
        } catch (InterruptedException e) {
          lockHeld = false;
        }

        if (!lockHeld) {
          for (int j = heldLocks.size() - 1; j >= 0; j--) {
            ReadWriteLockSync readWriteLockSync = heldLocks.get(j);
            readWriteLockSync.unlock(LockType.WRITE);
          }
          throw new TimeoutException("could not acquire all locks in " + timeout + " ms");
        }
      }
      syncs[i++] = entry.getKey();
    }
    return syncs;
  }
Exemplo n.º 17
0
 /**
  * Return a sorted map of column index by name.
  *
  * @param names all possible names for each column.
  * @param indexes index of the current name for each column.
  * @return a sorted map.
  */
 private SortedMap<String, Integer> solve(final String[][] names, final int[] indexes) {
   final int columnCount = names.length;
   // columns' index by name
   final CollectionMap<String, Integer> collisions =
       new CollectionMap<String, Integer>(columnCount);
   for (int i = 0; i < columnCount; i++) {
     final int index = indexes[i];
     if (index >= names[i].length)
       throw new IllegalStateException(
           "Ran out of names for " + i + " : " + Arrays.asList(names[i]));
     final String columnName = names[i][index];
     collisions.put(columnName, i);
   }
   final SortedMap<String, Integer> res = new TreeMap<String, Integer>();
   for (Entry<String, Collection<Integer>> e : collisions.entrySet()) {
     final Collection<Integer> indexesWithCollision = e.getValue();
     if (indexesWithCollision.size() > 1) {
       // increment only the minimum indexes to try to solve the conflict with the lowest
       // possible indexes
       int minIndex = Integer.MAX_VALUE;
       for (final Integer i : indexesWithCollision) {
         if (indexes[i] < minIndex) minIndex = indexes[i];
       }
       // now increment all indexes equal to minimum
       for (final Integer i : indexesWithCollision) {
         if (indexes[i] == minIndex) indexes[i]++;
       }
     } else {
       res.put(e.getKey(), indexesWithCollision.iterator().next());
     }
   }
   if (res.size() == columnCount) return res;
   else return solve(names, indexes);
 }
Exemplo n.º 18
0
    public Channel getChannel(String name) {
      synchronized (channels) {
        Channel channel = channels.get(name);
        if (channel == null) {
          boolean resize = false;

          channel = channels.remove(INITIAL);
          if (channel == null) {
            channel = new Channel(name);
            resize = true;
          } else {
            channel.setName(name);
          }

          channels.put(name, channel);
          channelArray = channels.values().toArray(new Channel[channels.size()]);

          if (resize) {
            getDisplay()
                .syncExec(
                    new Runnable() {
                      public void run() {
                        controlResized(null);
                      }
                    });
          }
        }

        return channel;
      }
    }
Exemplo n.º 19
0
  public ImponibileIva[] getRigheImponibiliIva(SortedMap<Integer, String> _map) {

    ImponibileIva[] righeImponibiliIva = new ImponibileIva[_map.size()];

    Iterator<Entry<Integer, String>> mit = _map.entrySet().iterator();

    while (mit.hasNext()) {
      Entry<Integer, String> entry = (Entry<Integer, String>) mit.next();
      String value = entry.getValue();

      ImponibileIva imponibileIva = new ImponibileIva();
      imponibileIva.setIndice(entry.getKey());
      if (!value.equals("")) {

        imponibileIva.setImponibile(value.substring(0, value.indexOf(' ')));
        value = value.substring(imponibileIva.getImponibile().length()).trim();
        imponibileIva.setAliquota(value.substring(0, value.indexOf(' ')));
        value = value.substring(imponibileIva.getAliquota().length()).trim();
        imponibileIva.setDescrizione(value);
      } else {

        imponibileIva.setImponibile("");
        imponibileIva.setAliquota("");
        imponibileIva.setDescrizione("");
      }
      righeImponibiliIva[entry.getKey()] = imponibileIva;
    }
    return righeImponibiliIva;
  }
Exemplo n.º 20
0
  private List<ChatMessage> sanitizeMap(final SortedMap<Date, ChatMessage> aMap) {
    if (aMap.isEmpty() || aMap.size() == 1) return Lists.newArrayList(aMap.values());

    final LinkedList<ChatMessage> ret = Lists.newLinkedList(aMap.values());
    final ListIterator<ChatMessage> i = ret.listIterator();
    ChatMessage prevMsg = i.next();
    do {
      ChatMessage msg = i.next();
      if (!msg.getPreviousMessageDate().equals(prevMsg.getDate())) {
        if (msg.getPreviousMessageDate().before(prevMsg.getDate())) {
          msg.setPreviousMessageDate(prevMsg.getDate());
        } else {
          final ChatMessage tmp =
              createLostMessageBetween(
                  msg.getRoom(), prevMsg.getDate(), msg.getPreviousMessageDate());
          aMap.put(tmp.getDate(), tmp);
          i.previous();
          i.add(tmp);
          i.next();
          msg = tmp;
        }
      }
      prevMsg = msg;
    } while (i.hasNext());

    return ret;
  }
Exemplo n.º 21
0
 public boolean next(SubRequest request) {
   MOScope scope = request.getQuery().getScope();
   SortedMap<OID, Variable> tail = vbs.tailMap(scope.getLowerBound());
   OID first = tail.firstKey();
   if (scope.getLowerBound().equals(first) && (!scope.isLowerIncluded())) {
     if (tail.size() > 1) {
       Iterator<OID> it = tail.keySet().iterator();
       it.next();
       first = it.next();
     } else {
       return false;
     }
   }
   if (first != null) {
     Variable vb = vbs.get(first);
     if (vb == null) {
       request.getVariableBinding().setVariable(Null.noSuchInstance);
     }
     request.getVariableBinding().setOid(first);
     request.getVariableBinding().setVariable(vb);
     request.completed();
     return true;
   }
   return false;
 }
  /*
   * values[]: the alphabet (provided as Integers) bitLengths[]: the number of
   * bits of symbil's huffman code
   */
  public CanonicalHuffmanIntegerCodec(int[] values, int[] bitLengths) {
    super();

    // 1. Sort by (a) bit length and (b) by symbol value -----------
    SortedMap codebook = new TreeMap<Integer, SortedSet<Integer>>();
    for (int i = 0; i < values.length; i++) {
      if (codebook.containsKey(bitLengths[i]))
        ((TreeSet) codebook.get(bitLengths[i])).add(values[i]);
      else {
        TreeSet<Integer> entry = new TreeSet<Integer>();
        entry.add(values[i]);
        codebook.put(bitLengths[i], entry);
      }
    }
    codeLentghSorted = new Integer[codebook.size()];
    int keys = 0;

    // 2. Calculate and Assign Canonical Huffman Codes -------------
    int codeLength = 0, codeValue = -1; // first Canonical is always 0
    codes = new TreeMap<Integer, HuffmanBitCode>();
    Set keySet = codebook.keySet();
    for (Object key : keySet) { // Iterate over code lengths
      int iKey = Integer.parseInt(key.toString());
      codeLentghSorted[keys++] = iKey;

      TreeSet<Integer> get = (TreeSet<Integer>) codebook.get(key);
      for (Integer entry : get) { // Iterate over symbols
        HuffmanBitCode code = new HuffmanBitCode();
        code.bitLentgh = iKey; // given: bit length
        code.value = entry; // given: symbol

        codeValue++; // increment bit value by 1
        int delta = iKey - codeLength; // new length?
        codeValue = codeValue << delta; // pad with 0's
        code.bitCode = codeValue; // calculated: huffman code
        codeLength += delta; // adjust current code len

        if (NumberOfSetBits(codeValue) > iKey)
          throw new IllegalArgumentException("Symbol out of range");

        codes.put(entry, code); // Store HuffmanBitCode

        Map<Long, Integer> codeMap = codeCache.get(code.bitLentgh);
        if (codeMap == null) {
          codeMap = new HashMap<Long, Integer>();
          codeCache.put(code.bitLentgh, codeMap);
        }
        codeMap.put(new Long(code.bitCode), code.value);
      }
    }

    // 3. Done. Just have to populate codeMaps ---------------------
    if (codeLentghSorted.length > 0)
      codeMaps = new Map[codeLentghSorted[codeLentghSorted.length - 1] + 1];
    else codeMaps = new Map[1];
    for (int len : codeLentghSorted) { // Iterate over code lengths
      codeMaps[len] = codeCache.get(len);
    }
  }
Exemplo n.º 23
0
 /** Looks up the {@link StringInfo} object for a JavaScript string. Creates it if necessary. */
 private StringInfo getOrCreateStringInfo(String string) {
   StringInfo info = stringInfoMap.get(string);
   if (info == null) {
     info = new StringInfo(stringInfoMap.size());
     stringInfoMap.put(string, info);
   }
   return info;
 }
Exemplo n.º 24
0
 @Override
 public long size() {
   if (associative_mode) {
     return associative_array.size();
   } else {
     return array.size();
   }
 }
Exemplo n.º 25
0
 public void addAction(Action action, int weight) {
   int last = 0;
   if (actions.size() > 0) {
     for (int x : actions.keySet()) {
       last = x;
     }
   }
   actions.put(last + weight, action);
 }
  /**
   * Change the session id. Note that this will change the session id for all contexts for which the
   * session id is in use.
   *
   * @see org.eclipse.jetty.nosql.NoSqlSessionManager#update(org.eclipse.jetty.nosql.NoSqlSession,
   *     java.lang.String, java.lang.String)
   */
  @Override
  protected void update(NoSqlSession session, String newClusterId, String newNodeId)
      throws Exception {
    __log.debug(
        "KVStoreSessionManager:update session {} to {}", session.getClusterId(), newClusterId);
    SortedMap<Key, ValueVersion> old_keyvalues =
        _kvstorehandler.multiGet(
            Key.createKey(Arrays.asList(__storeprefix, session.getClusterId())),
            null,
            Depth.PARENT_AND_DESCENDANTS);

    if (old_keyvalues != null && old_keyvalues.size() > 0) {
      this.kvstore_object_ops.clear();
      ValueVersion expiry_old_val = null;
      for (Entry<Key, ValueVersion> old_entry : old_keyvalues.entrySet()) {
        List<String> major_keypart = old_entry.getKey().getMajorPath();
        List<String> minor_keypart = old_entry.getKey().getMinorPath();
        if (old_entry
            .getKey()
            .toString()
            .startsWith(__storeprefix + "/" + session.getClusterId() + "/" + __EXPIRY)) {
          // got expiry value, save it for linkback
          expiry_old_val = old_entry.getValue();
        }
        this.kvstore_object_ops.add(
            this.kvstore_opfactory.createPut(
                Key.createKey(major_keypart, minor_keypart), old_entry.getValue().getValue()));

        major_keypart.set(1, newClusterId);
      }
      if (this.kvstore_object_ops.size() > 0) {
        _kvstorehandler.execute(this.kvstore_object_ops);
        this.kvstore_object_ops.clear();
        _kvstorehandler.multiDelete(
            Key.createKey(Arrays.asList(__storeprefix, session.getClusterId())),
            null,
            Depth.PARENT_AND_DESCENDANTS);
      }
      if (expiry_old_val != null) {
        _kvstorehandler.put(
            Key.createKey(
                Arrays.asList(
                    __expirydailyindexprefix,
                    new String(expiry_old_val.getValue().getValue()),
                    "UTF-8"),
                Arrays.asList(newClusterId)),
            Value.EMPTY_VALUE);
        _kvstorehandler.delete(
            Key.createKey(
                Arrays.asList(
                    __expirydailyindexprefix,
                    new String(expiry_old_val.getValue().getValue()),
                    "UTF-8"),
                Arrays.asList(session.getClusterId())));
      }
    }
  }
Exemplo n.º 27
0
 public void updateActions() {
   if (mActions.size() == 1) {
     ActionItem action = mPrimaryAction;
     actionButton.setVisibility(VISIBLE);
     actionButton.setImageDrawable(action.icon);
   } else {
     actionButton.setVisibility(GONE);
   }
 }
Exemplo n.º 28
0
  /**
   * Flush the nodes in order, from the lowest level to highest level. As a flush dirties its
   * parent, add it to the dirty map, thereby cascading the writes up the tree. If flushAll wasn't
   * specified, we need only cascade up to the highest level that existed before the checkpointing
   * started.
   *
   * <p>Note that all but the top level INs and the BINDeltas are logged provisionally. That's
   * because we don't need to process lower INs because the higher INs will end up pointing at them.
   */
  private void flushDirtyNodes(boolean flushAll, boolean allowDeltas, boolean flushExtraLevel)
      throws DatabaseException {

    LogManager logManager = envImpl.getLogManager();

    SortedMap dirtyMap = selectDirtyINs(flushAll, flushExtraLevel);

    while (dirtyMap.size() > 0) {

      /* Work on one level's worth of nodes in ascending level order. */
      Integer currentLevel = (Integer) dirtyMap.firstKey();
      boolean logProvisionally = (currentLevel.intValue() != highestFlushLevel);

      Set nodeSet = (Set) dirtyMap.get(currentLevel);
      Iterator iter = nodeSet.iterator();

      /* Flush all those nodes */
      while (iter.hasNext()) {
        IN target = (IN) iter.next();
        target.latch();
        boolean triedToFlush = false;

        /*
         * Only flush the ones that are still dirty -- some
         * may have been written out by the evictor. Also
         * check if the db is still valid -- since INs of
         * deleted databases are left on the in-memory tree
         * until the evictor lazily clears them out, there may
         * be dead INs around.
         */
        if (target.getDirty() && (!target.getDatabase().getIsDeleted())) {
          flushIN(target, logManager, dirtyMap, logProvisionally, allowDeltas);
          triedToFlush = true;
        } else {
          target.releaseLatch();
        }

        Tracer.trace(
            Level.FINE,
            envImpl,
            "Checkpointer: node="
                + target.getNodeId()
                + " level="
                + Integer.toHexString(target.getLevel())
                + " flushed="
                + triedToFlush);
      }

      /* We're done with this level. */
      dirtyMap.remove(currentLevel);

      /* We can stop at this point. */
      if (currentLevel.intValue() == highestFlushLevel) {
        break;
      }
    }
  }
Exemplo n.º 29
0
 // Note: this Javadoc is copied from javax.management.Descriptor
 //       due to 6369229.
 @Override
 public synchronized int hashCode() {
   final int size = descriptorMap.size();
   // descriptorMap is sorted with a comparator that ignores cases.
   //
   return Util.hashCode(
       descriptorMap.keySet().toArray(new String[size]),
       descriptorMap.values().toArray(new Object[size]));
 }
Exemplo n.º 30
0
  @Override
  public void fillLayout(final SipProfile account) {
    super.fillLayout(account);

    accountUsername.setTitle(R.string.w_advanced_caller_id);
    accountUsername.setDialogTitle(R.string.w_advanced_caller_id_desc);

    boolean recycle = true;
    providerListPref = (ListPreference) findPreference(PROVIDER_LIST_KEY);
    if (providerListPref == null) {
      Log.d(THIS_FILE, "Create new list pref");
      providerListPref = new ListPreference(parent);
      providerListPref.setKey(PROVIDER_LIST_KEY);
      recycle = false;
    } else {
      Log.d(THIS_FILE, "Recycle existing list pref");
    }

    CharSequence[] v = new CharSequence[providers.size()];
    int i = 0;
    for (String pv : providers.keySet()) {
      v[i] = pv;
      i++;
    }

    providerListPref.setEntries(v);
    providerListPref.setEntryValues(v);
    providerListPref.setKey(PROVIDER);
    providerListPref.setDialogTitle("Provider");
    providerListPref.setTitle("Provider");
    providerListPref.setSummary("Betamax clone provider");
    providerListPref.setDefaultValue("12VoIP");

    if (!recycle) {
      addPreference(providerListPref);
    }
    hidePreference(null, SERVER);

    String domain = account.getDefaultDomain();
    if (domain != null) {
      for (Entry<String, String[]> entry : providers.entrySet()) {
        String[] val = entry.getValue();
        if (val[0].equalsIgnoreCase(domain)) {
          Log.d(THIS_FILE, "Set provider list pref value to " + entry.getKey());
          providerListPref.setValue(entry.getKey());
          break;
        }
      }
    }
    Log.d(THIS_FILE, providerListPref.getValue());

    // Get wizard specific row
    customWizardText = (TextView) parent.findViewById(R.id.custom_wizard_text);
    customWizard = (LinearLayout) parent.findViewById(R.id.custom_wizard_row);

    updateAccountInfos(account);
  }