Java Code Examples for com.google.common.collect.Iterables#getFirst()

The following examples show how to use com.google.common.collect.Iterables#getFirst() . 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: LastHopOutgoingInterfaceManagerTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testTwoEdges() {
  Configuration c = configurationWithSession();
  String node = c.getHostname();
  String iface = Iterables.getFirst(c.getAllInterfaces().keySet(), null);
  Set<Edge> edges =
      ImmutableSet.of(Edge.of(NODE1, IFACE1, node, iface), Edge.of(NODE2, IFACE2, node, iface));
  LastHopOutgoingInterfaceManager mgr =
      new LastHopOutgoingInterfaceManager(_pkt, configs(c), edges);
  assertThat(mgr.getFiniteDomains().values(), not(empty()));
  BDD bdd1 = mgr.getLastHopOutgoingInterfaceBdd(NODE1, IFACE1, node, iface);
  BDD bdd2 = mgr.getLastHopOutgoingInterfaceBdd(NODE2, IFACE2, node, iface);
  assertFalse(bdd1.isZero());
  assertFalse(bdd1.isOne());
  assertFalse(bdd2.isZero());
  assertFalse(bdd2.isOne());
  assertTrue(!bdd1.equals(bdd2));
}
 
Example 2
Source File: ViewChanges.java    From morf with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a topological sort using a depth-first search algorithm and returns a sorted list of
 * database views for the schema upgrade.
 *
 * @param allViews all of the database views bound into the target schema.
 * @param index a complete index of all views in both the source and target schema.
 * @return a topologically sorted list {@link http://en.wikipedia.org/wiki/Topological_sorting} of view names
 */
private List<String> topoSortViews(Collection<View> allViews, Map<String, View> index) {
  if (log.isDebugEnabled()) {
    log.debug("Toposorting: " + Joiner.on(", ").join(Collections2.transform(allViews, viewToName())));
  }

  // The set of views we want to perform the sort on.
  Set<String> unmarkedViews = newHashSet(Collections2.transform(allViews, viewToName()));
  Set<String> temporarilyMarkedRecords = newHashSet();
  List<String> sortedList = newLinkedList();

  while (!unmarkedViews.isEmpty()) {
    String node = Iterables.getFirst(unmarkedViews, null);
    visit(node, temporarilyMarkedRecords, sortedList, index);
    unmarkedViews.remove(node);
  }

  return sortedList;
}
 
Example 3
Source File: MetadataTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private void testEndianess(String tsdl, ByteOrder traceEndian, ByteOrder fieldEndian) throws CTFException {
    fixture = new Metadata();
    CTFTrace trace = fixture.getTrace();
    fixture.parseText(tsdl);
    assertEquals(traceEndian, trace.getByteOrder());
    final Iterable<IEventDeclaration> eventDeclarations = trace.getEventDeclarations(0L);
    assertNotNull(eventDeclarations);
    IEventDeclaration event = Iterables.getFirst(eventDeclarations, null);
    assertNotNull(event);
    assertNotNull(event.getFields());
    final @Nullable IDeclaration field = event.getFields().getField("data");
    assertNotNull(field);
    if (field instanceof ISimpleDatatypeDeclaration) {
        ISimpleDatatypeDeclaration declaration = (ISimpleDatatypeDeclaration) field;
        assertEquals(fieldEndian, declaration.getByteOrder());
    } else {
        fail("data is not the right type");
    }
}
 
Example 4
Source File: ConfirmEmailHtmlNotificationDemoPage.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
public ConfirmEmailHtmlNotificationDemoPage(PageParameters parameters) {
	super(parameters);
	
	User user = userService.getByUserName(ConsoleNotificationIndexPage.DEFAULT_USERNAME);
	EmailAddress emailAddress = null;
	if (user != null) {
		emailAddress = Iterables.getFirst(user.getAdditionalEmails(), null);
	}
	if (user == null || emailAddress == null) {
		LOGGER.error("There is no user or email address available");
		Session.get().error(getString("console.notifications.noDataAvailable"));
		
		throw new RestartResponseException(ConsoleNotificationIndexPage.class);
	}

	if (emailAddress.getEmailHash() == null) {
		emailAddress.setEmailHash(userService.getHash(user, emailAddress.getEmail()));
	}
	
	add(new ConfirmEmailHtmlNotificationPanel("htmlPanel", Model.of(emailAddress)));
}
 
Example 5
Source File: LastHopOutgoingInterfaceManagerTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneEdge() {
  Configuration c = configurationWithSession();
  String node = c.getHostname();
  String iface = Iterables.getFirst(c.getAllInterfaces().keySet(), null);
  Set<Edge> edges = ImmutableSortedSet.of(Edge.of(NODE1, IFACE1, node, iface));
  LastHopOutgoingInterfaceManager mgr =
      new LastHopOutgoingInterfaceManager(_pkt, configs(c), edges);
  assertThat(mgr.getFiniteDomains().entrySet(), hasSize(1));
  BDD lastHopBdd = mgr.getLastHopOutgoingInterfaceBdd(NODE1, IFACE1, node, iface);
  assertFalse(lastHopBdd.isZero());
  assertFalse(lastHopBdd.isOne());

  BDD noLastHopBdd = mgr.getNoLastHopOutgoingInterfaceBdd(node, iface);
  assertFalse(noLastHopBdd.isZero());
  assertFalse(noLastHopBdd.isOne());

  assertThat(lastHopBdd, not(equalTo(noLastHopBdd)));
}
 
Example 6
Source File: PrefixedContainerBasedScope.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("PMD.UseLocaleWithCaseConversions")
@Override
public synchronized IEObjectDescription getSingleElement(final QualifiedName name) {
  final boolean ignoreCase = isIgnoreCase();
  final QualifiedName lookupName = ignoreCase ? name.toLowerCase() : name;
  final IEObjectDescription result = contentByNameCache.get(lookupName);
  if (result != null && result != NULL_DESCRIPTION) {
    return result;
  } else if (result == null) {
    final ContainerQuery copy = ((ContainerQuery.Builder) criteria).copy().name(prefix.append(lookupName)).ignoreCase(ignoreCase);
    final Iterable<IEObjectDescription> res = copy.execute(container);
    IEObjectDescription desc = Iterables.getFirst(res, null);
    if (desc != null) {
      IEObjectDescription aliased = new AliasingEObjectDescription(name, desc);
      contentByNameCache.put(lookupName, aliased);
      return aliased;
    }
    contentByNameCache.put(lookupName, NULL_DESCRIPTION);
  }

  // in case of aliasing revert to normal ContainerBasedScope behavior (using name pattern)
  if (nameFunctions.size() > 1) {
    return super.getSingleElement(name);
  }
  return getParent().getSingleElement(name);
}
 
Example 7
Source File: KeepAliveManagerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void transportGoesIdleBeforePingSent() {

  // Transport becomes active. We should schedule keepalive pings.
  keepAliveManager.onTransportActive();
  assertThat(fakeClock.getPendingTasks()).hasSize(1);
  ScheduledFuture<?> pingFuture = Iterables.getFirst(fakeClock.getPendingTasks(), null);

  // Data is received, and we go to ping delayed
  keepAliveManager.onDataReceived();

  // Transport becomes idle while the 1st ping is still scheduled
  keepAliveManager.onTransportIdle();

  // Transport becomes active again, we don't need to reschedule another ping
  keepAliveManager.onTransportActive();
  assertThat(fakeClock.getPendingTasks()).containsExactly(pingFuture);
}
 
Example 8
Source File: CollectionSearchTests.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void testGetFirst() {
    Collection<String> collection = Lists.newArrayList("a1", "a2", "a3", "a1");
    OrderedIterable<String> orderedIterable = FastList.newListWith("a1", "a2", "a3", "a1");
    Iterable<String> iterable = collection;

    // get first element
    Iterator<String> iterator = collection.iterator(); // using JDK
    String jdk = iterator.hasNext() ? iterator.next(): "1";
    String guava = Iterables.getFirst(iterable, "1"); // using guava
    String apache = CollectionUtils.get(iterable, 0);  // using Apache
    String gs = orderedIterable.getFirst(); // using GS
    String stream = collection.stream().findFirst().orElse("1"); // using Stream API
    System.out.println("first = " + jdk + ":" + guava + ":" + apache + ":" + gs + ":" + stream); // print first = a1:a1:a1:a1:a1
}
 
Example 9
Source File: Property.java    From closure-stylesheets with Apache License 2.0 5 votes vote down vote up
public Property build() {
  if (this.shorthands == null) {
    this.shorthands = computeShorthandPropertiesFor(this.name);
  }
  String partition = Iterables.getFirst(this.shorthands, name);
  return new Property(
      this.name,
      this.shorthands,
      partition,
      this.vendor,
      this.hasPositionalParameters,
      this.isCustom,
      this.isSvgOnly,
      this.warning);
}
 
Example 10
Source File: Bug480686Test.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateTwice() throws Exception {
	ContentAssistFragmentTestLanguageRoot result = parseHelper.parse("");
	XtextResource res = (XtextResource) result.eResource();
	new InvariantChecker().checkInvariant(res.getParseResult().getRootNode());
	res.update(0, 0, "newArrayList()");
	EObject first = Iterables.getFirst(res.getContents(), null);
	Assert.assertTrue(first.eClass().getName(), first instanceof ContentAssistFragmentTestLanguageRoot);
	res.update("newArrayList(".length(), 0, "1");
	EObject second = Iterables.getFirst(res.getContents(), null);
	Assert.assertTrue(second.eClass().getName(), second instanceof ContentAssistFragmentTestLanguageRoot);
}
 
Example 11
Source File: CASFileCacheTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public WindowsCASFileCacheTest() {
  super(
      Iterables.getFirst(
          Jimfs.newFileSystem(
                  Configuration.windows()
                      .toBuilder()
                      .setAttributeViews("basic", "owner", "dos", "acl", "posix", "user")
                      .build())
              .getRootDirectories(),
          null));
}
 
Example 12
Source File: FavoritesStatePreloader.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
protected FetchData getFetchData(@Nonnull BlueUrlTokenizer blueUrl) {
    User jenkinsUser = User.current();
    if (jenkinsUser != null) {
        BlueOrganization organization = Iterables.getFirst(OrganizationFactory.getInstance().list(), null);
        if (organization != null) {
            String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);

            // don't need this list when at pipeline pages
            if (pipelineFullName != null) {
                return null;
            }

            UserImpl blueUser = new UserImpl(organization, jenkinsUser, organization.getUsers());
            BlueFavoriteContainer favoritesContainer = blueUser.getFavorites();

            if (favoritesContainer != null) {
                JSONArray favorites = new JSONArray();
                // Limit the number of favorites to return to a sane amount
                Iterator<BlueFavorite> favoritesIterator = favoritesContainer.iterator(0, DEFAULT_LIMIT);

                while (favoritesIterator.hasNext()) {
                    Reachable favorite = favoritesIterator.next();
                    try {
                        favorites.add(JSONObject.fromObject(Export.toJson(favorite)));
                    } catch (IOException e) {
                        LOGGER.log(Level.FINE, String.format("Unable to preload favorites for User '%s'. Serialization error.", jenkinsUser.getFullName()), e);
                        return null;
                    }
                }

                return new FetchData(favoritesContainer.getLink().getHref() + "?start=0&limit=" + DEFAULT_LIMIT, favorites.toString());
            }
        }
    }

    // Don't preload any data on the page.
    return null;
}
 
