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

The following examples show how to use com.google.common.collect.Iterables#transform() . These examples are extracted from open source projects. 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
private String convertValue(Object value) {
    if (value == null) {
        return null;
    }
    if (value instanceof Iterable<?>) {
        Iterable<String> flattened = Iterables.transform((Iterable<?>) value, new Function<Object, String>() {
            public String apply(Object input) {
                return convertValue(input);
            }
        });

        Iterable<String> filtered = Iterables.filter(flattened, Predicates.notNull());
        String joined = COMMA_JOINER.join(filtered);
        return joined.isEmpty() ? null : joined;
    } else {
        return value.toString();
    }
}
 
Example 2
Source Project: incubator-myriad   File: TaskFactory.java    License: Apache License 2.0 6 votes vote down vote up
protected Iterable<Protos.Volume> getVolumes(Iterable<Map<String, String>> volume) {
  return Iterables.transform(volume, new Function<Map<String, String>, Protos.Volume>() {
    @Nullable
    @Override
    public Protos.Volume apply(Map<String, String> map) {
      Preconditions.checkArgument(map.containsKey(HOST_PATH_KEY) && map.containsKey(CONTAINER_PATH_KEY));
      Protos.Volume.Mode mode = Protos.Volume.Mode.RO;
      if (map.containsKey(RW_MODE) && map.get(RW_MODE).toLowerCase().equals("rw")) {
        mode = Protos.Volume.Mode.RW;
      }
      return Protos.Volume.newBuilder()
          .setContainerPath(map.get(CONTAINER_PATH_KEY))
          .setHostPath(map.get(HOST_PATH_KEY))
          .setMode(mode)
          .build();
    }
  });
}
 
Example 3
Source Project: xian   File: TestingCluster.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the set of servers in the ensemble
 *
 * @return set of servers
 */
public Collection<InstanceSpec> getInstances()
{
    Iterable<InstanceSpec> transformed = Iterables.transform
    (
        servers,
        new Function<TestingZooKeeperServer, InstanceSpec>()
        {
            @Override
            public InstanceSpec apply(TestingZooKeeperServer server)
            {
                return server.getInstanceSpec();
            }
        }
    );
    return Lists.newArrayList(transformed);
}
 
Example 4
Source Project: druid-api   File: DimensionsSpec.java    License: Apache License 2.0 6 votes vote down vote up
@Deprecated @JsonIgnore
public List<SpatialDimensionSchema> getSpatialDimensions()
{
  Iterable<NewSpatialDimensionSchema> filteredList = Iterables.filter(
      dimensions, NewSpatialDimensionSchema.class
  );

  Iterable<SpatialDimensionSchema> transformedList = Iterables.transform(
      filteredList,
      new Function<NewSpatialDimensionSchema, SpatialDimensionSchema>()
      {
        @Nullable
        @Override
        public SpatialDimensionSchema apply(NewSpatialDimensionSchema input)
        {
          return new SpatialDimensionSchema(input.getName(), input.getDims());
        }
      }
  );

  return Lists.newArrayList(transformedList);
}
 
Example 5
Source Project: estatio   File: PostalAddressRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Programmatic
public PostalAddress findByAddress(
        final CommunicationChannelOwner owner,
        final String address1,
        final String address2,
        final String address3,
        final String postalCode,
        final String city,
        final Country country) {

    final List<CommunicationChannelOwnerLink> links =
            communicationChannelOwnerLinkRepository.findByOwnerAndCommunicationChannelType(owner, CommunicationChannelType.POSTAL_ADDRESS);
    final Iterable<PostalAddress> postalAddresses =
            Iterables.transform(
                    links,
                    CommunicationChannelOwnerLink.Functions.communicationChannel(PostalAddress.class));
    final Optional<PostalAddress> postalAddressIfFound =
            Iterables.tryFind(postalAddresses, PostalAddress.Predicates.equalTo(address1, address2, address3, postalCode, city, country));
    return postalAddressIfFound.orNull();
}
 
