List of usage examples for com.google.common.collect Iterables getLast
public static <T> T getLast(Iterable<T> iterable)
From source file:org.sonar.java.se.JavaCheckVerifier.java
private void validateIssue(Multimap<Integer, Expectations.Issue> expected, List<Integer> unexpectedLines, AnalyzerMessage issue) {//from w w w. ja va 2s . c o m int line = issue.getLine(); if (expected.containsKey(line)) { Expectations.Issue attrs = Iterables.getLast(expected.get(line)); assertAttributeMatch(issue, attrs, MESSAGE); validateAnalyzerMessageAttributes(attrs, issue); expected.remove(line, attrs); } else { unexpectedLines.add(line); } }
From source file:nlp.pipeline.SentenceUtil.java
public static CoreMap getLastSentence(Annotation document) { List<CoreMap> sentences = document.get(SentencesAnnotation.class); if (!sentences.isEmpty()) { return Iterables.getLast(sentences); } else {/*from w ww . j a v a2 s . c o m*/ return null; } }
From source file:org.glowroot.ui.TransactionJsonService.java
@GET(path = "/backend/transaction/throughput", permission = "agent:transaction:overview") String getThroughput(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request, @BindAutoRefresh boolean autoRefresh) throws Exception { AggregateQuery query = toChartQuery(request, DataKind.GENERAL); long liveCaptureTime = clock.currentTimeMillis(); List<ThroughputAggregate> throughputAggregates = transactionCommonService .getThroughputAggregates(agentRollupId, query, autoRefresh); if (throughputAggregates.isEmpty() && fallBackToLargestAggregates(query)) { // fall back to largest aggregates in case expiration settings have recently changed query = withLargestRollupLevel(query); throughputAggregates = transactionCommonService.getThroughputAggregates(agentRollupId, query, autoRefresh);//from w w w. j a v a 2 s. c o m if (!throughputAggregates.isEmpty() && ignoreFallBackData(query, Iterables.getLast(throughputAggregates).captureTime())) { // this is probably data from before the requested time period throughputAggregates = ImmutableList.of(); } } long dataPointIntervalMillis = configRepository.getRollupConfigs().get(query.rollupLevel()) .intervalMillis(); List<DataSeries> dataSeriesList = getDataSeriesForThroughputChart(request, throughputAggregates, dataPointIntervalMillis, liveCaptureTime); // TODO more precise aggregate when from/to not on rollup grid long transactionCount = 0; for (ThroughputAggregate throughputAggregate : throughputAggregates) { long captureTime = throughputAggregate.captureTime(); if (captureTime > request.from() && captureTime <= request.to()) { transactionCount += throughputAggregate.transactionCount(); } } StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.writeStartObject(); jg.writeObjectField("dataSeries", dataSeriesList); jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis); jg.writeNumberField("transactionCount", transactionCount); jg.writeNumberField("transactionsPerMin", 60000.0 * transactionCount / (request.to() - request.from())); jg.writeEndObject(); } finally { jg.close(); } return sb.toString(); }
From source file:eu.trentorise.opendata.semtext.SemText.java
/** * Returns a copy of this object with the provided text set. *//*from ww w. ja v a 2 s .c om*/ public SemText with(String text) { checkNotNull(text); SemText ret = new SemText(this); ret.text = text; if (!sentences.isEmpty()) { int lastSentenceEnd = Iterables.getLast(sentences).getEnd(); if (lastSentenceEnd > text.length()) { throw new IllegalArgumentException("Tried to change text of semantic text, but last sentence end " + lastSentenceEnd + " exceeds provided text length! Semtext is\n:" + this + " \n new text to set is: " + text); } } return ret; }
From source file:com.google.gerrit.server.change.PostReviewers.java
private PatchSetApproval dummyApproval(ChangeControl ctl, PatchSet.Id patchSetId, Account.Id reviewerId) { LabelId id = Iterables.getLast(ctl.getLabelTypes().getLabelTypes()).getLabelId(); PatchSetApproval dummyApproval = new PatchSetApproval(new PatchSetApproval.Key(patchSetId, reviewerId, id), (short) 0); dummyApproval.cache(ctl.getChange()); return dummyApproval; }
From source file:org.zanata.service.impl.TranslationServiceImpl.java
private List<TranslationResult> translate(LocaleId localeId, List<TransUnitUpdateRequest> translationRequests, boolean runValidation) { List<TranslationResult> results = new ArrayList<TranslationResult>(); // avoid locale check if there is nothing to translate if (translationRequests.isEmpty()) { return results; }// www .j a va2 s .c om // single locale check - assumes update requests are all from the same // project-iteration HTextFlow sampleHTextFlow = entityManager.find(HTextFlow.class, translationRequests.get(0).getTransUnitId().getValue()); HProjectIteration projectIteration = sampleHTextFlow.getDocument().getProjectIteration(); HLocale hLocale = validateLocale(localeId, projectIteration); // single permission check - assumes update requests are all from same // project validateReviewPermissionIfApplicable(translationRequests, projectIteration, hLocale); List<TextFlowTargetStateChange> targetStates = Lists.newArrayList(); Map<ContentState, Long> contentStateDeltas = Maps.newHashMap(); for (TransUnitUpdateRequest request : translationRequests) { HTextFlow hTextFlow = entityManager.find(HTextFlow.class, request.getTransUnitId().getValue()); TranslationResultImpl result = new TranslationResultImpl(); if (runValidation) { String validationMessage = validateTranslations(request.getNewContentState(), projectIteration, request.getTransUnitId().toString(), hTextFlow.getContents(), request.getNewContents()); if (!StringUtils.isEmpty(validationMessage)) { log.warn(validationMessage); result.isSuccess = false; result.errorMessage = validationMessage; results.add(result); continue; } } HTextFlowTarget hTextFlowTarget = textFlowTargetDAO.getOrCreateTarget(hTextFlow, hLocale); // if hTextFlowTarget is created, any further hibernate fetch will // trigger an implicit flush // (which will save this target even if it's not fully ready!!!) if (request.hasTargetComment()) { // FIXME this creates orphan comments, and replaces identical // comments with copies hTextFlowTarget.setComment(new HSimpleComment(request.getTargetComment())); } result.baseVersion = hTextFlowTarget.getVersionNum(); result.baseContentState = hTextFlowTarget.getState(); if (request.getBaseTranslationVersion() == hTextFlowTarget.getVersionNum()) { try { int nPlurals = getNumPlurals(hLocale, hTextFlow); ContentState currentState = hTextFlowTarget.getState(); result.targetChanged = translate(hTextFlowTarget, request.getNewContents(), request.getNewContentState(), nPlurals, new TranslationDetails(request)); // fire event after flush if (result.targetChanged || hTextFlowTarget.getVersionNum() == 0) { HTextFlow textFlow = hTextFlowTarget.getTextFlow(); aggregateChanges(textFlow, hTextFlowTarget, currentState, targetStates, contentStateDeltas); } result.isSuccess = true; } catch (HibernateException e) { result.isSuccess = false; log.warn("HibernateException while translating"); } } else { // concurrent edits not allowed String errorMessage = "translation failed for textflow " + hTextFlow.getId() + ": base versionNum + " + request.getBaseTranslationVersion() + " does not match current versionNum " + hTextFlowTarget.getVersionNum(); log.warn(errorMessage); result.errorMessage = errorMessage; result.isVersionNumConflict = true; result.isSuccess = false; } result.translatedTextFlowTarget = hTextFlowTarget; results.add(result); } if (!targetStates.isEmpty()) { DocumentLocaleKey documentLocaleKey = new DocumentLocaleKey(sampleHTextFlow.getDocument().getId(), hLocale.getLocaleId()); TextFlowTargetStateEvent tftUpdatedEvent = new TextFlowTargetStateEvent(documentLocaleKey, projectIteration.getId(), authenticatedAccount.getPerson().getId(), ImmutableList.copyOf(targetStates)); textFlowTargetStateEvent.fire(tftUpdatedEvent); DocStatsEvent docEvent = new DocStatsEvent(documentLocaleKey, projectIteration.getId(), contentStateDeltas, Iterables.getLast(targetStates).getTextFlowTargetId()); docStatsEvent.fire(docEvent); } return results; }
From source file:com.github.benmanes.caffeine.cache.NodeFactoryGenerator.java
private void addNodeSpec(String className, boolean isFinal, Set<Feature> features) { TypeName superClass;// www.ja v a 2 s.co m Set<Feature> parentFeatures; Set<Feature> generateFeatures; if (features.size() == 2) { parentFeatures = ImmutableSet.of(); generateFeatures = features; superClass = TypeName.OBJECT; } else { parentFeatures = ImmutableSet.copyOf(Iterables.limit(features, features.size() - 1)); generateFeatures = ImmutableSet.of(Iterables.getLast(features)); superClass = ParameterizedTypeName.get( ClassName.get(PACKAGE_NAME + ".NodeFactory", encode(Feature.makeClassName(parentFeatures))), kTypeVar, vTypeVar); } NodeContext context = new NodeContext(superClass, className, isFinal, parentFeatures, generateFeatures); for (NodeRule rule : rules) { rule.accept(context); } nodeFactory.addType(context.nodeSubtype.build()); addEnumConstant(className, features); }
From source file:edu.buaa.satla.analysis.core.predicate.PredicateAbstractionRefinementStrategy.java
@Override public void performRefinement(ARGReachedSet pReached, List<ARGState> abstractionStatesTrace, List<BooleanFormula> pInterpolants, boolean pRepeatedCounterexample) throws CPAException, InterruptedException { pRepeatedCounterexample = !lastRefinementUsedHeuristics && pRepeatedCounterexample; if (useStaticRefinement()) { UnmodifiableReachedSet reached = pReached.asReachedSet(); ARGState root = (ARGState) reached.getFirstState(); ARGState refinementRoot = Iterables.getLast(root.getChildren()); PredicatePrecision heuristicPrecision; try {/*from w ww .j a v a 2s .com*/ heuristicPrecision = staticRefiner.extractPrecisionFromCfa(pReached.asReachedSet(), abstractionStatesTrace, atomicPredicates); } catch (CPATransferException | SolverException e) { logger.logUserException(Level.WARNING, e, "Static refinement failed"); lastRefinementUsedHeuristics = false; super.performRefinement(pReached, abstractionStatesTrace, pInterpolants, pRepeatedCounterexample); return; } shutdownNotifier.shutdownIfNecessary(); pReached.removeSubtree(refinementRoot, heuristicPrecision, PredicatePrecision.class); heuristicsCount++; lastRefinementUsedHeuristics = true; } else { lastRefinementUsedHeuristics = false; super.performRefinement(pReached, abstractionStatesTrace, pInterpolants, pRepeatedCounterexample); } }
From source file:com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl.java
@Override public RowQuery<K, C> getKey(final K rowKey) { return new AbstractRowQueryImpl<K, C>(columnFamily.getColumnSerializer()) { private boolean firstPage = true; @Override//from www. j a va2 s. c o m public ColumnQuery<C> getColumn(final C column) { return new ColumnQuery<C>() { @Override public OperationResult<Column<C>> execute() throws ConnectionException { return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Column<C>>( tracerFactory.newTracer(CassandraOperationType.GET_COLUMN, columnFamily), pinnedHost, keyspace.getKeyspaceName()) { @Override public Column<C> internalExecute(Client client, ConnectionContext context) throws Exception { ColumnOrSuperColumn cosc = client.get( columnFamily.getKeySerializer().toByteBuffer(rowKey), new org.apache.cassandra.thrift.ColumnPath() .setColumn_family(columnFamily.getName()) .setColumn(columnFamily.getColumnSerializer().toByteBuffer(column)), ThriftConverter.ToThriftConsistencyLevel(consistencyLevel)); if (cosc.isSetColumn()) { org.apache.cassandra.thrift.Column c = cosc.getColumn(); return new ThriftColumnImpl<C>( columnFamily.getColumnSerializer().fromBytes(c.getName()), c); } else if (cosc.isSetSuper_column()) { // TODO: Super columns // should be deprecated SuperColumn sc = cosc.getSuper_column(); return new ThriftSuperColumnImpl<C>( columnFamily.getColumnSerializer().fromBytes(sc.getName()), sc); } else if (cosc.isSetCounter_column()) { org.apache.cassandra.thrift.CounterColumn c = cosc.getCounter_column(); return new ThriftCounterColumnImpl<C>( columnFamily.getColumnSerializer().fromBytes(c.getName()), c); } else if (cosc.isSetCounter_super_column()) { // TODO: Super columns // should be deprecated CounterSuperColumn sc = cosc.getCounter_super_column(); return new ThriftCounterSuperColumnImpl<C>( columnFamily.getColumnSerializer().fromBytes(sc.getName()), sc); } else { throw new RuntimeException("Unknown column type in response"); } } @Override public ByteBuffer getRowKey() { return columnFamily.getKeySerializer().toByteBuffer(rowKey); } }, retry); } @Override public ListenableFuture<OperationResult<Column<C>>> executeAsync() throws ConnectionException { return executor.submit(new Callable<OperationResult<Column<C>>>() { @Override public OperationResult<Column<C>> call() throws Exception { return execute(); } }); } }; } @Override public OperationResult<ColumnList<C>> execute() throws ConnectionException { return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<ColumnList<C>>( tracerFactory.newTracer(CassandraOperationType.GET_ROW, columnFamily), pinnedHost, keyspace.getKeyspaceName()) { @Override public ColumnList<C> execute(Client client, ConnectionContext context) throws ConnectionException { if (isPaginating && paginateNoMore) { return new EmptyColumnList<C>(); } return super.execute(client, context); } @Override public ColumnList<C> internalExecute(Client client, ConnectionContext context) throws Exception { List<ColumnOrSuperColumn> columnList = client.get_slice( columnFamily.getKeySerializer().toByteBuffer(rowKey), new ColumnParent().setColumn_family(columnFamily.getName()), predicate, ThriftConverter.ToThriftConsistencyLevel(consistencyLevel)); // Special handling for pagination if (isPaginating && predicate.isSetSlice_range()) { // Did we reach the end of the query. if (columnList.size() != predicate.getSlice_range().getCount()) { paginateNoMore = true; } // If this is the first page then adjust the // count so we fetch one extra column // that will later be dropped if (firstPage) { firstPage = false; if (predicate.getSlice_range().getCount() != Integer.MAX_VALUE) predicate.getSlice_range().setCount(predicate.getSlice_range().getCount() + 1); } else { if (!columnList.isEmpty()) columnList.remove(0); } // Set the start column for the next page to // the last column of this page. // We will discard this column later. if (!columnList.isEmpty()) { ColumnOrSuperColumn last = Iterables.getLast(columnList); if (last.isSetColumn()) { predicate.getSlice_range().setStart(last.getColumn().getName()); } else if (last.isSetCounter_column()) { predicate.getSlice_range().setStart(last.getCounter_column().getName()); } else if (last.isSetSuper_column()) { // TODO: Super columns // should be deprecated predicate.getSlice_range().setStart(last.getSuper_column().getName()); } else if (last.isSetCounter_super_column()) { // TODO: Super columns // should be deprecated predicate.getSlice_range().setStart(last.getCounter_super_column().getName()); } } } ColumnList<C> result = new ThriftColumnOrSuperColumnListImpl<C>(columnList, columnFamily.getColumnSerializer()); return result; } @Override public ByteBuffer getRowKey() { return columnFamily.getKeySerializer().toByteBuffer(rowKey); } }, retry); } @Override public ColumnCountQuery getCount() { return new ColumnCountQuery() { @Override public OperationResult<Integer> execute() throws ConnectionException { return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Integer>( tracerFactory.newTracer(CassandraOperationType.GET_COLUMN_COUNT, columnFamily), pinnedHost, keyspace.getKeyspaceName()) { @Override public Integer internalExecute(Client client, ConnectionContext context) throws Exception { return client.get_count(columnFamily.getKeySerializer().toByteBuffer(rowKey), new ColumnParent().setColumn_family(columnFamily.getName()), predicate, ThriftConverter.ToThriftConsistencyLevel(consistencyLevel)); } @Override public ByteBuffer getRowKey() { return columnFamily.getKeySerializer().toByteBuffer(rowKey); } }, retry); } @Override public ListenableFuture<OperationResult<Integer>> executeAsync() throws ConnectionException { return executor.submit(new Callable<OperationResult<Integer>>() { @Override public OperationResult<Integer> call() throws Exception { return execute(); } }); } }; } @Override public ListenableFuture<OperationResult<ColumnList<C>>> executeAsync() throws ConnectionException { return executor.submit(new Callable<OperationResult<ColumnList<C>>>() { @Override public OperationResult<ColumnList<C>> call() throws Exception { return execute(); } }); } @Override public RowCopier<K, C> copyTo(final ColumnFamily<K, C> otherColumnFamily, final K otherRowKey) { return new RowCopier<K, C>() { private boolean useOriginalTimestamp = true; @Override public OperationResult<Void> execute() throws ConnectionException { return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Void>( tracerFactory.newTracer(CassandraOperationType.COPY_TO, columnFamily), pinnedHost, keyspace.getKeyspaceName()) { @Override public Void internalExecute(Client client, ConnectionContext context) throws Exception { long currentTime = keyspace.getConfig().getClock().getCurrentTime(); List<ColumnOrSuperColumn> columnList = client.get_slice( columnFamily.getKeySerializer().toByteBuffer(rowKey), new ColumnParent().setColumn_family(columnFamily.getName()), predicate, ThriftConverter.ToThriftConsistencyLevel(consistencyLevel)); // Create mutation list from columns in // the response List<Mutation> mutationList = new ArrayList<Mutation>(); for (ColumnOrSuperColumn sosc : columnList) { ColumnOrSuperColumn cosc; if (sosc.isSetColumn()) { cosc = new ColumnOrSuperColumn().setColumn(sosc.getColumn()); if (!useOriginalTimestamp) cosc.getColumn().setTimestamp(currentTime); } else if (sosc.isSetSuper_column()) { cosc = new ColumnOrSuperColumn().setSuper_column(sosc.getSuper_column()); if (!useOriginalTimestamp) { for (org.apache.cassandra.thrift.Column subColumn : sosc .getSuper_column().getColumns()) { subColumn.setTimestamp(currentTime); subColumn.setTimestamp(currentTime); } } } else if (sosc.isSetCounter_column()) { cosc = new ColumnOrSuperColumn() .setCounter_column(sosc.getCounter_column()); } else if (sosc.isSetCounter_super_column()) { cosc = new ColumnOrSuperColumn() .setCounter_super_column(sosc.getCounter_super_column()); } else { continue; } mutationList.add(new Mutation().setColumn_or_supercolumn(cosc)); } // Create mutation map Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>(); HashMap<String, List<Mutation>> cfmap = new HashMap<String, List<Mutation>>(); cfmap.put(otherColumnFamily.getName(), mutationList); mutationMap.put(columnFamily.getKeySerializer().toByteBuffer(otherRowKey), cfmap); // Execute the mutation client.batch_mutate(mutationMap, ThriftConverter.ToThriftConsistencyLevel(consistencyLevel)); return null; } }, retry); } @Override public ListenableFuture<OperationResult<Void>> executeAsync() throws ConnectionException { return executor.submit(new Callable<OperationResult<Void>>() { @Override public OperationResult<Void> call() throws Exception { return execute(); } }); } @Override public RowCopier<K, C> withOriginalTimestamp(boolean useOriginalTimestamp) { this.useOriginalTimestamp = useOriginalTimestamp; return this; } }; } }; }
From source file:org.sosy_lab.cpachecker.cpa.predicate.PredicateAbstractionRefinementStrategy.java
@Override public void performRefinement(ARGReachedSet pReached, List<ARGState> abstractionStatesTrace, List<BooleanFormula> pInterpolants, boolean pRepeatedCounterexample) throws CPAException, InterruptedException { pRepeatedCounterexample = !lastRefinementUsedHeuristics && pRepeatedCounterexample; if (useStaticRefinement()) { UnmodifiableReachedSet reached = pReached.asReachedSet(); ARGState root = (ARGState) reached.getFirstState(); ARGState refinementRoot = Iterables.getLast(root.getChildren()); PredicatePrecision heuristicPrecision; try {//w w w. j ava 2 s . c o m heuristicPrecision = staticRefiner.extractPrecisionFromCfa(pReached.asReachedSet(), abstractionStatesTrace, atomicPredicates); } catch (CPATransferException | SolverException e) { logger.logUserException(Level.WARNING, e, "Static refinement failed"); lastRefinementUsedHeuristics = false; super.performRefinement(pReached, abstractionStatesTrace, pInterpolants, pRepeatedCounterexample); return; } shutdownNotifier.shutdownIfNecessary(); pReached.removeSubtree(refinementRoot, heuristicPrecision, Predicates.instanceOf(PredicatePrecision.class)); heuristicsCount++; lastRefinementUsedHeuristics = true; } else { lastRefinementUsedHeuristics = false; super.performRefinement(pReached, abstractionStatesTrace, pInterpolants, pRepeatedCounterexample); } }