Java Code Examples for com.google.common.collect.Lists#reverse()

The following examples show how to use com.google.common.collect.Lists#reverse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityProcessor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public void addSecurityRules ( final Rules rules, final IProgressMonitor monitor )
{
    if ( rules == null )
    {
        return;
    }

    int priority = 1000;

    monitor.beginTask ( "Encoding security rules", rules.getRules ().size () );

    for ( final Rule rule : Lists.reverse ( rules.getRules () ) )
    {
        final RuleEncoder encoder = RuleEncoder.findEncoder ( rule );
        if ( encoder != null )
        {
            encoder.encodeRule ( this.ctx, priority += 100 );
        }
        monitor.worked ( 1 );
    }

    monitor.done ();
}
 
Example 2
Source File: MetadataUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
public static QualifiedObjectName createQualifiedObjectName(Session session, Node node, QualifiedName name)
{
    requireNonNull(session, "session is null");
    requireNonNull(name, "name is null");
    if (name.getParts().size() > 3) {
        throw new PrestoException(SYNTAX_ERROR, format("Too many dots in table name: %s", name));
    }

    List<String> parts = Lists.reverse(name.getParts());
    String objectName = parts.get(0);
    String schemaName = (parts.size() > 1) ? parts.get(1) : session.getSchema().orElseThrow(() ->
            semanticException(MISSING_SCHEMA_NAME, node, "Schema must be specified when session schema is not set"));
    String catalogName = (parts.size() > 2) ? parts.get(2) : session.getCatalog().orElseThrow(() ->
            semanticException(MISSING_CATALOG_NAME, node, "Catalog must be specified when session catalog is not set"));

    return new QualifiedObjectName(catalogName, schemaName, objectName);
}
 
Example 3
Source File: ResourceMapper.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
private List<String> resolveProductParts(String path) {
    // To speedup the lookup, we try to find the longest possible category path
    // Example for path: /var/commerce/products/cloudcommerce/Men/Coats/meskwielt.1-s
    // Remove root (/var/commerce/products/cloudcommerce) then try to find category /Men/Coats
    // --> we find the category /Men/Coats and try to fetch the product meskwielt.1-s

    // Example for path: /var/commerce/products/cloudcommerce/Men/Coats/meskwielt.1-s/meskwielt.2-l
    // Remove root (/var/commerce/products/cloudcommerce) then try to find category /Men/Coats/meskwielt.1-s
    // --> that category is not found, so we try to find the category /Men/Coats
    // --> we find the category /Men/Coats and try to fetch the product meskwielt.1-s and variant meskwielt.2-l

    String subPath = path.substring(root.length() + 1);
    int backtrackCounter = 0;
    List<String> productParts = new ArrayList<>();
    String[] parts = subPath.split("/");
    for (String part : Lists.reverse(Arrays.asList(parts))) {
        productParts.add(part);
        backtrackCounter -= part.length() + 1;
        String categorySubPath = StringUtils.substring(subPath, 0, backtrackCounter);
        if (graphqlDataService.getCategoryByPath(categorySubPath, storeView) != null) {
            break;
        }
    }
    productParts = Lists.reverse(productParts);
    return productParts;
}
 
