Java 类org.apache.commons.lang.mutable.MutableInt 实例源码

项目:engerek    文件:TestImportRecon.java   
private void assertDummyAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, 
            new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext);

       final MutableInt count = new MutableInt(0);
       ResultHandler<ShadowType> handler = (shadow, parentResult) -> {
        count.increment();
        display("Found",shadow);
        return true;
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
       assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue());
}
项目:engerek    文件:AbstractModelIntegrationTest.java   
protected <O extends ObjectType> void searchObjectsIterative(Class<O> type, ObjectQuery query, Consumer<PrismObject<O>> handler, Integer expectedNumberOfObjects) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
    Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".assertObjects");
      OperationResult result = task.getResult();
      final MutableInt count = new MutableInt(0);
// Cannot convert to lambda here. Java does not want to understand the generic types properly.
SearchResultMetadata searchMetadata = modelService.searchObjectsIterative(type, query, new ResultHandler<O>() {
        @Override
        public boolean handle(PrismObject<O> object, OperationResult oresult) {
            count.increment();
            if (handler != null) {
                handler.accept(object);
            }
            return true;
        }
    }, null, task, result);
      if (verbose) display(type.getSimpleName()+"s", count.getValue());
      assertEquals("Unexpected number of "+type.getSimpleName()+"s", expectedNumberOfObjects, count.getValue());
  }