Example 13
Source File: MultiAspect.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Factory method for building a multi aspect.
 *
 * @param aspects
 *            Aspects sharing the same type as the "aspectClass" parameter
 * @param aspectClass
 *            Class of the aspects to aggregate
 * @return a MultiAspect or another ITmfEventAspect
 */
public static @Nullable ITmfEventAspect<?> create(Iterable<ITmfEventAspect<?>> aspects, Class<?> aspectClass) {
    int size = Iterables.size(aspects);
    if (size == 0 || size == 1) {
        // Nothing to aggregate if there is no aspects or one unique aspect
        return Iterables.getFirst(aspects, null);
    }

    Set<String> names = new HashSet<>();
    for (ITmfEventAspect<?> aspect : aspects) {
        // Ensure all aspects belong to the same class as the "aspectClass" parameter
        if (aspectClass.isAssignableFrom(aspect.getClass())) {
            names.add(aspect.getName());
        } else {
            throw new IllegalArgumentException("Aspects must belong to the same class as the \"aspectClass\" parameter."); //$NON-NLS-1$
        }
    }

    // Ensure all aspects of the same type share the same name
    if (names.size() != 1) {
        StringJoiner sj = new StringJoiner(", "); //$NON-NLS-1$
        names.forEach(sj::add);
        TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, "Aspects do not have the same name: ", sj.toString()); //$NON-NLS-1$ );
    }

    return new MultiAspect<>(Iterables.get(names, 0), aspects);
}
 
