@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);
  }
 protected SortedMap<String, DataSource> lookupDataSourcesByRouter(
     final String statementName, final Object parameterObject) {
   SortedMap<String, DataSource> resultMap = new TreeMap<String, DataSource>();
   String namespace = StringUtils.substringBeforeLast(statementName, ".");
   String dsName = shardStrategy.getShardIdentitiesByNamespace(namespace, parameterObject);
   if (dsName == null) {
     throw new IllegalStateException("无法找到相应的分库资源,请检查参数列表中是否有传分库字段值, 参数:" + parameterObject);
   }
   resultMap.put(dsName, shardDataSourceService.getDataSources().get(dsName));
   return resultMap;
 }
Пример #3
0
 /**
  * Checks whether there are packets with sequence numbers between <tt>firstSeq</tt> and
  * <tt>lastSeq</tt> which are *not* stored in <tt>data</tt>.
  *
  * @return <tt>true</tt> if there are packets with sequence numbers between <tt>firstSeq</tt> and
  *     <tt>lastSeq</tt> which are *not* stored in <tt>data</tt>.
  */
 private boolean haveMissing() {
   Set<Long> seqs = data.keySet();
   long s = firstSeq;
   while (s != lastSeq) {
     if (!seqs.contains(s)) return true;
     s = (s + 1) % (1 << 16);
   }
   return false;
 }
  @Override
  public Map<?, ?> selectMap(
      final String statementName,
      final Object parameterObject,
      final String mapKey,
      final RowBounds rowBounds) {
    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<Map<?, ?>>() {
              @Override
              public Map<?, ?> doInSession(SqlSession sqlSession) {
                return sqlSession.selectMap(statementName, parameterObject, mapKey, rowBounds);
              }
            };

        if (dsMap.size() == 1) {
          return (Map<?, ?>) executeWith(dsMap.get(dsMap.firstKey()), action);
        } else {
          List<Object> results = executeInConcurrency(action, dsMap);
          Map<?, ?> retVal = Maps.newHashMap();
          if (results != null && !results.isEmpty()) {
            for (int i = 0; i < results.size(); i++) {
              retVal.putAll((Map) results.get(i));
            }
          }

          return retVal;
        }
      }
    }

    return super.selectMap(statementName, parameterObject, mapKey, rowBounds);
  }