项目:engerek    文件:TestLdap.java   
private void assertOpenDjAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, 
            new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext);

       final MutableInt count = new MutableInt(0);
       ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            count.increment();
            display("Found",shadow);
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
       assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue());
}
项目:engerek    文件:AbstractLdapConnTest.java   
private void singleInfernoSearch(ObjectQuery query, int expectedNumberOfResults, Integer offset, Integer maxSize, String sortAttrName, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectPaging paging = ObjectPaging.createPaging(offset, maxSize);
       paging.setOrdering(getAttributePath(resource, sortAttrName), OrderDirection.ASCENDING);
    query.setPaging(paging);

    final MutableInt count = new MutableInt();
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> object, OperationResult parentResult) {
            count.increment();
            return true;
        }
    };

    modelService.searchObjectsIterative(ShadowType.class, query, handler, null, task, result);

    assertEquals("Unexpected number of search results", expectedNumberOfResults, count.intValue());
}
项目:dataz-core    文件:DataStoreStatesTest.java   
@Test
public void in_which_order_should_multiple_registered_callbacks_executed() throws Exception {
    // arrange / given
    final MutableInt result=new MutableInt(0);
    final DataStoreState initial=DataStoreStates.create(originDataStore);

    final DataStoreState reserved = initial.reserve();
    reserved.register((ds)->result.setValue(result.intValue()/5));                              // result /=5
    reserved.register((ds)->result.setValue(result.intValue()*20));                              // result *=20
    reserved.register((ds)->result.setValue(result.intValue()+7));                               // result += 7

    // act / when
    reserved.release();

    // assert / then
    assertThat("Executed in LIFO-Order?", result.intValue(), is((7*20)/5));
}
项目:systemml    文件:ReaderTextCSV.java   
@Override
public MatrixBlock readMatrixFromInputStream(InputStream is, long rlen, long clen, int brlen, int bclen, long estnnz) 
    throws IOException, DMLRuntimeException 
{
    //allocate output matrix block
    MatrixBlock ret = createOutputMatrixBlock(rlen, clen, (int)rlen, (int)clen, estnnz, true, false);

    //core read 
    long lnnz = readCSVMatrixFromInputStream(is, "external inputstream", ret, new MutableInt(0), rlen, clen, 
        brlen, bclen, _props.hasHeader(), _props.getDelim(), _props.isFill(), _props.getFillValue(), true);

    //finally check if change of sparse/dense block representation required
    ret.setNonZeros( lnnz );
    ret.examSparsity();

    return ret;
}
项目:PrisonArchitect-translation    文件:Row.java   
private static String getWord(String line, MutableInt pos) {
    String word = "";
    boolean marker = false;
    boolean start = false;
    char ch;

    word = "";
    if (line.length() > 0) {
        do {
            ch = line.charAt(pos.intValue());
            start |=  ((ch != ' ') || (ch != '\t'));
            if (ch == '"') marker = !marker;

            if ((marker && start) || (start && (ch != ' ' && ch != '\t'))) {
                word += ch;
            }

            pos.increment();
        } while ((pos.intValue() < line.length()) && (marker || !start || (ch != ' ' && ch != '\t')));
    }

    if (word.length() == 0) word = null;
    return word;
}
项目:PrisonArchitect-translation    文件:Row.java   
private String getAllFromPos(String line, MutableInt pos) {
    String word = "";
    boolean start = false;
    char ch;

    word = "";
    if (line.length() > 0) {
        do {
            ch = line.charAt(pos.intValue());
            start |=  ((ch != ' ') && (ch != '\t'));

            if (start || (ch != ' ' && ch != '\t')) {
                if (startValue == 0) startValue = pos.intValue();
                word += ch;
            }

            pos.increment();
        } while (pos.intValue() < line.length());

        endValue = pos.intValue();
    }

    if (word.length() == 0) word = null;
    return word;
}
项目:termsuite-core    文件:CasStatCounter.java   
@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    this.docIt++;
    Optional<SourceDocumentInformation> sourceDocumentAnnotation = JCasUtils.getSourceDocumentAnnotation(aJCas);
    if(sourceDocumentAnnotation.isPresent())
        this.cumulatedFileSize += sourceDocumentAnnotation.get().getDocumentSize();
    FSIterator<Annotation> it =  aJCas.getAnnotationIndex().iterator();
    Annotation a;
    MutableInt i;
    while(it.hasNext()) {
        a = it.next();
        i = counters.get(a.getType().getShortName());
        if(i == null) 
            counters.put(a.getType().getShortName(), new MutableInt(1));
        else
            i.increment();
    }
    if(periodicStatEnabled && this.docIt % this.docPeriod == 0)
        try {
            traceToFile();
        } catch (IOException e) {
            throw new AnalysisEngineProcessException(e);
        }
}
项目:TabChannels    文件:Subscriber.java   
public BaseComponent[] getChannelSelection() {
    String currentLine = " " + StringUtils.capitalize(currentChannel.getName(selfUUID));
    ComponentBuilder builder = new ComponentBuilder(currentLine).bold(true).color(ChatColor.GREEN);

    for (Map.Entry<Channel, MutableInt> entry : unreadChannels.entrySet()) {
        Channel channel = entry.getKey();
        int unreadMessage = entry.getValue().intValue();
        if (!channel.equals(currentChannel)) {
            builder.append(CHANNEL_SEPERATOR).reset();
            builder.append(channel.getName(selfUUID))
                    .color(ChatColor.GREEN)
                    .event(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/switch " + channel.getId()));

            //show the number of unread messages
            if (unreadMessage > 0) {
                builder.append("(").reset()
                        .append(Integer.toString(unreadMessage)).color(ChatColor.YELLOW)
                        .append(")").reset();
            }
        }
    }

    return builder.create();
}
项目:midpoint    文件:TestImportRecon.java   
private void assertDummyAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID,
            new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext);

       final MutableInt count = new MutableInt(0);
       ResultHandler<ShadowType> handler = (shadow, parentResult) -> {
        count.increment();
        display("Found",shadow);
        return true;
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
       assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue());
}
项目:midpoint    文件:AbstractModelIntegrationTest.java   
protected <O extends ObjectType> void searchObjectsIterative(Class<O> type, ObjectQuery query, Consumer<PrismObject<O>> handler, Integer expectedNumberOfObjects) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
    Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".assertObjects");
      OperationResult result = task.getResult();
      final MutableInt count = new MutableInt(0);
// Cannot convert to lambda here. Java does not want to understand the generic types properly.
SearchResultMetadata searchMetadata = modelService.searchObjectsIterative(type, query, new ResultHandler<O>() {
        @Override
        public boolean handle(PrismObject<O> object, OperationResult oresult) {
            count.increment();
            if (handler != null) {
                handler.accept(object);
            }
            return true;
        }
    }, null, task, result);
      if (verbose) display(type.getSimpleName()+"s", count.getValue());
      assertEquals("Unexpected number of "+type.getSimpleName()+"s", expectedNumberOfObjects, count.getValue());
  }
