Java Code Examples for com.google.common.base.Function

The following are top voted examples for showing how to use com.google.common.base.Function. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dremio-oss   File: ElasticMappingSet.java   Source Code and License 6 votes vote down vote up
public ElasticIndex filterToType(String name){
  List<ElasticMapping> filtered = new ArrayList<>();
  for(ElasticMapping m : mappings){
    for(String namePiece : name.split(",")){
      if(m.getName().equals(namePiece)){
        filtered.add(m);
      }
    }
  }
  if(filtered.isEmpty()){
    return null;
  }
  return new ElasticIndex(name, ImmutableList.<String>of(), FluentIterable.from(filtered).uniqueIndex(new Function<ElasticMapping, String>(){

    @Override
    public String apply(ElasticMapping input) {
      return input.getName();
    }}));
}
 
Example 2
Project: guava-mock   File: FuturesTest.java   Source Code and License 6 votes vote down vote up
@GwtIncompatible // makeChecked

  public void testMakeChecked_listenersRunOnCancel() throws Exception {
    SettableFuture<String> future = SettableFuture.create();

    CheckedFuture<String, TestException> checked = makeChecked(
        future, new Function<Exception, TestException>() {
          @Override
          public TestException apply(Exception from) {
            throw new NullPointerException();
          }
        });

    ListenableFutureTester tester = new ListenableFutureTester(checked);
    tester.setUp();
    future.cancel(true); // argument is ignored
    tester.testCancelledFuture();
    tester.tearDown();
  }
 
Example 3
Project: n4js   File: TestTreeRegistryTest.java   Source Code and License 6 votes vote down vote up
private TestTree newTestTree(final String sessionId, final String... testIds) {
	final List<TestSuite> testSuites = newArrayList(transform(newHashSet(testIds),
			new Function<String, TestSuite>() {
				@Override
				public TestSuite apply(String testId) {
					final TestSuite suite = new TestSuite("TestSuite_for_Test_" + testId);
					final TestCase testCase = new TestCase(
							new ID(testId),
							"testClassName_" + testId,
							"origin_" + testId + "name_" + testId + "_0.0.0",
							"name_" + testId,
							"displayName_" + testId,
							URI.createURI("testURI_" + testId));
					suite.setTestCases(singletonList(testCase));
					return suite;
				}
			}));
	return new TestTree(new ID(sessionId), testSuites);
}
 
Example 4
Project: Reer   File: ModelPathSuggestionProvider.java   Source Code and License 6 votes vote down vote up
@Override
public List<ModelPath> transform(final ModelPath unavailable) {
    Iterable<Suggestion> suggestions = Iterables.transform(availablePaths, new Function<ModelPath, Suggestion>() {
        public Suggestion apply(ModelPath available) {
            int distance = StringUtils.getLevenshteinDistance(unavailable.toString(), available.toString());
            boolean suggest = distance <= Math.min(3, unavailable.toString().length() / 2);
            if (suggest) {
                return new Suggestion(distance, available);
            } else {
                // avoid excess creation of Suggestion objects
                return null;
            }
        }
    });

    suggestions = Iterables.filter(suggestions, REMOVE_NULLS);
    List<Suggestion> sortedSuggestions = CollectionUtils.sort(suggestions);
    return CollectionUtils.collect(sortedSuggestions, Suggestion.EXTRACT_PATH);
}
 
Example 5
Project: Equella   File: DrmScriptWrapper.java   Source Code and License 6 votes vote down vote up
@Override
public void setContentOwners(List<DrmPartyScriptType> contentOwners)
{
	changed = true;
	owners = contentOwners;

	List<Party> partyContentOwners = Lists
		.newArrayList(Lists.transform(contentOwners, new Function<DrmPartyScriptType, Party>()
		{
			@Override
			public Party apply(DrmPartyScriptType drmPartyScriptType)
			{
				DefaultDrmPartyScriptType scriptParty = ((DefaultDrmPartyScriptType) drmPartyScriptType);
				scriptParty.setOwnerSettings(DefaultDrmSettingsScriptType.this);
				return scriptParty.getWrapped();
			}
		}));
	settings.setContentOwners(partyContentOwners);
}
 
Example 6
Project: burp-vulners-scanner   File: PathIssue.java   Source Code and License 6 votes vote down vote up
@Override
public String getSeverity() {
    Collection<Double> scores = Collections2.transform(
            vulnerabilities, new Function<Vulnerability, Double>() {
                @Override
                public Double apply(Vulnerability vulnerability) {
                    return vulnerability.getCvssScore();
                }
            }
    );
    Double maxValue = Ordering.natural().max(scores);

    if (maxValue > 7) {
        return ScanIssueSeverity.HIGH.getName();
    } else if (maxValue > 4) {
        return ScanIssueSeverity.MEDIUM.getName();
    }
    return ScanIssueSeverity.LOW.getName();
}
 
Example 7
Project: pact-spring-mvc   File: DefaultPactResolver.java   Source Code and License 6 votes vote down vote up
@Override
public List<Pact> resolvePacts(final PactDefinition pactDefinition, final ObjectStringConverter jsonConverter) throws Exception {

    if (!StringUtils.isEmpty(pactDefinition.localPactFilePath())) {
        String pactJson = loadPactFile(pactDefinition.localPactFilePath());
        Pact pact = Pact.parse(pactJson, jsonConverter);

        pact.setDisplayVersion("local");
        pact.setDisplayName(pactDefinition.consumer() + "-local");

        return singletonList(pact);
    }

    return transform(getPactVersionsToRun(pactDefinition), new Function<String, Pact>() {
        @Override
        public Pact apply(String version) {
            return resolvePact(pactDefinition, version, jsonConverter);
        }
    });
}
 