Пример #5
0
  /**
   * Decode file charset.
   *
   * @param f File to process.
   * @return File charset.
   * @throws IOException in case of error.
   */
  public static Charset decode(File f) throws IOException {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();

    String[] firstCharsets = {
      Charset.defaultCharset().name(), "US-ASCII", "UTF-8", "UTF-16BE", "UTF-16LE"
    };

    Collection<Charset> orderedCharsets = U.newLinkedHashSet(charsets.size());

    for (String c : firstCharsets)
      if (charsets.containsKey(c)) orderedCharsets.add(charsets.get(c));

    orderedCharsets.addAll(charsets.values());

    try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
      FileChannel ch = raf.getChannel();

      ByteBuffer buf = ByteBuffer.allocate(4096);

      ch.read(buf);

      buf.flip();

      for (Charset charset : orderedCharsets) {
        CharsetDecoder decoder = charset.newDecoder();

        decoder.reset();

        try {
          decoder.decode(buf);

          return charset;
        } catch (CharacterCodingException ignored) {
        }
      }
    }

    return Charset.defaultCharset();
  }
  protected List<Object> executeInConcurrency(
      SqlSessionCallback action, SortedMap<String, DataSource> dsMap) {
    List<ConcurrentShardRequest> requests = Lists.newArrayList();

    for (Map.Entry<String, DataSource> entry : dsMap.entrySet()) {
      ConcurrentShardRequest request = new ConcurrentShardRequest();
      request.setAction(action);
      request.setDataSource(entry.getValue());
      request.setExecutor(dataSourceSpecificExecutors.get(entry.getKey()));
      requests.add(request);
    }
    return getConcurrentShardRequestProcessor().process(requests);
  }
  /**
   * 更新记录
   *
   * @param statementName
   * @param parameterObject
   * @return
   */
  @Override
  public int update(final String statementName, final Object parameterObject) {
    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) {
                return sqlSession.update(statementName, parameterObject);
              }
            };

        if (dsMap.size() == 1) {
          return (Integer) executeWith(dsMap.get(dsMap.firstKey()), action);
        } else {
          List<Object> results = executeInConcurrency(action, dsMap);

          Integer rowAffected = 0;

          if (results != null && !results.isEmpty()) {
            for (Object item : results) {
              rowAffected += (Integer) item;
            }
          }
          return rowAffected;
        }
      }
    }
    return super.update(statementName, parameterObject);
  }
 /**
  * Returns a grouped and sorted map of all registered metrics which match then given {@link
  * MetricPredicate}.
  *
  * @param predicate a predicate which metrics have to match to be in the results
  * @return all registered metrics which match {@code predicate}, sorted by name
  */
 public SortedMap<String, SortedMap<MetricName, Metric>> getGroupedMetrics(
     MetricPredicate predicate) {
   final SortedMap<String, SortedMap<MetricName, Metric>> groups =
       new TreeMap<String, SortedMap<MetricName, Metric>>();
   for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) {
     final String qualifiedTypeName = entry.getKey().getGroup() + "." + entry.getKey().getType();
     if (predicate.matches(entry.getKey(), entry.getValue())) {
       final String scopedName;
       if (entry.getKey().hasScope()) {
         scopedName = qualifiedTypeName + "." + entry.getKey().getScope();
       } else {
         scopedName = qualifiedTypeName;
       }
       SortedMap<MetricName, Metric> group = groups.get(scopedName);
       if (group == null) {
         group = new TreeMap<MetricName, Metric>();
         groups.put(scopedName, group);
       }
       group.put(entry.getKey(), entry.getValue());
     }
   }
   return Collections.unmodifiableSortedMap(groups);
 }
Пример #9
0
  /**
   * Re-initializes the fields which store information about the currently held data. Empties
   * <tt>data</tt>.
   */
  private void reinit() {
    firstSeq = lastSeq = timestamp = -1;
    pictureId = -1;
    empty = true;
    haveEnd = haveStart = false;
    frameLength = 0;

    Iterator<Map.Entry<Long, Container>> it = data.entrySet().iterator();
    Map.Entry<Long, Container> e;
    while (it.hasNext()) {
      e = it.next();
      free.offer(e.getValue());
      it.remove();
    }
  }
 /** headMap returns map with keys in requested range */
 public void testHeadMapContents() {
   ConcurrentNavigableMap map = map5();
   SortedMap sm = map.headMap(four);
   assertTrue(sm.containsKey(one));
   assertTrue(sm.containsKey(two));
   assertTrue(sm.containsKey(three));
   assertFalse(sm.containsKey(four));
   assertFalse(sm.containsKey(five));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(one, k);
   k = (Integer) (i.next());
   assertEquals(two, k);
   k = (Integer) (i.next());
   assertEquals(three, k);
   assertFalse(i.hasNext());
   sm.clear();
   assertTrue(sm.isEmpty());
   assertEquals(2, map.size());
   assertEquals(four, map.firstKey());
 }
 /** headMap returns map with keys in requested range */
 public void testDescendingHeadMapContents() {
   ConcurrentNavigableMap map = dmap5();
   SortedMap sm = map.headMap(m4);
   assertTrue(sm.containsKey(m1));
   assertTrue(sm.containsKey(m2));
   assertTrue(sm.containsKey(m3));
   assertFalse(sm.containsKey(m4));
   assertFalse(sm.containsKey(m5));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m1, k);
   k = (Integer) (i.next());
   assertEquals(m2, k);
   k = (Integer) (i.next());
   assertEquals(m3, k);
   assertFalse(i.hasNext());
   sm.clear();
   assertTrue(sm.isEmpty());
   assertEquals(2, map.size());
   assertEquals(m4, map.firstKey());
 }