项目:midpoint    文件:TestLdap.java   
private void assertOpenDjAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID,
            new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext);

       final MutableInt count = new MutableInt(0);
       ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            count.increment();
            display("Found",shadow);
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
       assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue());
}
项目:midpoint    文件:AbstractLdapConnTest.java   
private void singleInfernoSearch(ObjectQuery query, int expectedNumberOfResults, Integer offset, Integer maxSize, String sortAttrName, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectPaging paging = ObjectPaging.createPaging(offset, maxSize);
       paging.setOrdering(getAttributePath(resource, sortAttrName), OrderDirection.ASCENDING);
    query.setPaging(paging);

    final MutableInt count = new MutableInt();
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> object, OperationResult parentResult) {
            count.increment();
            return true;
        }
    };

    modelService.searchObjectsIterative(ShadowType.class, query, handler, null, task, result);

    assertEquals("Unexpected number of search results", expectedNumberOfResults, count.intValue());
}
项目:gatk    文件:MutectDownsampler.java   
/**
 * @param maxReadsPerAlignmentStart Maximum number of reads per alignment start position. Must be > 0
 * @param stride Length in bases constituting a single pool of reads to downsample
 */
public MutectDownsampler(final int maxReadsPerAlignmentStart,
                         final int maxSuspiciousReadsPerAlignmentStart,
                         final int stride) {
    // convert coverage per base to coverage per stride
    maxCoverage = maxReadsPerAlignmentStart <= 0 ? Integer.MAX_VALUE : (maxReadsPerAlignmentStart * stride);
    this.stride = ParamUtils.isPositive(stride, "stride must be > 0");
    maxSuspiciousReadsPerStride = maxSuspiciousReadsPerAlignmentStart <= 0 ? Integer.MAX_VALUE : stride * ParamUtils.isPositive(maxSuspiciousReadsPerAlignmentStart, "maxSuspiciousReadsPerAlignmentStart must be > 0");

    pendingReads = new ArrayList<>();
    finalizedReads = new ArrayList<>();
    rejectAllReadsInStride = false;
    suspiciousReadCount = new MutableInt(0);

    clearItems();
    resetStats();
}
项目:gatk    文件:OxoGReadCounts.java   
/**
 *  If the allele is not in the count mappings, then it is not counted.  No exception will be thrown
 *  Modifies count variables in place.
 *
 * @param pileupElement pileup overlapping the alleles
 * @param f1r2Counts a mapping of allele to f1r2 counts
 * @param f2r1Counts a mapping of allele to f2r1 counts
 */
private static void incrementCounts(final PileupElement pileupElement, final Map<Allele, MutableInt> f1r2Counts,
                                final Map<Allele, MutableInt> f2r1Counts, final Allele referenceAllele,
                                    final List<Allele> altAlleles, int minBaseQualityCutoff) {

    final Map<Allele, MutableInt> countMap = isF2R1(pileupElement.getRead()) ? f2r1Counts : f1r2Counts;

    final Allele pileupAllele = GATKProtectedVariantContextUtils.chooseAlleleForRead(pileupElement, referenceAllele, altAlleles, minBaseQualityCutoff);

    if (pileupAllele == null) {
        return;
    }

    if (countMap.containsKey(pileupAllele)) {
        countMap.get(pileupAllele).increment();
    }
}
项目:miru    文件:MiruAggregateUtil.java   
private void collectTerm(int fieldId,
    MiruTermId termId,
    boolean fieldTermIn,
    List<MiruTermId> fieldTermIds,
    Map<FieldAndTermId, MutableInt> termCollector) throws Exception {

    fieldTermIds.add(termId);

    if (termCollector != null) {
        MutableInt count = termCollector.computeIfAbsent(new FieldAndTermId(fieldId, termId), key -> new MutableInt());
        if (fieldTermIn) {
            count.increment();
        } else {
            count.decrement();
        }
    }
}
项目:lens    文件:ColumnarSQLRewriter.java   
/**
 * Check if expression is answerable from fact, then push it to fact pushdown subquery
 *
 * @param node
 * @return true if expressions is used
 */