Example 8
Project: hashsdn-controller   File: TransactionProxy.java   Source Code and License 6 votes vote down vote up
private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readAllData() {
    final Set<String> allShardNames = txContextFactory.getActorContext().getConfiguration().getAllShardNames();
    final Collection<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>> futures =
            new ArrayList<>(allShardNames.size());

    for (String shardName : allShardNames) {
        futures.add(singleShardRead(shardName, YangInstanceIdentifier.EMPTY));
    }

    final ListenableFuture<List<Optional<NormalizedNode<?, ?>>>> listFuture = Futures.allAsList(futures);
    final ListenableFuture<Optional<NormalizedNode<?, ?>>> aggregateFuture;

    aggregateFuture = Futures.transform(listFuture,
        (Function<List<Optional<NormalizedNode<?, ?>>>, Optional<NormalizedNode<?, ?>>>) input -> {
            try {
                return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.EMPTY, input,
                        txContextFactory.getActorContext().getSchemaContext(),
                        txContextFactory.getActorContext().getDatastoreContext().getLogicalStoreType());
            } catch (DataValidationFailedException e) {
                throw new IllegalArgumentException("Failed to aggregate", e);
            }
        }, MoreExecutors.directExecutor());

    return MappingCheckedFuture.create(aggregateFuture, ReadFailedException.MAPPER);
}
 
Example 9
Project: iotplatform   File: CassandraBaseTimeseriesDao.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<TsKvEntry>> findAllAsync(EntityId entityId, List<TsKvQuery> queries) {
    List<ListenableFuture<List<TsKvEntry>>> futures = queries.stream().map(query -> findAllAsync(entityId, query)).collect(Collectors.toList());
    return Futures.transform(Futures.allAsList(futures), new Function<List<List<TsKvEntry>>, List<TsKvEntry>>() {
        @Nullable
        @Override
        public List<TsKvEntry> apply(@Nullable List<List<TsKvEntry>> results) {
            if (results == null || results.isEmpty()) {
                return null;
            }
            return results.stream()
                    .flatMap(List::stream)
                    .collect(Collectors.toList());
        }
    }, readResultsProcessingExecutor);
}
 
Example 10
Project: athena   File: DefaultOvsdbClient.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<OperationResult>> transactConfig(String dbName,
                                                              List<Operation> operations) {
    if (dbName == null) {
        return null;
    }
    DatabaseSchema dbSchema = schema.get(dbName);
    if (dbSchema != null) {
        Function<List<JsonNode>, List<OperationResult>> rowFunction = (input -> {
            log.info("Get ovsdb operation result");
            List<OperationResult> result = FromJsonUtil
                    .jsonNodeToOperationResult(input, operations);

            if (result == null) {
                log.debug("The operation result is null");
                return null;
            }
            return result;
        });
        return Futures.transform(transact(dbSchema, operations),
                                 rowFunction);
    }
    return null;
}
 
Example 11
Project: Reer   File: DefaultTaskOutputs.java   Source Code and License 6 votes vote down vote up
@Override
public SortedSet<TaskOutputFilePropertySpec> getFileProperties() {
    if (fileProperties == null) {
        TaskPropertyUtils.ensurePropertiesHaveNames(filePropertiesInternal);
        Iterator<TaskOutputFilePropertySpec> flattenedProperties = Iterators.concat(Iterables.transform(filePropertiesInternal, new Function<TaskPropertySpec, Iterator<? extends TaskOutputFilePropertySpec>>() {
            @Override
            public Iterator<? extends TaskOutputFilePropertySpec> apply(TaskPropertySpec propertySpec) {
                if (propertySpec instanceof CompositeTaskOutputPropertySpec) {
                    return ((CompositeTaskOutputPropertySpec) propertySpec).resolveToOutputProperties();
                } else {
                    return Iterators.singletonIterator((TaskOutputFilePropertySpec) propertySpec);
                }
            }
        }).iterator());
        fileProperties = TaskPropertyUtils.collectFileProperties("output", flattenedProperties);
    }
    return fileProperties;
}
 
Example 12
Project: vscrawler   File: FetchTaskProcessor.java   Source Code and License 6 votes vote down vote up
private Object unPackSipNode(Object object) {
    if (object == null) {
        return null;
    }
    if (object instanceof SIPNode) {
        return handleSingleSipNode((SIPNode) object);
    }
    if (object instanceof Collection) {
        return Collections2.transform((Collection) object, new Function<Object, Object>() {
            @Override
            public Object apply(Object input) {
                if (!(input instanceof SIPNode)) {
                    return input;
                }
                return handleSingleSipNode((SIPNode) input);
            }
        });
    }
    return object;
}
 
Example 13
Project: googles-monorepo-demo   File: FuturesTest.java   Source Code and License 6 votes vote down vote up
@GwtIncompatible // makeChecked

  public void testMakeChecked_listenersRunOnceCompleted() throws Exception {
    SettableFuture<String> future = SettableFuture.create();

    CheckedFuture<String, TestException> checked = makeChecked(
        future, new Function<Exception, TestException>() {
          @Override
          public TestException apply(Exception from) {
            throw new NullPointerException();
          }
        });

    ListenableFutureTester tester = new ListenableFutureTester(checked);
    tester.setUp();
    future.set(DATA1);
    tester.testCompletedFuture(DATA1);
    tester.tearDown();
  }
 
Example 14
Project: googles-monorepo-demo   File: AbstractNetwork.java   Source Code and License 6 votes vote down vote up
private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) {
  Function<E, EndpointPair<N>> edgeToIncidentNodesFn =
      new Function<E, EndpointPair<N>>() {
        @Override
        public EndpointPair<N> apply(E edge) {
          return network.incidentNodes(edge);
        }
      };
  return Maps.asMap(network.edges(), edgeToIncidentNodesFn);
}
 