Example 6
public static Iterable<Object[]> parameterizedTestData() throws Exception {
	SCTUnitTestModels models = new SCTUnitTestModels();
	List<Statechart> all = models.loadAllStatecharts();
	return Iterables.transform(all, new Function<Statechart, Object[]>() {
		@Override
		public Object[] apply(Statechart input) {
			return new Object[]{input};
		}
	});
}
 
Example 7
Source Project: datawave   File: Intersection.java    License: Apache License 2.0 5 votes vote down vote up
static Iterable<IndexInfo> convert(Iterable<? extends PeekingIterator<Tuple2<String,IndexInfo>>> i) {
    final Function<PeekingIterator<Tuple2<String,IndexInfo>>,IndexInfo> f = itr -> {
        if (log.isTraceEnabled())
            log.trace("ah" + itr.peek().first() + " " + itr.peek().second());
        return itr.peek().second();
    };
    return Iterables.transform(i, f);
}
 
Example 8
@SuppressWarnings("unchecked")
@Test
public void testRebindsMultiLocation() throws Exception {
    mac1a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
            .displayName("mac1a")
            .configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
    mac2a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
            .displayName("mac2a")
            .configure("address", Networking.getInetAddressWithFixedName("1.1.1.3")));
    loc1 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
            .displayName("loc1")
            .configure("machines", MutableSet.of(mac1a)));
    loc2 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
            .displayName("loc2")
            .configure("machines", MutableSet.of(mac2a)));
    multiLoc = origManagementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
                    .displayName("multiLoc")
                    .configure("subLocations", ImmutableList.of(loc1, loc2)));
    
    newApp = rebind();
    newManagementContext = newApp.getManagementContext();
    
    MultiLocation<?> newMultiLoc = (MultiLocation<?>) Iterables.find(newManagementContext.getLocationManager().getLocations(), Predicates.instanceOf(MultiLocation.class));
    AvailabilityZoneExtension azExtension = newMultiLoc.getExtension(AvailabilityZoneExtension.class);
    List<Location> newSublLocs = azExtension.getAllSubLocations();
    Iterable<String> newSubLocNames = Iterables.transform(newSublLocs, new Function<Location, String>() {
        @Override public String apply(Location input) {
            return (input == null) ? null : input.getDisplayName();
        }});
    Asserts.assertEqualsIgnoringOrder(newSubLocNames, ImmutableList.of("loc1", "loc2"));
}
 
Example 9
/**
 * Evaluate the delegate scopes.
 *
 * @return The delegate scopes.
 */
protected Iterable<IScope> getDelegates() {
  if (delegates == null) {
    delegates = Iterables.transform(contexts.get(), o -> {
      try {
        return eReference != null ? scopeProvider.getScope(o, eReference, scopeName, originalResource)
            : scopeProvider.getScope(o, eClass, scopeName, originalResource);
      } catch (StackOverflowError e) {
        stackOverflowScopeId = DelegatingScope.this.getId();
        return STACK_OVERFLOW_SCOPE;
      }
    });
  }
  return delegates;
}
 