public boolean isExpressionsAnswerableFromFact(ASTNode node) {
  boolean isAnswerable = true;
  for (int i = 0; i < node.getChildCount(); i++) {
    if (node.getChild(i).getType() == HiveParser.TOK_SELEXPR) {
      int cnt = getColumnCount((ASTNode) node.getChild(i));
      if (cnt >= 2) {
        if (cnt == getNumFactTableInExpressions((ASTNode) node.getChild(i), new MutableInt(0))) {
          isAnswerable = true;
        } else {
          isAnswerable = false;
        }
      }
    }
  }
  return isAnswerable;
}
项目:lens    文件:ColumnarSQLRewriter.java   
/**
 * Get number of fact columns used in the an expression
 *
 * @param node
 * @param count
 * @return Number of fact columns used in expression
 */
protected int getNumFactTableInExpressions(ASTNode node, MutableInt count) {

  if (node == null) {
    log.debug("ASTNode is null ");
    return 0;
  }
  if (node.getToken().getType() == HiveParser.TOK_TABLE_OR_COL) {
    String factAlias = getFactAlias();
    String table = node.getChild(0).getText();
    if (table.equals(factAlias)) {
      count.add(1);
    }
  }
  for (int i = 0; i < node.getChildCount(); i++) {
    ASTNode child = (ASTNode) node.getChild(i);
    getNumFactTableInExpressions(child, count);
  }

  return count.intValue();
}
项目:pinot    文件:RequestUtils.java   
private static FilterQuery traverseFilterQueryAndPopulateMap(FilterQueryTree tree,
    Map<Integer, FilterQuery> filterQueryMap, MutableInt currentId) {
  int currentNodeId = currentId.intValue();
  currentId.increment();

  final List<Integer> f = new ArrayList<Integer>();
  if (null != tree.getChildren()) {
    for (final FilterQueryTree c : tree.getChildren()) {
      int childNodeId = currentId.intValue();
      currentId.increment();

      f.add(childNodeId);
      final FilterQuery q = traverseFilterQueryAndPopulateMap(c, filterQueryMap, currentId);
      filterQueryMap.put(childNodeId, q);
    }
  }

  FilterQuery query = new FilterQuery();
  query.setColumn(tree.getColumn());
  query.setId(currentNodeId);
  query.setNestedFilterQueryIds(f);
  query.setOperator(tree.getOperator());
  query.setValue(tree.getValue());
  return query;
}
项目:pinot    文件:RequestUtils.java   
private static HavingFilterQuery traverseHavingFilterQueryAndPopulateMap(HavingQueryTree tree,
    Map<Integer, HavingFilterQuery> filterQueryMap, MutableInt currentId) {
  int currentNodeId = currentId.intValue();
  currentId.increment();

  final List<Integer> filterIds = new ArrayList<Integer>();
  if (null != tree.getChildren()) {
    for (final HavingQueryTree child : tree.getChildren()) {
      int childNodeId = currentId.intValue();
      currentId.increment();
      filterIds.add(childNodeId);
      final HavingFilterQuery filterQuery = traverseHavingFilterQueryAndPopulateMap(child, filterQueryMap, currentId);
      filterQueryMap.put(childNodeId, filterQuery);
    }
  }

  HavingFilterQuery havingFilterQuery = new HavingFilterQuery();
  havingFilterQuery.setAggregationInfo(tree.getAggregationInfo());
  havingFilterQuery.setId(currentNodeId);
  havingFilterQuery.setNestedFilterQueryIds(filterIds);
  havingFilterQuery.setOperator(tree.getOperator());
  havingFilterQuery.setValue(tree.getValue());
  return havingFilterQuery;
}
项目:fraudwall-util    文件:IndexedPriorityQueue.java   
/**
 * Adds the specified <code>entry</code> into this priority queue. It is
 * an error to call this method if the queue is full or if an entry already
 * exists in the queue with the same key as <code>entry</code>'s key.
 *
 * @throws ArrayIndexOutOfBoundsException
 *             if this priority queue is full
 * @throws IllegalArgumentException
 *             if this priority queue already contains an entry with the
 *             same key as <code>entry</code>'s key.
 * @return true (indicating that the priority queue was modified)
 *
 * @see #isFull
 * @see #pop
 */