Example 15
Project: randomito-all   File: AnnotationPostProcessorScanner.java   Source Code and License 6 votes vote down vote up
public PostProcessor[] scan(final Object instance) {
    return FluentIterable
            .from(ReflectionUtils.getDeclaredFields(instance.getClass(), true))
            .filter(new Predicate<Field>() {
                @Override
                public boolean apply(Field input) {
                    return input.isAnnotationPresent(Random.PostProcessor.class)
                            && PostProcessor.class.isAssignableFrom(input.getType());
                }
            })
            .transform(new Function<Field, PostProcessor>() {
                @Override
                public PostProcessor apply(Field field) {
                    try {
                        if (!ReflectionUtils.makeFieldAccessible(field)) {
                            return null;
                        }
                        return (PostProcessor) field.get(instance);
                    } catch (IllegalAccessException e) {
                        throw new RandomitoException(e);
                    }
                }
            })
            .filter(Predicates.<PostProcessor>notNull())
            .toArray(PostProcessor.class);
}
 
Example 16
Project: rx-twitter-stream-android   File: StreamActivityTest.java   Source Code and License 6 votes vote down vote up
@Override
public ApplicationModule getApplicationModule() {

    RxTwitterApplication application = (RxTwitterApplication) context.getApplicationContext();

    return new TestModule(application) {

        @Override
        protected ActivityModule getActivityModule(BaseActivity baseActivity, BackPressureStrategy backPressureStrategy) {

            return new ActivityModule(baseActivity, backPressureStrategy) {
                @Override
                public TwitterStreamPresenter provideTwitterStreamPresenter(TweetsRepository repository,
                                                                            TwitterAvatarRepository avatarRepository,
                                                                            ExecutionScheduler uiScheduler,
                                                                            ExecutionScheduler tweetScheduler,
                                                                            ExecutionScheduler imageScheduler,
                                                                            Function<Flowable<Tweet>, Flowable<Tweet>> backPressureStrategyFunction) {
                    return mockTwitterStreamPresenter;
                }
            };
        }
    };
}
 
Example 17
Project: guava-mock   File: AbstractCatchingFuture.java   Source Code and License 5 votes vote down vote up
static <V, X extends Throwable> ListenableFuture<V> create(
    ListenableFuture<? extends V> input,
    Class<X> exceptionType,
    Function<? super X, ? extends V> fallback,
    Executor executor) {
  CatchingFuture<V, X> future = new CatchingFuture<V, X>(input, exceptionType, fallback);
  input.addListener(future, rejectionPropagatingExecutor(executor, future));
  return future;
}
 
Example 18
Project: Equella   File: EmailSelectorWebControl.java   Source Code and License 5 votes vote down vote up
@Override
public void doEdits(SectionInfo info)
{
	final EmailSelectorWebControlModel model = getModel(info);
	if( model.getSelectedUsers() != null )
	{
		final Collection<String> selectedUuids = Collections2.transform(model.getSelectedUsers(),
			new Function<SelectedUser, String>()
			{
				@Override
				public String apply(SelectedUser user)
				{
					return user.getUuid();
				}
			});

		final List<String> controlValues = storageControl.getValues();
		for( UserBean ub : userService.getInformationForUsers(selectedUuids).values() )
		{
			String emailAddress = ub.getEmailAddress();
			if( Check.isEmpty(emailAddress) )
			{
				model.setWarning("warning.noemails");
			}
			else if( !controlValues.contains(emailAddress) )
			{
				controlValues.add(emailAddress);
			}
		}
	}
}
 
Example 19
Project: Equella   File: AbstractPopupBrowserDialog.java   Source Code and License 5 votes vote down vote up
@Override
public List<HtmlTreeNode> getChildNodes(SectionInfo info, String id)
{
	return Lists.transform(taxonomyService.getChildTerms(taxonomyUuid, id),
		new Function<TermResult, HtmlTreeNode>()
		{
			@Override
			public HtmlTreeNode apply(TermResult tr)
			{
				return new TermSelectorTreeNode(tr);
			}
		});
}
 
Example 20
Project: guava-mock   File: ForwardingWrapperTesterTest.java   Source Code and License 5 votes vote down vote up
public void testFailsToForwardToString() {
  assertFailure(Runnable.class, new Function<Runnable, Runnable>() {
    @Override public Runnable apply(final Runnable runnable) {
      return new ForwardingRunnable(runnable) {
        @Override public String toString() {
          return "";
        }
      };
    }
  }, "toString()");
}
 
Example 21
Project: dremio-oss   File: FlattenRelBase.java   Source Code and License 5 votes vote down vote up
public Set<Integer> getFlattenedIndices(){
  return FluentIterable.from(getToFlatten()).transform(new Function<RexInputRef, Integer>(){
    @Override
    public Integer apply(RexInputRef input) {
      return input.getIndex();
    }}).toSet();
}
 
Example 22
Project: Proyecto2017Seguros   File: ClientesPorCumpleaños.java   Source Code and License 5 votes vote down vote up
private Function<Cliente, ClientesCumpleañosViewModel> ordenar() {
	return new Function<Cliente, ClientesCumpleañosViewModel>() {

		@Override
		public ClientesCumpleañosViewModel apply(final Cliente client) {

			return new ClientesCumpleañosViewModel(client);
		}
	};
}
 