Example 10
Source Project: yql-plus   File: SourceUnitGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void complete(ObjectBuilder.MethodBuilder adapterMethod, ScopedBuilder body) {
    // we need to surface optional/required arguments and a suitable struct type to populate the planner
    // so let's make a YQL schema for our argument map
    this.insertType = argumentMap.build();
    // derive a struct type from it
    // that is the type our adapter method takes as an argument
    // it then needs to explode that into the arguments to the method
    TypeWidget insertRecord = AnyTypeWidget.getInstance();
    BytecodeExpression record = adapterMethod.addArgument("$record", insertRecord);
    // scatter the record in key into all the key values
    // TODO: check data types before blind coercion attempts!
    for (Map.Entry<String, AssignableValue> keyEntry : dataValues.entrySet()) {
        String propertyName = keyEntry.getKey();
        BytecodeExpression defaultValue = defaultValues.get(propertyName);
        AssignableValue setValue = keyEntry.getValue();
        if(defaultValue == null) {
            defaultValue = new MissingRequiredFieldExpr(clazz.getName(), this.method.getName(), propertyName, setValue.getType());
        }
        body.set(Location.NONE, setValue, body.cast(setValue.getType(), body.coalesce(Location.NONE, body.propertyValue(Location.NONE, record, propertyName), defaultValue)));
    }
    // verify we didn't get any unrecognized fields
    if(insertType.isClosed()) {
        PropertyAdapter adapter = insertRecord.getPropertyAdapter();
        TreeSet<String> fieldNames = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
        for(String name : Iterables.transform(insertType.getFields(), new Function<YQLNamePair, String>() {
                    @Nullable
                    @Override
                    public String apply(YQLNamePair input) {
                        return input.getName();
                    }
                })) {
            fieldNames.add(name);
        }
        body.exec(adapter.mergeIntoFieldWriter(record, body.constant(body.adapt(FieldWriter.class, false), new VerifyNoExtraFieldsFieldWriter(fieldNames, clazz.getName(), this.method.getName()))));
    }

}
 
Example 11
/**
 * Decorates all descriptions which are filtered with error markers. Since
 * {@link #wrapFilteredDescription(IEObjectDescription)} may return null, null values are filtered out.
 *
 * @param originalDescriptions
 *            the original unfiltered descriptions.
 */
protected Iterable<IEObjectDescription> doDecorateWithErrorIfFiltered(
		Iterable<IEObjectDescription> originalDescriptions, Predicate<IEObjectDescription> predicate) {
	Iterable<IEObjectDescription> filteredResult = Iterables.transform(originalDescriptions,
			it -> {
				if (it == null || predicate.test(it)) {
					return it;
				} else {
					return wrapFilteredDescription(it);
				}
			});
	return Iterables.filter(filteredResult, it -> it != null);
}
 
Example 12
@Override
public IExpression caseArray(final Array object) {
	final List<? extends Expression> list = EGaml.getInstance().getExprsOf(object.getExprs());
	// Awkward expression, but necessary to fix Issue #2612
	final boolean allPairs = !list.isEmpty() && Iterables.all(list,
			each -> each instanceof ArgumentPair || "::".equals(EGaml.getInstance().getKeyOf(each)));
	final Iterable<IExpression> result = Iterables.transform(list, input -> compile(input));
	return allPairs ? getFactory().createMap(result) : getFactory().createList(result);
}
 
Example 13
Source Project: morf   File: MySqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#getSqlFrom(org.alfasoftware.morf.sql.MergeStatement)
 */
@Override
protected String getSqlFrom(final MergeStatement statement) {

  if (StringUtils.isBlank(statement.getTable().getName())) {
    throw new IllegalArgumentException("Cannot create SQL for a blank table");
  }

  checkSelectStatementHasNoHints(statement.getSelectStatement(), "MERGE may not be used with SELECT statement hints");

  final boolean hasNonKeyFields = getNonKeyFieldsFromMergeStatement(statement).iterator().hasNext();

  final String destinationTableName = statement.getTable().getName();

  // Add the preamble
  StringBuilder sqlBuilder = new StringBuilder("INSERT ");
  if (!hasNonKeyFields) {
    sqlBuilder.append("IGNORE ");
  }
  sqlBuilder.append("INTO ");
  sqlBuilder.append(schemaNamePrefix(statement.getTable()));
  sqlBuilder.append(destinationTableName);
  sqlBuilder.append("(");
  Iterable<String> intoFields = Iterables.transform(statement.getSelectStatement().getFields(), AliasedField::getImpliedName);
  sqlBuilder.append(Joiner.on(", ").join(intoFields));
  sqlBuilder.append(") ");

  // Add select statement
  sqlBuilder.append(getSqlFrom(statement.getSelectStatement()));

  // Add the update expressions
  if (hasNonKeyFields) {
    sqlBuilder.append(" ON DUPLICATE KEY UPDATE ");
    Iterable<AliasedField> updateExpressions = getMergeStatementUpdateExpressions(statement);
    String updateExpressionsSql = getMergeStatementAssignmentsSql(updateExpressions);
    sqlBuilder.append(updateExpressionsSql);
  }
  return sqlBuilder.toString();
}
 