Example 14
Source File: CSVConverter.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Given a column determines the column -> position. If the column contains data in the format
 * {@code columnName:position}, use that. Otherwise, use the provided value of i.
 *
 * @param column The data in the column
 * @param i The default position to use
 * @return A map entry of column value -> position
 */
public static Map.Entry<String, Integer> getColumnMapEntry(String column, int i) {
  if(column.contains(":")) {
    Iterable<String> tokens = Splitter.on(':').split(column);
    String col = Iterables.getFirst(tokens, null);
    Integer pos = Integer.parseInt(Iterables.getLast(tokens));
    return new AbstractMap.SimpleEntry<>(col, pos);
  }
  else {
    return new AbstractMap.SimpleEntry<>(column, i);
  }

}
 
Example 15
Source File: TestFileSystemUtil.java    From kite with Apache License 2.0 4 votes vote down vote up
@Test
public void testIncompatibleFormatFilesInSameFolder() throws Exception {
  File folder = temp.newFolder("a/b/c/d/e");
  Path root = new Path(temp.getRoot().toURI());
  FileSystem fs = LocalFileSystem.getInstance();

  // create Avro and Parquet files under separate folders, with the same schema
  Path parent = new Path(folder.toURI());
  createAvroUserFile(fs, parent);
  createParquetUserFile(fs, parent);

  Collection<DatasetDescriptor> descriptors = FileSystemUtil
      .findPotentialDatasets(fs, root);

  Assert.assertEquals("Should have 2 descriptors", 2, descriptors.size());
  DatasetDescriptor avro;
  DatasetDescriptor parquet;
  DatasetDescriptor first = Iterables.getFirst(descriptors, null);
  if (first.getFormat() == Formats.AVRO) {
    avro = first;
    parquet = Iterables.getLast(descriptors, null);
  } else {
    parquet = first;
    avro = Iterables.getLast(descriptors, null);
  }

  Assert.assertFalse("Should not flag at mixed depth",
      avro.hasProperty("kite.filesystem.mixed-depth"));
  Assert.assertEquals("Should be directly under parent",
      parent.toUri(),
      parent(avro.getLocation()));
  Assert.assertTrue("Should be a .avro file",
      avro.getLocation().toString().endsWith(".avro"));
  Assert.assertEquals("Should use user schema",
      USER_SCHEMA, avro.getSchema());
  Assert.assertEquals("Should have Avro format",
      Formats.AVRO, avro.getFormat());
  Assert.assertFalse("Should not be partitioned",
      avro.isPartitioned());

  Assert.assertFalse("Should not flag at mixed depth",
      parquet.hasProperty("kite.filesystem.mixed-depth"));
  Assert.assertEquals("Should be directly under parent",
      parent.toUri(),
      parent(parquet.getLocation()));
  Assert.assertTrue("Should be a .parquet file",
      parquet.getLocation().toString().endsWith(".parquet"));
  Assert.assertEquals("Should use user schema",
      USER_SCHEMA, parquet.getSchema());
  Assert.assertEquals("Should have Avro format",
      Formats.PARQUET, parquet.getFormat());
  Assert.assertFalse("Should not be partitioned",
      parquet.isPartitioned());
}
 