Example 23
Project: Adventurers-Toolbox   File: PickaxeModel.java   Source Code and License 5 votes vote down vote up
@Override
@Nonnull
public IBakedModel handleItemState(@Nonnull IBakedModel originalModel, @Nonnull ItemStack stack,
		@Nullable World world, @Nullable EntityLivingBase entity) {

	if (stack.getItem() != ModItems.pickaxe) {
		return originalModel;
	}

	BakedPickaxeModel model = (BakedPickaxeModel) originalModel;

	String key = IHeadTool.getHeadMat(stack).getName() + "|"
			+ IHaftTool.getHaftMat(stack).getName() + "|"
			+ IHandleTool.getHandleMat(stack).getName() + "|"
			+ IAdornedTool.getAdornmentMat(stack).getName();

	if (!model.cache.containsKey(key)) {
		ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
		builder.put("head", IHeadTool.getHeadMat(stack).getName());
		builder.put("haft", IHaftTool.getHaftMat(stack).getName());
		builder.put("handle", IHandleTool.getHandleMat(stack).getName());
		if (IAdornedTool.getAdornmentMat(stack) != ModMaterials.ADORNMENT_NULL) {
			builder.put("adornment", IAdornedTool.getAdornmentMat(stack).getName());
		}
		IModel parent = model.parent.retexture(builder.build());
		Function<ResourceLocation, TextureAtlasSprite> textureGetter;
		textureGetter = new Function<ResourceLocation, TextureAtlasSprite>() {
			public TextureAtlasSprite apply(ResourceLocation location) {
				return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString());
			}
		};
		IBakedModel bakedModel = parent.bake(new SimpleModelState(model.transforms), model.format,
				textureGetter);
		model.cache.put(key, bakedModel);
		return bakedModel;
	}

	return model.cache.get(key);
}
 
Example 24
Project: dremio-oss   File: FixHiveMetadata.java   Source Code and License 5 votes vote down vote up
@Override
public void upgrade(UpgradeContext context) {
  final NamespaceService namespaceService = new NamespaceServiceImpl(context.getKVStoreProvider().get());
  try {
    for (SourceConfig source : namespaceService.getSources()) {
      if (source.getType() == SourceType.HIVE) {
        for (NamespaceKey datasetPath : namespaceService.getAllDatasets(new NamespaceKey(source.getName()))) {
          final DatasetConfig datasetConfig = namespaceService.getDataset(datasetPath);

          // drop the metadata and splits
          if (datasetConfig.getReadDefinition() != null) {
            Iterable<DatasetSplitId> splitIdList = Iterables.transform(
              namespaceService.findSplits(DatasetSplitId.getAllSplitsRange(datasetConfig)),
              new Function<Entry<DatasetSplitId, DatasetSplit>, DatasetSplitId>() {
                @Override
                public DatasetSplitId apply(Entry<DatasetSplitId, DatasetSplit> input) {
                  return input.getKey();
                }
              });
            namespaceService.deleteSplits(splitIdList);
          }

          datasetConfig.setReadDefinition(null);
          namespaceService.addOrUpdateDataset(datasetPath, datasetConfig);
        }
      }
    }
  } catch (NamespaceException e) {
    throw new RuntimeException("FixHiveMetadata failed", e);
  }
}
 
Example 25
Project: CustomWorldGen   File: ModelLoader.java   Source Code and License 5 votes vote down vote up
@Override
public IBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter)
{
    MultipartBakedModel.Builder builder = new MultipartBakedModel.Builder();

    for (Selector selector : multipart.getSelectors())
    {
        builder.putModel(selector.getPredicate(multipart.getStateContainer()), partModels.get(selector).bake(partModels.get(selector).getDefaultState(), format, bakedTextureGetter));
    }

    IBakedModel bakedModel = builder.makeMultipartModel();
    return bakedModel;
}
 
Example 26
Project: hashsdn-controller   File: ClusterAdminRpcService.java   Source Code and License 5 votes vote down vote up
@Override
public Future<RpcResult<AddReplicasForAllShardsOutput>> addReplicasForAllShards() {
    LOG.info("Adding replicas for all shards");

    final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData = new ArrayList<>();
    Function<String, Object> messageSupplier = AddShardReplica::new;

    sendMessageToManagerForConfiguredShards(DataStoreType.Config, shardResultData, messageSupplier);
    sendMessageToManagerForConfiguredShards(DataStoreType.Operational, shardResultData, messageSupplier);

    return waitForShardResults(shardResultData, shardResults ->
            new AddReplicasForAllShardsOutputBuilder().setShardResult(shardResults).build(),
            "Failed to add replica");
}
 
Example 27
Project: Equella   File: CreateFromScratchTest.java   Source Code and License 5 votes vote down vote up
@Test(dependsOnMethods = "item")
public void waitUntilIndexed() throws Exception
{

	final int items = importer.getItemCount();
	RequestSpecification req = importer.searches().searchRequest("", null).queryParam("showall", true);
	importer.searches().waitUntilIgnoreError(req, new Function<ObjectNode, Boolean>()
	{
		@Override
		public Boolean apply(ObjectNode input)
		{
			return input.get("available").asInt() == items;
		}
	});
}
 