Пример #12
0
  /** {@inheritDoc} */
  @Override
  protected int doProcess(Buffer inBuffer, Buffer outBuffer) {
    byte[] inData = (byte[]) inBuffer.getData();
    int inOffset = inBuffer.getOffset();

    if (!VP8PayloadDescriptor.isValid(inData, inOffset)) {
      logger.warn("Invalid RTP/VP8 packet discarded.");
      outBuffer.setDiscard(true);
      return BUFFER_PROCESSED_FAILED; // XXX: FAILED or OK?
    }

    long inSeq = inBuffer.getSequenceNumber();
    long inRtpTimestamp = inBuffer.getRtpTimeStamp();
    int inPictureId = VP8PayloadDescriptor.getPictureId(inData, inOffset);
    boolean inMarker = (inBuffer.getFlags() & Buffer.FLAG_RTP_MARKER) != 0;
    boolean inIsStartOfFrame = VP8PayloadDescriptor.isStartOfFrame(inData, inOffset);
    int inLength = inBuffer.getLength();
    int inPdSize = VP8PayloadDescriptor.getSize(inData, inOffset);
    int inPayloadLength = inLength - inPdSize;

    if (empty && lastSentSeq != -1 && seqNumComparator.compare(inSeq, lastSentSeq) != 1) {
      if (logger.isInfoEnabled()) logger.info("Discarding old packet (while empty) " + inSeq);
      outBuffer.setDiscard(true);
      return BUFFER_PROCESSED_OK;
    }

    if (!empty) {
      // if the incoming packet has a different PictureID or timestamp
      // than those of the current frame, then it belongs to a different
      // frame.
      if ((inPictureId != -1 && pictureId != -1 && inPictureId != pictureId)
          | (timestamp != -1 && inRtpTimestamp != -1 && inRtpTimestamp != timestamp)) {
        if (seqNumComparator.compare(inSeq, firstSeq) != 1) // inSeq <= firstSeq
        {
          // the packet belongs to a previous frame. discard it
          if (logger.isInfoEnabled()) logger.info("Discarding old packet " + inSeq);
          outBuffer.setDiscard(true);
          return BUFFER_PROCESSED_OK;
        } else // inSeq > firstSeq (and also presumably isSeq > lastSeq)
        {
          // the packet belongs to a subsequent frame (to the one
          // currently being held). Drop the current frame.

          if (logger.isInfoEnabled())
            logger.info(
                "Discarding saved packets on arrival of"
                    + " a packet for a subsequent frame: "
                    + inSeq);

          // TODO: this would be the place to complain about the
          // not-well-received PictureID by sending a RTCP SLI or NACK.
          reinit();
        }
      }
    }

    // a whole frame in a single packet. avoid the extra copy to
    // this.data and output it immediately.
    if (empty && inMarker && inIsStartOfFrame) {
      byte[] outData = validateByteArraySize(outBuffer, inPayloadLength, false);
      System.arraycopy(inData, inOffset + inPdSize, outData, 0, inPayloadLength);
      outBuffer.setOffset(0);
      outBuffer.setLength(inPayloadLength);
      outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp());

      if (TRACE) logger.trace("Out PictureID=" + inPictureId);

      lastSentSeq = inSeq;

      return BUFFER_PROCESSED_OK;
    }

    // add to this.data
    Container container = free.poll();
    if (container == null) container = new Container();
    if (container.buf == null || container.buf.length < inPayloadLength)
      container.buf = new byte[inPayloadLength];

    if (data.get(inSeq) != null) {
      if (logger.isInfoEnabled())
        logger.info("(Probable) duplicate packet detected, discarding " + inSeq);
      outBuffer.setDiscard(true);
      return BUFFER_PROCESSED_OK;
    }

    System.arraycopy(inData, inOffset + inPdSize, container.buf, 0, inPayloadLength);
    container.len = inPayloadLength;
    data.put(inSeq, container);

    // update fields
    frameLength += inPayloadLength;
    if (firstSeq == -1 || (seqNumComparator.compare(firstSeq, inSeq) == 1)) firstSeq = inSeq;
    if (lastSeq == -1 || (seqNumComparator.compare(inSeq, lastSeq) == 1)) lastSeq = inSeq;

    if (empty) {
      // the first received packet for the current frame was just added
      empty = false;
      timestamp = inRtpTimestamp;
      pictureId = inPictureId;
    }

    if (inMarker) haveEnd = true;
    if (inIsStartOfFrame) haveStart = true;

    // check if we have a full frame
    if (frameComplete()) {
      byte[] outData = validateByteArraySize(outBuffer, frameLength, false);
      int ptr = 0;
      Container b;
      for (Map.Entry<Long, Container> entry : data.entrySet()) {
        b = entry.getValue();
        System.arraycopy(b.buf, 0, outData, ptr, b.len);
        ptr += b.len;
      }

      outBuffer.setOffset(0);
      outBuffer.setLength(frameLength);
      outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp());

      if (TRACE) logger.trace("Out PictureID=" + inPictureId);
      lastSentSeq = lastSeq;

      // prepare for the next frame
      reinit();

      return BUFFER_PROCESSED_OK;
    } else {
      // frame not complete yet
      outBuffer.setDiscard(true);
      return OUTPUT_BUFFER_NOT_FILLED;
    }
  }
  /** headMap returns map with keys in requested range */
  public void testTailMapContents() {
    ConcurrentNavigableMap map = map5();
    SortedMap sm = map.tailMap(two);
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertTrue(sm.containsKey(four));
    assertTrue(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer) (i.next());
    assertEquals(two, k);
    k = (Integer) (i.next());
    assertEquals(three, k);
    k = (Integer) (i.next());
    assertEquals(four, k);
    k = (Integer) (i.next());
    assertEquals(five, k);
    assertFalse(i.hasNext());

    Iterator ei = sm.entrySet().iterator();
    Map.Entry e;
    e = (Map.Entry) (ei.next());
    assertEquals(two, e.getKey());
    assertEquals("B", e.getValue());
    e = (Map.Entry) (ei.next());
    assertEquals(three, e.getKey());
    assertEquals("C", e.getValue());
    e = (Map.Entry) (ei.next());
    assertEquals(four, e.getKey());
    assertEquals("D", e.getValue());
    e = (Map.Entry) (ei.next());
    assertEquals(five, e.getKey());
    assertEquals("E", e.getValue());
    assertFalse(i.hasNext());

    SortedMap ssm = sm.tailMap(four);
    assertEquals(four, ssm.firstKey());
    assertEquals(five, ssm.lastKey());
    assertEquals("D", ssm.remove(four));
    assertEquals(1, ssm.size());
    assertEquals(3, sm.size());
    assertEquals(4, map.size());
  }
 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());
 }
  /** headMap returns map with keys in requested range */
  public void testDescendingTailMapContents() {
    ConcurrentNavigableMap map = dmap5();
    SortedMap sm = map.tailMap(m2);
    assertFalse(sm.containsKey(m1));
    assertTrue(sm.containsKey(m2));
    assertTrue(sm.containsKey(m3));
    assertTrue(sm.containsKey(m4));
    assertTrue(sm.containsKey(m5));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer) (i.next());
    assertEquals(m2, k);
    k = (Integer) (i.next());
    assertEquals(m3, k);
    k = (Integer) (i.next());
    assertEquals(m4, k);
    k = (Integer) (i.next());
    assertEquals(m5, k);
    assertFalse(i.hasNext());

    Iterator ei = sm.entrySet().iterator();
    Map.Entry e;
    e = (Map.Entry) (ei.next());
    assertEquals(m2, e.getKey());
    assertEquals("B", e.getValue());
    e = (Map.Entry) (ei.next());
    assertEquals(m3, e.getKey());
    assertEquals("C", e.getValue());
    e = (Map.Entry) (ei.next());
    assertEquals(m4, e.getKey());
    assertEquals("D", e.getValue());
    e = (Map.Entry) (ei.next());
    assertEquals(m5, e.getKey());
    assertEquals("E", e.getValue());
    assertFalse(i.hasNext());

    SortedMap ssm = sm.tailMap(m4);
    assertEquals(m4, ssm.firstKey());
    assertEquals(m5, ssm.lastKey());
    assertEquals("D", ssm.remove(m4));
    assertEquals(1, ssm.size());
    assertEquals(3, sm.size());
    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());
 }