Example 14
Source Project: powsybl-core   File: BusAdapter.java    License: Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Iterable<Load> getLoads() {
    return Iterables.transform(getDelegate().getLoads(),
                               getIndex()::getLoad);
}
 
Example 15
Source Project: bazel   File: Interspersing.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Prepends {@code what} to each string in {@code sequence}, returning a lazy sequence of the 
 * same length.
 */
public static Iterable<String>
    prependEach(final String what, Iterable<String> sequence) {
  Preconditions.checkNotNull(what);
  return Iterables.transform(sequence, input -> what + input);
}
 
Example 16
public Iterable<Label> getFilteredLabels() {
  return Iterables.transform(filteredTargets, ThinTarget::getLabel);
}
 
Example 17
@Override
public Iterable<TwoWindingsTransformer> getTwoWindingsTransformers() {
    return Iterables.transform(getDelegate().getTwoWindingsTransformers(),
                               getIndex()::getTwoWindingsTransformer);
}
 
Example 18
Source Project: fluo   File: StochasticBankIT.java    License: Apache License 2.0 4 votes vote down vote up
private static void printDiffs(Environment env, TestTransaction lastTx, TestTransaction tx)
    throws Exception {
  Map<String, String> bals1 = toMap(lastTx);
  Map<String, String> bals2 = toMap(tx);

  if (!bals1.keySet().equals(bals2.keySet())) {
    log.debug("KS NOT EQ");
  }

  int sum1 = 0;
  int sum2 = 0;

  for (Entry<String, String> entry : bals1.entrySet()) {
    String val2 = bals2.get(entry.getKey());

    if (!entry.getValue().equals(val2)) {
      int v1 = Integer.parseInt(entry.getValue());
      int v2 = Integer.parseInt(val2);
      sum1 += v1;
      sum2 += v2;

      log.debug(entry.getKey() + " " + entry.getValue() + " " + val2 + " " + (v2 - v1));
    }
  }

  log.debug("start times : " + lastTx.getStartTs() + " " + tx.getStartTs());
  log.debug("sum1 : %,d  sum2 : %,d  diff : %,d\n", sum1, sum2, sum2 - sum1);

  File tmpFile = File.createTempFile("sb_dump", ".txt");
  Writer fw = new BufferedWriter(new FileWriter(tmpFile));

  Scanner scanner =
      env.getAccumuloClient().createScanner(env.getTable(), env.getAuthorizations());

  for (String cell : Iterables.transform(scanner, FluoFormatter::toString)) {
    fw.append(cell);
    fw.append("\n");
  }

  fw.close();

  log.debug("Dumped table : " + tmpFile);
}
 
Example 19
Source Project: bazel   File: LinkerInputs.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates input libraries for which we do not know what objects files it consists of.
 */
public static Iterable<LibraryToLink> opaqueLibrariesToLink(
    final ArtifactCategory category, Iterable<Artifact> input) {
  return Iterables.transform(input, artifact -> precompiledLibraryToLink(artifact, category));
}
 
Example 20
Source Project: attic-aurora   File: ResourceCounter.java    License: Apache License 2.0 4 votes vote down vote up
private Iterable<ITaskConfig> getTasks(Query.Builder query) throws StorageException {
  return Iterables.transform(
      Storage.Util.fetchTasks(storage, query),
      Tasks::getConfig);
}