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: DecompiledMinecraft   File: ItemMultiTexture.java   View source code 7 votes vote down vote up
public ItemMultiTexture(Block block, Block block2, final String[] namesByMeta)
{
    this(block, block2, new Function<ItemStack, String>()
    {
        public String apply(ItemStack p_apply_1_)
        {
            int i = p_apply_1_.getMetadata();

            if (i < 0 || i >= namesByMeta.length)
            {
                i = 0;
            }

            return namesByMeta[i];
        }
    });
}
 
Example 2
Project: dremio-oss   File: ElasticMappingSet.java   View source code 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 3
Project: guava-mock   File: FuturesTest.java   View source code 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 4
Project: n4js   File: TestTreeRegistryTest.java   View source code 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 5
Project: Reer   File: ModelPathSuggestionProvider.java   View source code 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 6
Project: Equella   File: DrmScriptWrapper.java   View source code 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 7
Project: burp-vulners-scanner   File: PathIssue.java   View source code 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 8
Project: pact-spring-mvc   File: DefaultPactResolver.java   View source code 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 9
Project: hashsdn-controller   File: TransactionProxy.java   View source code 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 10
Project: iotplatform   File: CassandraBaseTimeseriesDao.java   View source code 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 11
Project: athena   File: DefaultOvsdbClient.java   View source code 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 12
Project: Reer   File: DefaultTaskOutputs.java   View source code 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 13
Project: vscrawler   File: FetchTaskProcessor.java   View source code 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 14
Project: googles-monorepo-demo   File: FuturesTest.java   View source code 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 15
Project: googles-monorepo-demo   File: AbstractNetwork.java   View source code 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 16
Project: randomito-all   File: AnnotationPostProcessorScanner.java   View source code 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 17
Project: rx-twitter-stream-android   File: StreamActivityTest.java   View source code 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 18
Project: guava-mock   File: AbstractCatchingFuture.java   View source code 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 19
Project: Equella   File: EmailSelectorWebControl.java   View source code 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 20
Project: Equella   File: AbstractPopupBrowserDialog.java   View source code 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 21
Project: guava-mock   File: ForwardingWrapperTesterTest.java   View source code 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 22
Project: dremio-oss   File: FlattenRelBase.java   View source code 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 23
Project: Proyecto2017Seguros   File: ClientesPorCumpleaños.java   View source code 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 24
Project: Adventurers-Toolbox   File: PickaxeModel.java   View source code 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 25
Project: dremio-oss   File: FixHiveMetadata.java   View source code 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 26
Project: CustomWorldGen   File: ModelLoader.java   View source code 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 27
Project: hashsdn-controller   File: ClusterAdminRpcService.java   View source code 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 28
Project: Equella   File: CreateFromScratchTest.java   View source code 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 29
Project: Adventurers-Toolbox   File: HoeModel.java   View source code 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 30
Project: azure-libraries-for-java   File: RedisCacheImpl.java   View source code 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 31
Project: tac-kbp-eal   File: _EventArgumentLinking.java   View source code 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 32
Project: googles-monorepo-demo   File: ImmutableSortedMultisetTest.java   View source code 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 33
Project: hue   File: VeroGoogleAnalyticsExpFormatter.java   View source code 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 34
Project: shibboleth-idp-oidc-extension   File: AbstractSignJWTAction.java   View source code 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 35
Project: NBANDROID-V2   File: TestLaunchAction.java   View source code 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 36
Project: appinventor-extensions   File: Urls.java   View source code 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 37
Project: Equella   File: AbstractEntityServiceImpl.java   View source code 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 38
Project: sdoc   File: DocumentScanner.java   View source code 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 39
Project: Re-Collector   File: NumberSuffixStrategy.java   View source code 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 40
Project: Jenkins-Plugin-Examples   File: WaitForConditionStep.java   View source code 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;
        }
    });
}