Example 28
Project: Adventurers-Toolbox   File: HoeModel.java   Source Code and License 5 votes vote down vote up
@Override
public IBakedModel bake(IModelState state, VertexFormat format,
		java.util.function.Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {

	ImmutableMap<TransformType, TRSRTransformation> transformMap = PerspectiveMapWrapper.getTransforms(state);

	TRSRTransformation transform = (TRSRTransformation.identity());

	ImmutableList.Builder<BakedQuad> builder = ImmutableList.builder();

	if (headTexture != null && haftTexture != null && handleTexture != null) {
		
		ImmutableList.Builder<ResourceLocation> texBuilder = ImmutableList.builder();
		if (haftTexture != null) {
			texBuilder.add(haftTexture);
		}
		if (headTexture != null) {
			texBuilder.add(headTexture);
		}
		if (handleTexture != null) {
			texBuilder.add(handleTexture);
		}
		if (adornmentTexture != null) {
			texBuilder.add(adornmentTexture);
		}
		ImmutableList<ResourceLocation> textures = texBuilder.build();
		
		IBakedModel model = (new ItemLayerModel(textures)).bake(state, format, bakedTextureGetter);
		builder.addAll(model.getQuads(null, null, 0));
	}

	return new BakedHoeModel(this, builder.build(), format, Maps.immutableEnumMap(transformMap),
			Maps.<String, IBakedModel>newHashMap());
}
 
Example 29
Project: azure-libraries-for-java   File: RedisCacheImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<ScheduleEntry> listPatchSchedules() {
    RedisPatchScheduleInner patchSchedules =  this.manager().inner().patchSchedules().get(resourceGroupName(), name());
    if (patchSchedules != null) {
        return Lists.transform(patchSchedules.scheduleEntries(),
                new Function<ScheduleEntryInner, ScheduleEntry>() {
                    public ScheduleEntry apply(ScheduleEntryInner entryInner) {
                        return new ScheduleEntry(entryInner);
                    }
                });
    }
    return null;
}
 
Example 30
Project: tac-kbp-eal   File: _EventArgumentLinking.java   Source Code and License 5 votes vote down vote up
public static EventArgumentLinking createMinimalLinkingFrom(AnswerKey answerKey) {
  final Function<Response, TypeRoleFillerRealis> ToEquivalenceClass =
      TypeRoleFillerRealis.extractFromSystemResponse(
          answerKey.corefAnnotation().strictCASNormalizerFunction());

  log.info("creating minimal linking for {} responses", answerKey.annotatedResponses().size());

  return EventArgumentLinking.builder().docID(answerKey.docId())
      .incomplete(FluentIterable.from(answerKey.annotatedResponses())
          .transform(AssessedResponseFunctions.response())
          .transform(ToEquivalenceClass)).build();
}
 
Example 31
Project: googles-monorepo-demo   File: ImmutableSortedMultisetTest.java   Source Code and License 5 votes vote down vote up
public void testCreation_arrayOfArray() {
  Comparator<String[]> comparator =
      Ordering.natural().lexicographical()
          .onResultOf(new Function<String[], Iterable<Comparable>>() {
            @Override
            public Iterable<Comparable> apply(String[] input) {
              return Arrays.<Comparable>asList(input);
            }
          });
  String[] array = new String[] {"a"};
  Multiset<String[]> multiset = ImmutableSortedMultiset.orderedBy(comparator).add(array).build();
  Multiset<String[]> expected = HashMultiset.create();
  expected.add(array);
  assertEquals(expected, multiset);
}
 
Example 32
Project: hue   File: VeroGoogleAnalyticsExpFormatter.java   Source Code and License 5 votes vote down vote up
public Function<Expression, String> expressionFormatterFunction()
{
    return new Function<Expression, String>()
    {
        @Override
        public String apply(Expression input)
        {
            return formatExpression(input);
        }
    };
}
 
Example 33
Project: shibboleth-idp-oidc-extension   File: AbstractSignJWTAction.java   Source Code and License 5 votes vote down vote up
/**
 * Set the strategy used to locate the {@link SecurityParametersContext} to use.
 * 
 * @param strategy
 *            lookup strategy
 */
public void setSecurityParametersLookupStrategy(
        @Nonnull final Function<ProfileRequestContext, SecurityParametersContext> strategy) {
    ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);

    securityParametersLookupStrategy = Constraint.isNotNull(strategy,
            "SecurityParameterContext lookup strategy cannot be null");
}
 
Example 34
Project: NBANDROID-V2   File: TestLaunchAction.java   Source Code and License 5 votes vote down vote up
public TestRunListener(final Project project) {
    Preconditions.checkNotNull(project);
    delegates = Lists.newArrayList(Iterables.concat(
            Collections.singleton(simpleLsnr),
            Iterables.transform(
                    project.getLookup().lookupAll(TestOutputConsumer.class),
                    new Function<TestOutputConsumer, ITestRunListener>() {

                @Override
                public ITestRunListener apply(TestOutputConsumer input) {
                    return input.createTestListener(project);
                }
            })));
    LOG.log(Level.FINE, "Sending test output to {0}", Iterables.toString(delegates));
}
 
