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

The following examples show how to use com.google.common.collect.Iterables#transform() . 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: SonarRunnerPlugin.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 File: TaskFactory.java    From incubator-myriad with 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 File: PostalAddressRepository.java    From estatio with 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 4
Source File: DimensionsSpec.java    From druid-api with 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 File: TestingCluster.java    From xian with 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 6
Source File: FilterWithErrorMarkerScope.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 7
Source File: MySqlDialect.java    From morf with 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 8
Source File: GamlExpressionCompiler.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@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 9
Source File: SCTUnitTestModels.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
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 10
Source File: SourceUnitGenerator.java    From yql-plus with 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
Source File: DelegatingScope.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 12
Source File: MultiLocationRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: Intersection.java    From datawave with 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 14
Source File: TargetParsingCompleteEvent.java    From bazel with Apache License 2.0 4 votes vote down vote up
public Iterable<Label> getFilteredLabels() {
  return Iterables.transform(filteredTargets, ThinTarget::getLabel);
}
 
Example 15
Source File: SubstationAdapter.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Iterable<TwoWindingsTransformer> getTwoWindingsTransformers() {
    return Iterables.transform(getDelegate().getTwoWindingsTransformers(),
                               getIndex()::getTwoWindingsTransformer);
}
 
Example 16
Source File: StochasticBankIT.java    From fluo with 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 17
Source File: Interspersing.java    From bazel with 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 18
Source File: LinkerInputs.java    From bazel with 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 19
Source File: BusAdapter.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Iterable<Load> getLoads() {
    return Iterables.transform(getDelegate().getLoads(),
                               getIndex()::getLoad);
}
 
Example 20
Source File: ResourceCounter.java    From attic-aurora with 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);
}