Example 4
Source File: FileSystemView.java    From jimfs with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the {@linkplain Path#toRealPath(LinkOption...) real path} to the file located by the given
 * path.
 */
public JimfsPath toRealPath(
    JimfsPath path, PathService pathService, Set<? super LinkOption> options) throws IOException {
  checkNotNull(path);
  checkNotNull(options);

  store.readLock().lock();
  try {
    DirectoryEntry entry = lookUp(path, options).requireExists(path);

    List<Name> names = new ArrayList<>();
    names.add(entry.name());
    while (!entry.file().isRootDirectory()) {
      entry = entry.directory().entryInParent();
      names.add(entry.name());
    }

    // names are ordered last to first in the list, so get the reverse view
    List<Name> reversed = Lists.reverse(names);
    Name root = reversed.remove(0);
    return pathService.createPath(root, reversed);
  } finally {
    store.readLock().unlock();
  }
}
 
Example 5
Source File: SecurityRoleFunctionDaoTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSecurityRoleFunctionKeys()
{
    // Create a list of security role to function mapping keys.
    final List<SecurityRoleFunctionKey> securityRoleFunctionKeys = ImmutableList
        .of(new SecurityRoleFunctionKey(SECURITY_ROLE, SECURITY_FUNCTION), new SecurityRoleFunctionKey(SECURITY_ROLE, SECURITY_FUNCTION_2),
            new SecurityRoleFunctionKey(SECURITY_ROLE_2, SECURITY_FUNCTION), new SecurityRoleFunctionKey(SECURITY_ROLE_2, SECURITY_FUNCTION_2));

    // Create and persist security role to function mapping entities in reverse order.
    for (SecurityRoleFunctionKey securityRoleFunctionKey : Lists.reverse(securityRoleFunctionKeys))
    {
        securityRoleFunctionDaoTestHelper.createSecurityRoleFunctionEntity(securityRoleFunctionKey);
    }

    // Get a list of keys for all security role to function mappings registered in the system.
    assertEquals(securityRoleFunctionKeys, securityRoleFunctionDao.getSecurityRoleFunctionKeys());
}
 
Example 6
Source File: PhysicalPlan.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public List<PhysicalOperator> getSortedOperators(boolean reverse){
  List<PhysicalOperator> list = GraphAlgos.TopoSorter.sort(graph);
  if(reverse){
    return Lists.reverse(list);
  }else{
    return list;
  }

}
 
Example 7
Source File: TestConfiguration.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * @return number of times the given test should run. If the test doesn't match any of the
 *     filters, runs it once.
 */
public int getRunsPerTestForLabel(Label label) {
  for (PerLabelOptions perLabelRuns : Lists.reverse(options.runsPerTest)) {
    if (perLabelRuns.isIncluded(label)) {
      return Integer.parseInt(Iterables.getOnlyElement(perLabelRuns.getOptions()));
    }
  }
  return 1;
}
 
Example 8
Source File: SimpleLifeCycleRegistry.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() throws Exception {
    for (Managed managed : Lists.reverse(_managed)) {
        managed.stop();
    }
    _managed.clear();
}
 
Example 9
Source File: ExonumHttpClient.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
/**
 * Post-processes the blocks, coming from
 * {@link #doGetBlocks(int, BlockFilteringOption, Long, BlockTimeOption)}:
 * 1. Turns them in ascending order by height.
 * 2. Keeps only blocks that fall in range [fromHeight; toHeight].
 */
private static BlocksRange postProcessResponseBlocks(long fromHeight, long toHeight,
    List<Block> blocks) {
  // Turn the blocks in ascending order
  blocks = Lists.reverse(blocks);

  // Filter the possible blocks that are out of the requested range
  // No Stream#dropWhile in Java 8 :(
  int firstInRange = indexOf(blocks, b -> b.getHeight() >= fromHeight)
      .orElse(blocks.size());
  blocks = blocks.subList(firstInRange, blocks.size());

  // Do not bother trimming — BlocksRange copies the list
  return new BlocksRange(fromHeight, toHeight, blocks);
}
 
Example 10
Source File: CmdTopics.java    From pulsar with Apache License 2.0 5 votes vote down vote up
static MessageId findFirstLedgerWithinThreshold(List<PersistentTopicInternalStats.LedgerInfo> ledgers,
                                                long sizeThreshold) {
    long suffixSize = 0L;

    ledgers = Lists.reverse(ledgers);
    long previousLedger = ledgers.get(0).ledgerId;
    for (PersistentTopicInternalStats.LedgerInfo l : ledgers) {
        suffixSize += l.size;
        if (suffixSize > sizeThreshold) {
            return new MessageIdImpl(previousLedger, 0L, -1);
        }
        previousLedger = l.ledgerId;
    }
    return null;
}
 
Example 11
Source File: ObjectSchemeInitializer.java    From guice-persist-orient with MIT License 5 votes vote down vote up
/**
 * Register model scheme. If model class extends other classes, superclasses will be processed first
 * (bottom to top). On each class from hierarchy extensions are searched and applied. Processed classes are
 * cashed to avoid multiple processing of the same base model class.
 *
 * @param model model class
 */
public void register(final Class<?> model) {
    final ODatabaseObject db = dbProvider.get();
    // auto create schema for new classes
    ((OObjectDatabaseTx) db).setAutomaticSchemaGeneration(true);
    // processing lower hierarchy types first
    try {
        for (Class<?> type : Lists.reverse(SchemeUtils.resolveHierarchy(model))) {
            processType(db, type);
        }
    } catch (Throwable th) {
        throw new SchemeInitializationException("Failed to register model class " + model.getName(), th);
    }
}
 
Example 12
Source File: LazyXtaChecker.java    From theta with Apache License 2.0 5 votes vote down vote up
private void close(final ArgNode<XtaState<S>, XtaAction> coveree) {
	stats.startClosing();

	final Iterable<ArgNode<XtaState<S>, XtaAction>> candidates = Lists.reverse(passed.get(coveree));
	for (final ArgNode<XtaState<S>, XtaAction> coverer : candidates) {

		stats.checkCoverage();
		if (algorithmStrategy.mightCover(coveree, coverer)) {

			stats.attemptCoverage();

			coveree.setCoveringNode(coverer);
			final Collection<ArgNode<XtaState<S>, XtaAction>> uncoveredNodes = new ArrayList<>();
			algorithmStrategy.cover(coveree, coverer, uncoveredNodes, stats);

			waiting.addAll(uncoveredNodes.stream().filter(n -> !n.equals(coveree)));

			if (coveree.isCovered()) {
				stats.successfulCoverage();
				stats.stopClosing();
				return;
			}
		}
	}

	stats.stopClosing();
}
 
Example 13
Source File: AssignmentCreator2.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private List<WorkWrapper> createWorkList(List<T> completeWorkList) {
  List<WorkWrapper> workList = new ArrayList<>();
  for (T work : completeWorkList) {
    workList.add(new WorkWrapper(work));
  }

  Collections.sort(workList);

  // we want largest work units first in the list
  return Lists.reverse(workList);
}
 
Example 14
Source File: AsyncChannelAsserts.java    From c5-replicator with Apache License 2.0 5 votes vote down vote up
public T getLatest(Matcher<? super T> matcher) {
  synchronized (messageLog) {
    for (T element : Lists.reverse(messageLog)) {
      if (matcher.matches(element)) {
        return element;
      }
    }
  }
  return null;
}
 
Example 15
Source File: ReverseIterator.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Iterate using Guava {@link Lists} API.
 *
 * @param list the list
 */
public void iterateUsingGuava(final List<String> list) {

    final List<String> reversedList = Lists.reverse(list);
    for (final String item : reversedList) {
        System.out.println(item);
    }
}
 
Example 16
Source File: BreadCrumbs.java    From ForgeHax with MIT License 5 votes vote down vote up
private static List<Anchor> getPath(Anchor source, Anchor target, Map<Anchor, Anchor> prev) {
  final List<Anchor> out = new ArrayList<>();
  Anchor it = target;
  if (prev.containsKey(it) || it == source) {
    while (it != null) {
      out.add(it); // supposed to add to the beginning of the list but returning a reverse view will have the same effect
      it = prev.get(it);
    }
  }
  return Lists.reverse(out);
}
 
Example 17
Source File: LastTaskStatusMigration.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Override
public void applyMigration() {
  final long start = System.currentTimeMillis();
  final List<SingularityTaskId> taskIds = taskManager.getActiveTaskIds();

  for (SingularityTaskId taskId : taskIds) {
    List<SingularityTaskHistoryUpdate> updates = Lists.reverse(
      taskManager.getTaskHistoryUpdates(taskId)
    );
    Optional<MesosTaskStatusObject> taskStatus = Optional.empty();

    for (SingularityTaskHistoryUpdate update : updates) {
      if (update.getTaskState().toTaskState().isPresent()) {
        Optional<SingularityTask> task = taskManager.getTask(taskId);

        taskStatus =
          Optional.of(
            mesosProtosUtils.taskStatusFromProtos(
              TaskStatus
                .newBuilder()
                .setTaskId(TaskID.newBuilder().setValue(taskId.getId()))
                .setAgentId(MesosProtosUtils.toAgentId(task.get().getAgentId()))
                .setState(MesosProtosUtils.toTaskState(update.getTaskState()))
                .build()
            )
          );

        break;
      }
    }

    SingularityTaskStatusHolder taskStatusHolder = new SingularityTaskStatusHolder(
      taskId,
      taskStatus,
      start,
      serverId,
      Optional.empty()
    );

    taskManager.saveLastActiveTaskStatus(taskStatusHolder);
  }
}
 
Example 18
Source File: PipelineEventListener.java    From blueocean-plugin with MIT License 4 votes vote down vote up
List<String> getBranch(FlowNode flowNode) {
    return Lists.reverse(flowNode.getAllEnclosingIds());
}
 
Example 19
Source File: BaseResultIterators.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public static <T> List<T> reverseIfNecessary(List<T> list, boolean reverse) {
    if (!reverse) {
        return list;
    }
    return Lists.reverse(list);
}
 
Example 20
Source File: OperatorImplGraph.java    From samza with Apache License 2.0 4 votes vote down vote up
public void close() {
  List<OperatorImpl> initializationOrder = new ArrayList<>(operatorImpls.values());
  List<OperatorImpl> finalizationOrder = Lists.reverse(initializationOrder);
  finalizationOrder.forEach(OperatorImpl::close);
}