Example 35
Project: appinventor-extensions   File: Urls.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a {@code Function} that encodes a URI query parameter by
 * calling {@link #escapeQueryParameter}.
 */
public static Function<String, String> getEscapeQueryParameterFunction() {
  return new Function<String, String>() {
    public String apply(String s) {
      return escapeQueryParameter(s);
    }
  };
}
 
Example 36
Project: Equella   File: AbstractEntityServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Collection<String> convertToUuids(Collection<T> entities)
{
	// Return a copy of the transformed list for serialization purposes
	return Lists.newArrayList(Collections2.transform(entities, new Function<T, String>()
	{
		@Override
		public String apply(T input)
		{
			return input.getUuid();
		}
	}));
}
 
Example 37
Project: sdoc   File: DocumentScanner.java   Source Code and License 5 votes vote down vote up
private Function<Map.Entry<RequestMappingInfo, HandlerMethod>, RequestHandler> toRequestHandler() {
    return new Function<Map.Entry<RequestMappingInfo, HandlerMethod>, RequestHandler>() {
        @Override
        public RequestHandler apply(Map.Entry<RequestMappingInfo, HandlerMethod> input) {
            return new RequestHandler(input.getKey(), input.getValue());
        }
    };
}
 
Example 38
Project: Re-Collector   File: NumberSuffixStrategy.java   Source Code and License 5 votes vote down vote up
public NumberSuffixStrategy(Set<Path> basePaths) {
    this.basePaths = Iterables.transform(basePaths, new Function<Path, Path>() {
        @Nullable
        @Override
        public Path apply(Path path) {
            return path.normalize().toAbsolutePath();
        }
    });
}
 
Example 39
Project: Jenkins-Plugin-Examples   File: WaitForConditionStep.java   Source Code and License 5 votes vote down vote up
private static void retry(final String id, final StepContext context) {
    StepExecution.applyAll(Execution.class, new Function<Execution, Void>() {
        @Override public Void apply(@Nonnull Execution execution) {
            if (execution.id.equals(id)) {
                execution.retry(context);
            }
            return null;
        }
    });
}
 
Example 40
Project: redirector   File: PendingChangeStatusHelper.java   Source Code and License 5 votes vote down vote up
public static Collection<String> getNewRulesIds (String objectType, PendingChangesStatus pendingChangesStatus) {

        Map<String, PendingChange> pendingRules = new HashMap<>();
        switch (objectType) {
            case RedirectorConstants.PENDING_STATUS_PATH_RULES: {
                pendingRules = pendingChangesStatus.getPathRules();
                break;
            }
            case RedirectorConstants.PENDING_STATUS_URL_RULES: {
                pendingRules = pendingChangesStatus.getUrlRules();
                break;
            }
            case RedirectorConstants.PENDING_STATUS_TEMPLATE_PATH_RULES: {
                pendingRules = pendingChangesStatus.getTemplatePathRules();
                break;
            }
            case RedirectorConstants.PENDING_STATUS_TEMPLATE_URL_PATH_RULES: {
                pendingRules = pendingChangesStatus.getTemplateUrlPathRules();
                break;
            }
            default:
        }

        return Lists.newArrayList(Iterables.filter(
                Iterables.transform(pendingRules.values(), new Function<PendingChange, String>() {
                    @Override
                    public String apply(@Nullable PendingChange input) {
                        return input != null && input.getChangeType() == ActionType.ADD ? input.getId() : null;
                    }
                }),
                Predicates.notNull()
        ));
    }
 
Example 41
Project: tac-kbp-eal   File: CorefAnnotation.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a function which normalizes {@link com.bbn.kbp.events2014.KBPString}s to some canonical
 * coreferent {@code KBPString}.  The particular {@code KBPString} returned is undefined, other
 * than being guaranteed to be coreferent and that it will be the same for all coreferent inputs.
 * If a provided {@code KBPString} has no coreference information, this behaves like the identity
 * function.
 */
public Function<KBPString, KBPString> laxCASNormalizerFunction() {
  return new Function<KBPString, KBPString>() {
    @Override
    public KBPString apply(KBPString input) {
      final Integer id = CASesToIDs.get(input);
      if (id != null) {
        // will never be null by construction of CASestoIDs & idToCASes
        return Iterables.getFirst(idToCASes.get(id), null);
      } else {
        return input;
      }
    }
  };
}
 
Example 42
Project: iotgateway   File: MqttGatewayService.java   Source Code and License 5 votes vote down vote up
private <T> boolean subscribe(Function<T, Boolean> f, T sub) {
  if (f.apply(sub)) {
    log.info("Subscription added: {}", sub);
    return true;
  } else {
    log.warn("Subscription was already added: {}", sub);
    return false;
  }
}
 
Example 43
Project: Equella   File: ViewItemServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<NameValue> getViewerNames()
{
	List<NameValue> viewers = Lists
		.newArrayList(Lists.transform(viewerPlugins.getExtensions(), new Function<Extension, NameValue>()
		{
			@Override
			public NameValue apply(Extension o)
			{
				String n = CurrentLocale.get(o.getParameter("nameKey").valueAsString());
				String v = o.getParameter("id").valueAsString();
				return new NameValue(n, v);
			}
		}));
	Collections.sort(viewers, new Comparator<NameValue>()
	{
		private final Map<String, Extension> extensions = viewerPlugins.getExtensionMap();

		@Override
		public int compare(NameValue o1, NameValue o2)
		{
			// Use order if it exists otherwise fall back to name
			Parameter p1 = extensions.get(o1.getValue()).getParameter("order");
			Parameter p2 = extensions.get(o2.getValue()).getParameter("order");
			if( p1 != null && p2 != null )
			{
				Integer x = p1.valueAsNumber().intValue();
				Integer y = p2.valueAsNumber().intValue();
				return Integer.compare(x, y);
			}
			return Format.NAME_VALUE_COMPARATOR.compare(o1, o2);
		}
	});
	return viewers;
}
 
Example 44
Project: googles-monorepo-demo   File: ForwardingWrapperTester.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that the forwarding wrapper returned by {@code wrapperFunction} properly forwards
 * method calls with parameters passed as is, return value returned as is, and exceptions
 * propagated as is.
 */
public <T> void testForwarding(
    Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) {
  checkNotNull(wrapperFunction);
  checkArgument(interfaceType.isInterface(), "%s isn't an interface", interfaceType);
  Method[] methods = getMostConcreteMethods(interfaceType);
  AccessibleObject.setAccessible(methods, true);
  for (Method method : methods) {
    // Under java 8, interfaces can have default methods that aren't abstract.
    // No need to verify them.
    // Can't check isDefault() for JDK 7 compatibility.
    if (!Modifier.isAbstract(method.getModifiers())) {
      continue;
    }
    // The interface could be package-private or private.
    // filter out equals/hashCode/toString
    if (method.getName().equals("equals")
        && method.getParameterTypes().length == 1
        && method.getParameterTypes()[0] == Object.class) {
      continue;
    }
    if (method.getName().equals("hashCode")
        && method.getParameterTypes().length == 0) {
      continue;
    }
    if (method.getName().equals("toString")
        && method.getParameterTypes().length == 0) {
      continue;
    }
    testSuccessfulForwarding(interfaceType, method, wrapperFunction);
    testExceptionPropagation(interfaceType, method, wrapperFunction);
  }
  if (testsEquals) {
    testEquals(interfaceType, wrapperFunction);
  }
  testToString(interfaceType, wrapperFunction);
}
 
Example 45
Project: guava-mock   File: EmptyCachesTest.java   Source Code and License 5 votes vote down vote up
/**
 * Most of the tests in this class run against every one of these caches.
 */
private Iterable<LoadingCache<Object, Object>> caches() {
  // lots of different ways to configure a LoadingCache
  CacheBuilderFactory factory = cacheFactory();
  return Iterables.transform(factory.buildAllPermutations(),
      new Function<CacheBuilder<Object, Object>, LoadingCache<Object, Object>>() {
        @Override public LoadingCache<Object, Object> apply(
            CacheBuilder<Object, Object> builder) {
          return builder.build(identityLoader());
        }
      });
}
 
Example 46
Project: ditb   File: KeyValueUtil.java   Source Code and License 5 votes vote down vote up
@Deprecated
public static List<KeyValue> ensureKeyValues(List<Cell> cells) {
  List<KeyValue> lazyList = Lists.transform(cells, new Function<Cell, KeyValue>() {
    @Override
    public KeyValue apply(Cell arg0) {
      return KeyValueUtil.ensureKeyValue(arg0);
    }
  });
  return new ArrayList<KeyValue>(lazyList);
}
 
Example 47
Project: CORNETTO   File: SpringAnimationService.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a function that calculates an edge length based on the correlation value of the edge
 * Correlation of -1 results in minmal length, Corr = +1 is maximal length
 * Gives preferred distance in integer values
 * @return edge length function used in the SpringLayout2
 */
private Function<MyEdge, Integer> getMyEdgeLengthFunction() {

    Function<MyEdge, Integer> foo = (MyEdge myEdge) -> {
        Double corr = myEdge.getCorrelation();

        // Corr = -1 --> Edgelength = minLength
        // Corr =  1 --> Edgelength = maxLength
        Double weight = (minLength + ((maxLength - minLength)/2)*(1 - corr));
        return weight.intValue();
    };
    return foo;
}
 
Example 48
Project: Reer   File: EclipsePlugin.java   Source Code and License 5 votes vote down vote up
private static void configureScalaDependencies(final Project project, final GenerateEclipseClasspath task) {
    project.getPlugins().withType(ScalaBasePlugin.class, new Action<ScalaBasePlugin>() {
        @Override
        public void execute(ScalaBasePlugin scalaBasePlugin) {
            task.getClasspath().containers("org.scala-ide.sdt.launching.SCALA_CONTAINER");

            // exclude the dependencies already provided by SCALA_CONTAINER; prevents problems with Eclipse Scala plugin
            project.getGradle().addBuildListener(new BuildAdapter() {
                @Override
                public void projectsEvaluated(Gradle gradle) {
                    final List<String> provided = Lists.newArrayList("scala-library", "scala-swing", "scala-dbc");
                    Predicate<Dependency> dependencyInProvided = new Predicate<Dependency>() {
                        @Override
                        public boolean apply(Dependency dependency) {
                            return provided.contains(dependency.getName());
                        }

                    };
                    List<Dependency> dependencies = Lists.newArrayList(Iterables.filter(Iterables.concat(Iterables.transform(task.getClasspath().getPlusConfigurations(), new Function<Configuration, Iterable<Dependency>>() {
                        @Override
                        public Iterable<Dependency> apply(Configuration config) {
                            return config.getAllDependencies();
                        }

                    })), dependencyInProvided));
                    if (!dependencies.isEmpty()) {
                        task.getClasspath().getMinusConfigurations().add(project.getConfigurations().detachedConfiguration(dependencies.toArray(new Dependency[0])));
                    }
                }
            });
        }

    });
}
 
Example 49
Project: circus-train   File: ConfigurationPojosTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPojo() {
  ValidatorBuilder
      .create()
      .with(new GetterMustExistRule())
      .with(new SetterMustExistRule())
      .with(new SetterTester())
      .with(new GetterTester())
      .build()
      .validate(Lists.transform(
          ImmutableList
              .<Class<?>> builder()
              .add(MetastoreTunnel.class)
              .add(ReplicaTable.class)
              .add(ReplicaCatalog.class)
              .add(Security.class)
              .add(SourceCatalog.class)
              .add(SourceTable.class)
              .add(TableReplication.class)
              .add(TableReplications.class)
              .add(MetricsReporter.class)
              .build(),
          new Function<Class<?>, PojoClass>() {
            @Override
            public PojoClass apply(Class<?> input) {
              return PojoClassFactory.getPojoClass(input);
            }
          }));
}
 
Example 50
Project: iotplatform   File: BaseAssetService.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<List<Asset>> findAssetsByQuery(AssetSearchQuery query) {
  ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(query.toEntitySearchQuery());
  ListenableFuture<List<Asset>> assets = Futures.transform(relations,
      (AsyncFunction<List<EntityRelation>, List<Asset>>) relations1 -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<Asset>> futures = new ArrayList<>();
        for (EntityRelation relation : relations1) {
          EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
          if (entityId.getEntityType() == ThingType.ASSET) {
            futures.add(findAssetByIdAsync(new AssetId(entityId.getId())));
          }
        }
        return Futures.successfulAsList(futures);
      });

  assets = Futures.transform(assets, new Function<List<Asset>, List<Asset>>() {
    @Nullable
    @Override
    public List<Asset> apply(@Nullable List<Asset> assetList) {
      return assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType()))
          .collect(Collectors.toList());
    }
  });

  return assets;
}
 