@Override
public boolean add(Entry<V> entry) {
    if (isFull()) {
        throw new ArrayIndexOutOfBoundsException();
    }
    if (map.containsKey(entry.getKey())) {
        throw new IllegalArgumentException("Duplicate key");
    }
    MutableInt m = (spare != null) ? spare : new MutableInt();
    spare = null;
    pq[++N] = entry;
    m.setValue(N);
    map.put(entry.getKey(), m);
    swim(N);
    return true;
}
项目:jClipCorn    文件:NextEpisodeHelper.java   
public static CCEpisode findNextEpisode(CCSeries s) {
    List<CCEpisode> el = s.getEpisodeList();

    if (el.size() == 0) return null;

    NextEpisodeHeuristic heuristic = CCProperties.getInstance().PROP_SERIES_NEXT_EPISODE_HEURISTIC.getValue();

    switch (heuristic) {
        case AUTOMATIC: return findNextEpisode_Automatic(s, el);
        case FIRST_UNWATCHED: return findNextEpisode_FirstUnwatched(s, el);
        case NEXT_EPISODE: return findNextEpisode_AfterLastViewed(s, el);
        case CONTINUOUS: return findNextEpisode_Continuous(s, el, new MutableInt());
    }

    CCLog.addDefaultSwitchError(NextEpisodeHelper.class, heuristic);
    return null;
}
项目:midpoint    文件:TestImportRecon.java   
private void assertDummyAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID,
            new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext);

       final MutableInt count = new MutableInt(0);
       ResultHandler<ShadowType> handler = (shadow, parentResult) -> {
        count.increment();
        display("Found",shadow);
        return true;
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
       assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue());
}
项目:midpoint    文件:AbstractModelIntegrationTest.java   
protected <O extends ObjectType> void searchObjectsIterative(Class<O> type, ObjectQuery query, Consumer<PrismObject<O>> handler, Integer expectedNumberOfObjects) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
    Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".assertObjects");
      OperationResult result = task.getResult();
      final MutableInt count = new MutableInt(0);
// Cannot convert to lambda here. Java does not want to understand the generic types properly.
SearchResultMetadata searchMetadata = modelService.searchObjectsIterative(type, query, new ResultHandler<O>() {
        @Override
        public boolean handle(PrismObject<O> object, OperationResult oresult) {
            count.increment();
            if (handler != null) {
                handler.accept(object);
            }
            return true;
        }
    }, null, task, result);
      if (verbose) display(type.getSimpleName()+"s", count.getValue());
      assertEquals("Unexpected number of "+type.getSimpleName()+"s", expectedNumberOfObjects, count.getValue());
  }