Example 16
Source File: ConversionProcessor.java    From scalable-ocr with Apache License 2.0 4 votes vote down vote up
private int getPageNumber(String fileName) {
  Iterable<String> it = Splitter.on(".tiff").split(fileName);
  String first = Iterables.getFirst(it, null);
  return Integer.parseInt(Iterables.getLast(Splitter.on("-").split(first)));
}
 
Example 17
Source File: PostgreSQLTypeInstancesNotificationParserTest.java    From binnavi with Apache License 2.0 4 votes vote down vote up
private void testParser(final String table, final String databaseOperation, final String moduleId,
    final String address, final String position, final String expressionId,
    final String typeInstanceId) {

  final StringBuilder builder = new StringBuilder();
  builder.append(table);
  builder.append(' ');
  builder.append(databaseOperation);
  builder.append(' ');
  builder.append(moduleId);
  builder.append(' ');
  if (address != null) {
    builder.append(address);
    builder.append(' ');
  }
  if (position != null) {
    builder.append(position);
    builder.append(' ');
  }
  if (expressionId != null) {
    builder.append(expressionId);
    builder.append(' ');
  }
  builder.append(typeInstanceId);
  final String notification = builder.toString();
  notifications.add(new MockPGNotification("type_instances_changes", notification));

  final PostgreSQLTypeInstancesNotificationParser parser =
      new PostgreSQLTypeInstancesNotificationParser();
  final Collection<TypeInstancesNotificationContainer> result =
      parser.parse(notifications, provider);

  assertNotNull(result);
  assertTrue(!result.isEmpty());
  assertTrue(result.size() == 1);

  final TypeInstancesNotificationContainer container = Iterables.getFirst(result, null);
  assertNotNull(container);
  assertEquals(databaseOperation, container.getDatabaseOperation());

}
 
Example 18
Source File: CallGraphDensityViewer.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected @Nullable ISegmentStoreProvider getSegmentStoreProvider(@NonNull ITmfTrace trace) {
    Iterable<CallStackAnalysis> csModules = TmfTraceUtils.getAnalysisModulesOfClass(trace, CallStackAnalysis.class);
    return Iterables.getFirst(csModules, null);
}
 
Example 19
Source File: CommandRegistryTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> unregisterCapability(UnregistrationParams params) {
	Unregistration unreg = Iterables.getFirst(params.getUnregisterations(), null);
	registered.remove(unreg.getId());
	return CompletableFuture.completedFuture(null);
}
 
Example 20
Source File: QueryResult.java    From async-datastore-client with Apache License 2.0 2 votes vote down vote up
/**
 * Return the first entity returned from the query or null if not found.
 *
 * This is a shortcut for {@code getAll().get(0)}
 *
 * @return an entity returned from the Datastore.
 */
public Entity getEntity() {
  return Iterables.getFirst(entities, null);
}