Example 51
Project: googles-monorepo-demo   File: FuturesTest.java   Source Code and License 5 votes vote down vote up
@GwtIncompatible // used only in GwtIncompatible tests
private static Function<Integer, Integer> newOneTimeExceptionThrower() {
  return new Function<Integer, Integer>() {
    int calls = 0;

    @Override
    public Integer apply(Integer from) {
      if (++calls > 1) {
        fail();
      }
      throw new MyRuntimeException();
    }
  };
}
 
Example 52
Project: Equella   File: MyPagesServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public HtmlAttachment clonePage(final WizardStateInterface state, final Item sourceItem,
	final HtmlAttachment sourcePage, boolean draft)
{
	final HtmlAttachment newPage = (HtmlAttachment) sourcePage.clone();
	newPage.setUuid(UUID.randomUUID().toString());
	newPage.setId(0);
	newPage.setNew(draft);
	newPage.setDraft(draft);

	ItemFile itemFile = itemFileService.getItemFile(sourceItem);

	final String newHtml = forFile(itemFile, sourcePage.getFilename(), new Function<Reader, String>()
	{
		@Override
		@Nullable
		public String apply(@Nullable Reader input)
		{
			List<HrefConversion> conversions = new StagingConversion(true, sourceItem.getItemId(), state.getWizid(),
				state.getStagingId(), sourcePage.getFolder(), newPage.getFolder()).getConversions();
			return convertHtmlService.convert(input, false, conversions);
		}
	});

	final FileHandle destHandle = state.getFileHandle();
	// clone attachments first
	fileSystemService.copy(itemFile, sourcePage.getFolder(), destHandle, newPage.getFolder());

	saveHtml(destHandle, newPage.getFilename(), newHtml);

	return newPage;
}
 