项目:midpoint    文件:TestLdap.java   
private void assertOpenDjAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID,
            new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext);

       final MutableInt count = new MutableInt(0);
       ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> shadow, OperationResult parentResult) {
            count.increment();
            display("Found",shadow);
            return true;
        }
    };
    Collection<SelectorOptions<GetOperationOptions>> options = null;
    if (raw) {
        options = SelectorOptions.createCollection(GetOperationOptions.createRaw());
    }
    modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result);
       assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue());
}
项目:midpoint    文件:AbstractLdapConnTest.java   
private void singleInfernoSearch(ObjectQuery query, int expectedNumberOfResults, Integer offset, Integer maxSize, String sortAttrName, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    ObjectPaging paging = ObjectPaging.createPaging(offset, maxSize);
       paging.setOrdering(getAttributePath(resource, sortAttrName), OrderDirection.ASCENDING);
    query.setPaging(paging);

    final MutableInt count = new MutableInt();
    ResultHandler<ShadowType> handler = new ResultHandler<ShadowType>() {
        @Override
        public boolean handle(PrismObject<ShadowType> object, OperationResult parentResult) {
            count.increment();
            return true;
        }
    };

    modelService.searchObjectsIterative(ShadowType.class, query, handler, null, task, result);

    assertEquals("Unexpected number of search results", expectedNumberOfResults, count.intValue());
}
项目:ScoreboardStats    文件:RefreshTask.java   
@Override
public void run() {
    //let the players update smoother
    int remainingUpdates = getNextUpdates();
    for (Map.Entry<Player, MutableInt> entry : queue.entrySet()) {
        Player player = entry.getKey();
        MutableInt remainingTicks = entry.getValue();
        if (remainingTicks.intValue() == 0) {
            if (remainingUpdates != 0) {
                //Smoother refreshing; limit the updates
                plugin.getScoreboardManager().onUpdate(player);
                remainingTicks.setValue(20 * Settings.getInterval());
                remainingUpdates--;
            }
        } else {
            remainingTicks.decrement();
        }
    }

    nextGlobalUpdate--;
    if (nextGlobalUpdate == 0) {
        nextGlobalUpdate = 20 * Settings.getInterval();
        //update globals
        plugin.getReplaceManager().updateGlobals();
    }
}
项目:zeno    文件:DiffHistoryDataState.java   
private <T> Map<Object, List<T>> groupObjectsByKey(FastBlobTypeDeserializationState<T> deserializationState, TypeDiffInstruction<T> instruction, Map<Object, MutableInt> countsByKey) {
    Map<Object, List<T>> groupsByKey = new HashMap<Object, List<T>>(countsByKey.size());

    for (T obj : deserializationState) {
        Object key = instruction.getKeyFromObject(obj);
        List<T> groupList = groupsByKey.get(key);
        if (groupList == null) {
            int count = countsByKey.get(key).intValue();
            groupList = new ArrayList<T>(count);
            groupsByKey.put(key, groupList);
        }

        groupList.add(obj);
    }
    return groupsByKey;
}
项目:alfresco-repository    文件:BehaviourFilterImpl.java   
@Override
public void enableBehaviour(NodeRef nodeRef)
{
    ParameterCheck.mandatory("nodeRef",  nodeRef);

    if (logger.isDebugEnabled())
    {
        logger.debug("Behaviour: ENABLE (" + AlfrescoTransactionSupport.getTransactionId() + "): " + nodeRef + "/ALL");
    }

    TransactionalResourceHelper.decrementCount(KEY_FILTER_COUNT, false);

    if (!TransactionalResourceHelper.isResourcePresent(KEY_INSTANCE_FILTERS))
    {
        // Nothing was disabled
        return;
    }
    nodeRef = tenantService.getName(nodeRef);

    Map<NodeRef, MutableInt> instanceFilters = TransactionalResourceHelper.getMap(KEY_INSTANCE_FILTERS);
    MutableInt filter = instanceFilters.get(nodeRef);
    if (filter == null)
    {
        // Instance was not disabled
        return;
    }
    else if (filter.intValue() <= 0)
    {
        // Can't go below zero for this
    }
    else
    {
        filter.decrement();
    }

    if (logger.isDebugEnabled())
    {
        logger.debug("   Now:" + filter);
    }
}
项目:alfresco-repository    文件:BehaviourFilterImpl.java   
private ClassFilter getClassFilter(QName className)
{
    ParameterCheck.mandatory("className", className);

    // Check the global, first
    if (!isEnabled())
    {
        return null;
    }

    if (!TransactionalResourceHelper.isResourcePresent(KEY_CLASS_FILTERS))
    {
        // Nothing was disabled
        return null;
    }
    Map<ClassFilter, MutableInt> classFilters = TransactionalResourceHelper.getMap(KEY_CLASS_FILTERS);
    for (ClassFilter classFilter : classFilters.keySet())
    {
        if (classFilter.getClassName().equals(className))
        {
            MutableInt filterNumber = classFilters.get(classFilter);
            if (filterNumber != null && filterNumber.intValue() > 0 )
            {
                return classFilter;
            }
            break;
        }
    }
    return null;
}
项目:alfresco-repository    文件:BehaviourFilterImpl.java   
@Override
public boolean isEnabled(NodeRef nodeRef)
{
    ParameterCheck.mandatory("nodeRef",  nodeRef);

    // Check the class (includes global) and instance, first
    if (!isEnabled())
    {
        return false;
    }

    if (!TransactionalResourceHelper.isResourcePresent(KEY_INSTANCE_FILTERS))
    {
        // Nothing was disabled
        return true;
    }
    nodeRef = tenantService.getName(nodeRef);

    Map<NodeRef, MutableInt> instanceFilters = TransactionalResourceHelper.getMap(KEY_INSTANCE_FILTERS);
    MutableInt filter = instanceFilters.get(nodeRef);
    if (filter != null && filter.intValue() > 0)
    {
        // Instance was disabled
        return false;
    }
    return true;
}
项目:alfresco-repository    文件:ContentStoreCleanerScalabilityRunner.java   
private void loadData(final int maxCount)
{
    final MutableInt doneCount = new MutableInt(0);
    // Batches of 1000 objects
    RetryingTransactionCallback<Integer> makeNodesCallback = new RetryingTransactionCallback<Integer>()
    {
        public Integer execute() throws Throwable
        {
            for (int i = 0; i < 1000; i++)
            {
                // We don't need to write anything
                String contentUrl = FileContentStore.createNewFileStoreUrl();
                ContentData contentData = new ContentData(contentUrl, MimetypeMap.MIMETYPE_TEXT_PLAIN, 10, "UTF-8");
                nodeHelper.makeNode(contentData);

                int count = doneCount.intValue();
                count++;
                doneCount.setValue(count);

                // Do some reporting
                if (count % 1000 == 0)
                {
                    System.out.println(String.format("   " + (new Date()) + "Total created: %6d", count));
                }

                // Double check for shutdown
                if (vmShutdownListener.isVmShuttingDown())
                {
                    break;
                }
            }
            return maxCount;
        }
    };
    int repetitions = (int) Math.floor((double)maxCount / 1000.0);
    for (int i = 0; i < repetitions; i++)
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(makeNodesCallback);
    }
}
项目:alfresco-repository    文件:ConnectionPoolOverloadTest.java   
@Before
public void setUp() throws Exception
{
    failCount = new MutableInt(0);
    transactionService = ctx.getBean("transactionComponent", TransactionService.class);
    properties = ctx.getBean("global-properties", Properties.class);

    String dbPoolMaxProp = properties.getProperty("db.pool.max");
    if (PropertyCheck.isValidPropertyString(dbPoolMaxProp))
    {
        dbPoolMax = Integer.parseInt(dbPoolMaxProp);
    }
    else
    {
        throw new InvalidArgumentException("The db.pool.max property is not valid.");
    }

    String dbPoolWaitMaxProp = properties.getProperty("db.pool.wait.max");
    if (PropertyCheck.isValidPropertyString(dbPoolWaitMaxProp))
    {
        dbPoolWaitMax = Integer.parseInt(dbPoolWaitMaxProp);
    }
    else
    {
        throw new InvalidArgumentException("The db.pool.wait.max property is not valid.");
    }

    dbPoolWaitMax = dbPoolWaitMax == -1 ? 100 : dbPoolWaitMax;
}
项目:lams    文件:TransactionRetryInterceptor.java   
private void processException(Exception e, MethodInvocation invocation, MutableInt attempt) {
StringBuilder message = new StringBuilder("When invoking method \"").append(invocation.getMethod().getName())
    .append("\" caught \"").append(e.getMessage()).append("\". Attempt #").append(attempt);

attempt.increment();
if (attempt.intValue() <= TransactionRetryInterceptor.MAX_ATTEMPTS) {
    message.append(". Retrying.");
} else {
    message.append(". Giving up.");
}
TransactionRetryInterceptor.log.warn(message);
   }
