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]; } }); }
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(); }})); }
@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(); }
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); }
@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); }
@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); }
@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(); }
@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); } }); }
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); }
@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); }
@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; }
@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; }
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; }
@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(); }
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); }
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); }
@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; } }; } }; }
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; }
@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); } } } }
@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); } }); }
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()"); }
public Set<Integer> getFlattenedIndices(){ return FluentIterable.from(getToFlatten()).transform(new Function<RexInputRef, Integer>(){ @Override public Integer apply(RexInputRef input) { return input.getIndex(); }}).toSet(); }
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); } }; }
@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); }
@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); } }
@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; }
@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"); }
@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; } }); }
@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()); }
@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; }
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(); }
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); }
public Function<Expression, String> expressionFormatterFunction() { return new Function<Expression, String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
/** * 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"); }
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)); }
/** * 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); } }; }
@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(); } })); }
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()); } }; }
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(); } }); }
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; } }); }