Example 53
Project: dremio-oss   File: MapWithOrdinal.java   Source Code and License 5 votes vote down vote up
@Override
public Collection<V> values() {
  return Lists.newArrayList(Iterables.transform(secondary.entries(), new Function<IntObjectMap.Entry<V>, V>() {
    @Override
    public V apply(IntObjectMap.Entry<V> entry) {
      return Preconditions.checkNotNull(entry).value();
    }
  }));
}
 
Example 54
Project: dremio-oss   File: ApiIntentMessageMapper.java   Source Code and License 5 votes vote down vote up
private List<RowTypeApiDescriptor.Field> toApiRowTypeFields(final List<ViewFieldType> fieldList) {
  return FluentIterable
      .from(AccelerationUtils.selfOrEmpty(fieldList))
      .transform(new Function<ViewFieldType, RowTypeApiDescriptor.Field>() {
        @Nullable
        @Override
        public RowTypeApiDescriptor.Field apply(@Nullable final ViewFieldType input) {
          return new RowTypeApiDescriptor.Field()
              .setName(input.getName())
              .setType(Optional.fromNullable(API_TYPES.get(input.getType())).or(RowTypeApiDescriptor.FieldType.OTHER))
              .setTypeFamily(input.getTypeFamily());
        }
      })
      .toList();
}
 
Example 55
Project: dremio-oss   File: LocalIndexedStore.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Map.Entry<K, V>> find() {
  return Iterables.transform(coreIndexedStore.find(), new Function<Map.Entry<KVStoreTuple<K>, KVStoreTuple<V>>, Map.Entry<K, V>>() {
    @Override
    public Map.Entry<K, V> apply(final Map.Entry<KVStoreTuple<K>, KVStoreTuple<V>> input) {
      return new ConvertingEntry(input);
    }
  });
}
 
Example 56
Project: dremio-oss   File: AccelerationUtils.java   Source Code and License 5 votes vote down vote up
private static List<String> getNames(List<LayoutField> fields){
  return FluentIterable.from(fields).transform(new Function<LayoutField, String>(){
    @Override
    public String apply(LayoutField input) {
      return input.getName();
    }}).toList();
}
 
Example 57
Project: EscapeLag   File: AbstractMultipleInjector.java   Source Code and License 5 votes vote down vote up
public Map<String, Long> getTotalTime() {
	return Maps.transformValues(map, new Function<MonitorRecord, Long>() {
		@Override
		public Long apply(MonitorRecord input) {
			return input.getTotalTime();
		}
	});
}
 
Example 58
Project: googles-monorepo-demo   File: ForwardingWrapperTesterTest.java   Source Code and License 5 votes vote down vote up
public void testCovariantReturn() {
  new ForwardingWrapperTester().testForwarding(Sub.class, new Function<Sub, Sub>() {
    @Override public Sub apply(Sub sub) {
      return new ForwardingSub(sub);
    }
  });
}
 
Example 59
Project: guava-mock   File: ImmutableSortedMultisetTest.java   Source Code and License 5 votes vote down vote up
public void testCreation_arrayOfArray() {
  Comparator<String[]> comparator =
      Ordering.natural().lexicographical()
          .onResultOf(new Function<String[], Iterable<Comparable>>() {
            @Override
            public Iterable<Comparable> apply(String[] input) {
              return Arrays.<Comparable>asList(input);
            }
          });
  String[] array = new String[] {"a"};
  Multiset<String[]> multiset = ImmutableSortedMultiset.orderedBy(comparator).add(array).build();
  Multiset<String[]> expected = HashMultiset.create();
  expected.add(array);
  assertEquals(expected, multiset);
}
 
Example 60
Project: redirector   File: StacksService.java   Source Code and License 5 votes vote down vote up
private Map<XreStackPath, Integer> getStackToNodesCount(Collection<XreStackPath> stackPaths) {
    return Maps.toMap(stackPaths, new Function<XreStackPath, Integer>() {
        @Override
        public Integer apply(XreStackPath input) {
            try {
                return stacksDAO.getHostsCount(input);
            } catch (RedirectorDataSourceException e) {
                log.error("failed to get hosts count for " + input.getPath());
                throw new ServiceException("failed to get hosts count for " + input.getPath(), e);
            }
        }
    });
}