项目:ditb    文件:ZkSplitLogWorkerCoordination.java   
/**
 * Submit a log split task to executor service
 * @param curTask task to submit
 * @param curTaskZKVersion current version of task
 */
void submitTask(final String curTask, final RecoveryMode mode, final int curTaskZKVersion,
    final int reportPeriod) {
  final MutableInt zkVersion = new MutableInt(curTaskZKVersion);

  CancelableProgressable reporter = new CancelableProgressable() {
    private long last_report_at = 0;

    @Override
    public boolean progress() {
      long t = EnvironmentEdgeManager.currentTime();
      if ((t - last_report_at) > reportPeriod) {
        last_report_at = t;
        int latestZKVersion =
            attemptToOwnTask(false, watcher, server.getServerName(), curTask,
              mode, zkVersion.intValue());
        if (latestZKVersion < 0) {
          LOG.warn("Failed to heartbeat the task" + curTask);
          return false;
        }
        zkVersion.setValue(latestZKVersion);
      }
      return true;
    }
  };
  ZkSplitLogWorkerCoordination.ZkSplitTaskDetails splitTaskDetails =
      new ZkSplitLogWorkerCoordination.ZkSplitTaskDetails();
  splitTaskDetails.setTaskNode(curTask);
  splitTaskDetails.setCurTaskZKVersion(zkVersion);

  WALSplitterHandler hsh =
      new WALSplitterHandler(server, this, splitTaskDetails, reporter,
          this.tasksInProgress, splitTaskExecutor, mode);
  server.getExecutorService().submit(hsh);
}
项目:ontobrowser    文件:XrefTagHandler.java   
@Override
void handleTagValue(String tag, String value, 
        String qualifierBlock, String comment) {
    int colon = indexOf(value, ':', 0);
    if(colon == -1) {
        throw new InvalidFormatException("Invalid OBO xref (no datasource): " + value);
    }
    String datasourceAcronym = value.substring(0,colon);
    int quote = indexOf(value, '"', colon+1);
    String refId = quote == -1 ? value.substring(colon+1) : value.substring(colon+1, quote);

    datasourceAcronym = context.unescapeTagValue(datasourceAcronym);
    refId = context.unescapeTagValue(refId);
    CrossReference xref = null;

    if(UrlParser.isValidProtocol(datasourceAcronym)) {
        String url = datasourceAcronym + ":" + refId;
        xref = addCrossReference(url, false);
    } else {
        xref = addCrossReference(datasourceAcronym, refId, false);
    }

    if(quote != -1) {
        MutableInt fromIndex = new MutableInt(quote);
        String description = substr(value, '"', '"', fromIndex);
        description = context.unescapeTagValue(description);
        xref.setDescription(description);
    }
}
项目:ontobrowser    文件:SynonymTagHandler.java   
private Synonym.Type parseType(String value, MutableInt fromIndex) {
    Synonym.Type type = Synonym.Type.RELATED;

    while(fromIndex.intValue() < value.length() 
            && Character.isWhitespace(value.charAt(fromIndex.intValue()))) {
        fromIndex.increment();
    }

    int start = fromIndex.intValue();

    while(fromIndex.intValue() < value.length() 
            && Character.isLetter(value.charAt(fromIndex.intValue()))) {
        fromIndex.increment();
    }

    if(start < fromIndex.intValue()) {
        String scope = value.substring(start, fromIndex.intValue());
        try {
            type = Synonym.Type.valueOf(scope.toUpperCase());
        } catch(IllegalArgumentException e) {
            type = Synonym.Type.RELATED;
            fromIndex.setValue(start);
        }
    }

    return type;
}
项目:apex-malhar    文件:ExactlyOnceJdbcOutputApp.java   
@Override
public void endWindow()
{
  for (Map.Entry<String, MutableInt> e: map.entrySet()) {
    counts.emit(new KeyValPair<>(e.getKey(), e.getValue().toInteger()));
  }
  map.clear();
}
项目:apex-malhar    文件:CountKeyVal.java   
/**
 * Emits on all ports that are connected. Data is computed during process on
 * input port and endWindow just emits it for each key. Clears the internal
 * data if resetAtEndWindow is true.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endWindow()
{
  for (Map.Entry<K, MutableInt> e : counts.entrySet()) {
    count.emit(new KeyValPair(e.getKey(),
        new Integer(e.getValue().intValue())));
  }
  counts.clear();
}