@Override public Ordering<Element> enclosedBy(Element element) { if (element instanceof ElementImpl && Iterables.all(element.getEnclosedElements(), Predicates.instanceOf(ElementImpl.class))) { ElementImpl implementation = (ElementImpl) element; if (implementation._binding instanceof SourceTypeBinding) { SourceTypeBinding sourceBinding = (SourceTypeBinding) implementation._binding; return Ordering.natural().onResultOf( Functions.compose(bindingsToSourceOrder(sourceBinding), this)); } } return DEFAULT_PROVIDER.enclosedBy(element); }
public void testBulkGetReturnsSorted() { for (Striped<?> striped : allImplementations()) { Map<Object, Integer> indexByLock = Maps.newHashMap(); for (int i = 0; i < striped.size(); i++) { indexByLock.put(striped.getAt(i), i); } // ensure that bulkGet returns locks in monotonically increasing order for (int objectsNum = 1; objectsNum <= striped.size() * 2; objectsNum++) { Set<Object> objects = Sets.newHashSetWithExpectedSize(objectsNum); for (int i = 0; i < objectsNum; i++) { objects.add(new Object()); } Iterable<?> locks = striped.bulkGet(objects); assertTrue(Ordering.natural().onResultOf(Functions.forMap(indexByLock)).isOrdered(locks)); // check idempotency Iterable<?> locks2 = striped.bulkGet(objects); assertEquals(Lists.newArrayList(locks), Lists.newArrayList(locks2)); } } }
public void testTransformReflectsUnderlyingMap() { Map<String, Integer> underlying = Maps.newHashMap(); underlying.put("a", 1); underlying.put("b", 2); underlying.put("c", 3); Map<String, String> map = Maps.transformValues(underlying, Functions.toStringFunction()); assertEquals(underlying.size(), map.size()); underlying.put("d", 4); assertEquals(underlying.size(), map.size()); assertEquals("4", map.get("d")); underlying.remove("c"); assertEquals(underlying.size(), map.size()); assertFalse(map.containsKey("c")); underlying.clear(); assertEquals(underlying.size(), map.size()); }
public void testTransformEquals() { Map<String, Integer> underlying = ImmutableMap.of("a", 0, "b", 1, "c", 2); Map<String, Integer> expected = Maps.transformValues(underlying, Functions.<Integer>identity()); assertMapsEqual(expected, expected); Map<String, Integer> equalToUnderlying = Maps.newTreeMap(); equalToUnderlying.putAll(underlying); Map<String, Integer> map = Maps.transformValues( equalToUnderlying, Functions.<Integer>identity()); assertMapsEqual(expected, map); map = Maps.transformValues(ImmutableMap.of("a", 1, "b", 2, "c", 3), new Function<Integer, Integer>() { @Override public Integer apply(Integer from) { return from - 1; } } ); assertMapsEqual(expected, map); }
public void testOnResultOf_chained() { Comparator<String> comparator = DECREASING_INTEGER.onResultOf( StringLengthFunction.StringLength); assertTrue(comparator.compare("to", "be") == 0); assertTrue(comparator.compare("not", "or") < 0); assertTrue(comparator.compare("to", "that") > 0); new EqualsTester() .addEqualityGroup( comparator, DECREASING_INTEGER.onResultOf(StringLengthFunction.StringLength)) .addEqualityGroup( DECREASING_INTEGER.onResultOf(Functions.constant(1))) .addEqualityGroup(Ordering.natural()) .testEquals(); reserializeAndAssert(comparator); assertEquals("Ordering.natural().reverse().onResultOf(StringLength)", comparator.toString()); }
@Override public ListenableFuture<Long> visitGrantPrivilegeAnalyzedStatement(GrantPrivilegeAnalyzedStatement analysis, SingleJobTask jobId) { String tableName = analysis.getTable(); boolean isDBPrivilege = true; if (tableName.contains(".")) { isDBPrivilege = false; } GrantOrRevokeUserPrivilegeRequest grantRequest = new GrantOrRevokeUserPrivilegeRequest(analysis.getUsername(), tableName, PrivilegeType.valueOf(analysis.getPrivilege().toUpperCase()), isDBPrivilege, true); grantRequest.putHeader(LoginUserContext.USER_INFO_KEY, analysis.getParameterContext().getLoginUserContext()); final SettableFuture<Long> future = SettableFuture.create(); ActionListener<GrantOrRevokeUserPrivilegeResponse> listener = ActionListeners.wrap(future, Functions.<Long>constant(ONE)); transportActionProvider.transportGrantOrRevokeUserPrivilegeAction().execute(grantRequest, listener); return future; }
@Override public ListenableFuture<Long> visitRevokePrivilegeAnalyzedStatement(RevokePrivilegeAnalyzedStatement analysis, SingleJobTask jobId) { String tableName = analysis.getTable(); boolean isDBPrivilege = true; if (tableName.contains(".")) { isDBPrivilege = false; } GrantOrRevokeUserPrivilegeRequest grantRequest = new GrantOrRevokeUserPrivilegeRequest(analysis.getUsername(), tableName, PrivilegeType.valueOf(analysis.getPrivilege().toUpperCase()), isDBPrivilege, false); grantRequest.putHeader(LoginUserContext.USER_INFO_KEY, analysis.getParameterContext().getLoginUserContext()); final SettableFuture<Long> future = SettableFuture.create(); ActionListener<GrantOrRevokeUserPrivilegeResponse> listener = ActionListeners.wrap(future, Functions.<Long>constant(ONE)); transportActionProvider.transportGrantOrRevokeUserPrivilegeAction().execute(grantRequest, listener); return future; }
public ListenableFuture<Long> dispatch(final RestoreSnapshotAnalyzedStatement analysis) { final SettableFuture<Long> resultFuture = SettableFuture.create(); boolean waitForCompletion = analysis.settings().getAsBoolean(WAIT_FOR_COMPLETION.settingName(), WAIT_FOR_COMPLETION.defaultValue()); boolean ignoreUnavailable = analysis.settings().getAsBoolean(IGNORE_UNAVAILABLE.settingName(), IGNORE_UNAVAILABLE.defaultValue()); // ignore_unavailable as set by statement IndicesOptions indicesOptions = IndicesOptions.fromOptions(ignoreUnavailable, true, true, false, IndicesOptions.lenientExpandOpen()); RestoreSnapshotRequest request = new RestoreSnapshotRequest(analysis.repositoryName(), analysis.snapshotName()) .indices(analysis.indices()) .indicesOptions(indicesOptions) .settings(analysis.settings()) .waitForCompletion(waitForCompletion) .includeGlobalState(false) .includeAliases(true); ActionListener<RestoreSnapshotResponse> listener = ActionListeners.wrap(resultFuture, Functions.constant(1L)); transportActionProvider.transportRestoreSnapshotAction().execute(request, listener); return resultFuture; }
public ESClusterUpdateSettingsTask(UUID jobId, TransportClusterUpdateSettingsAction transport, ESClusterUpdateSettingsNode node) { super(jobId); this.transport = transport; final SettableFuture<TaskResult> result = SettableFuture.create(); results = Collections.<ListenableFuture<TaskResult>>singletonList(result); request = new ClusterUpdateSettingsRequest(); request.persistentSettings(node.persistentSettings()); request.transientSettings(node.transientSettings()); if (node.persistentSettingsToRemove() != null) { request.persistentSettingsToRemove(node.persistentSettingsToRemove()); } if (node.transientSettingsToRemove() != null) { request.transientSettingsToRemove(node.transientSettingsToRemove()); } listener = ActionListeners.wrap(result, Functions.constant(TaskResult.ONE_ROW)); }
private static String propertyDescription(ModelSchemaExtractionContext<?> parentContext, ModelProperty<?> property) { if (property.getDeclaredBy().size() == 1 && property.getDeclaredBy().contains(parentContext.getType())) { return String.format("property '%s'", property.getName()); } else { ImmutableSortedSet<String> declaredBy = ImmutableSortedSet.copyOf(Iterables.transform(property.getDeclaredBy(), Functions.toStringFunction())); return String.format("property '%s' declared by %s", property.getName(), Joiner.on(", ").join(declaredBy)); } }
public void testToMapWithNullValues() { Iterable<String> strings = ImmutableList.of("one", "two", "three"); try { Maps.toMap(strings, Functions.constant(null)); fail(); } catch (NullPointerException expected) { } }
public void testToMap() { assertThat(fluent(1, 2, 3).toMap(Functions.toStringFunction()).entrySet()) .containsExactly( Maps.immutableEntry(1, "1"), Maps.immutableEntry(2, "2"), Maps.immutableEntry(3, "3")).inOrder(); }
private static Function<DocumentSystemOutput, DocumentSystemOutput> getSystemOutputFilter( Parameters params) { final Function<DocumentSystemOutput, DocumentSystemOutput> filter; if (params.getBoolean("importOnlyBestAnswers")) { filter = KeepBestJustificationOnly.asFunctionOnSystemOutput(); log.info("Importing only responses the scorer would select"); } else { filter = Functions.identity(); log.info("Importing all responses"); } return filter; }
@Test public void returnProperBeanParamWithDefaultParameterExtension() throws NoSuchMethodException { final Method method = getClass().getDeclaredMethod("testRoute", BaseBean.class, ChildBean.class, RefBean.class, EnumBean.class, Integer.class); final List<Pair<Type, Annotation[]>> parameters = getParameters(method.getGenericParameterTypes(), method.getParameterAnnotations()); for (final Pair<Type, Annotation[]> parameter : parameters) { final Type parameterType = parameter.first(); final List<Parameter> swaggerParams = new DefaultParameterExtension().extractParameters(Arrays.asList(parameter.second()), parameterType, new HashSet<Type>(), SwaggerExtensions.chain()); // Ensure proper number of parameters returned if (parameterType.equals(BaseBean.class)) { assertEquals(2, swaggerParams.size()); } else if (parameterType.equals(ChildBean.class)) { assertEquals(5, swaggerParams.size()); } else if (parameterType.equals(RefBean.class)) { assertEquals(5, swaggerParams.size()); } else if (parameterType.equals(EnumBean.class)) { assertEquals(1, swaggerParams.size()); final HeaderParameter enumParam = (HeaderParameter) swaggerParams.get(0); assertEquals("string", enumParam.getType()); final List<String> enumValues = new ArrayList<>(Collections2.transform(Arrays.asList(TestEnum.values()), Functions.toStringFunction())); assertEquals(enumValues, enumParam.getEnum()); } else if (parameterType.equals(Integer.class)) { assertEquals(0, swaggerParams.size()); } else { fail(String.format("Parameter of type %s was not expected", parameterType)); } // Ensure the proper parameter type and name is returned (The rest is handled by pre-existing logic) for (final Parameter param : swaggerParams) { assertEquals(param.getClass().getSimpleName().replace("eter", ""), param.getName()); } } }
/** * Takes this AnswerKey as ground truth, and takes unannotated or assessed Responses in fallback * and adds them to the AnswerKey. * * If the CAS for an AssessedResponse is known, prefer that CAS to the CAS in fallback. * * Does not handle the case where the fallback AnswerKey has an Assessment that this AnswerKey * does not. */ public AnswerKey copyFallingBackTo(AnswerKey fallback) { final Builder ret = modifiedCopyBuilder(); final ImmutableMap<String, Response> unannotatedHere = Maps.uniqueIndex(unannotatedResponses(), ResponseFunctions.uniqueIdentifier()); final ImmutableMap<String, AssessedResponse> idToAssessedHere = Maps.uniqueIndex(annotatedResponses(), Functions.compose(ResponseFunctions.uniqueIdentifier(), AssessedResponseFunctions.response())); final Set<String> idsHere = Sets.union(unannotatedHere.keySet(), idToAssessedHere.keySet()); final ImmutableMap<String, Response> unannotatedThere = Maps.uniqueIndex( fallback.unannotatedResponses(), ResponseFunctions.uniqueIdentifier()); final ImmutableMap<String, AssessedResponse> idToAssessedThere = Maps.uniqueIndex(fallback.annotatedResponses(), Functions.compose(ResponseFunctions.uniqueIdentifier(), AssessedResponseFunctions.response())); final Set<String> idsThere = Sets.union(unannotatedThere.keySet(), idToAssessedThere.keySet()); final Set<String> idsOnlyInFallback = Sets.difference(idsThere, idsHere); for (final String id : idsOnlyInFallback) { if (unannotatedThere.containsKey(id)) { ret.addUnannotated(unannotatedThere.get(id)); } if (idToAssessedThere.containsKey(id)) { final AssessedResponse r = idToAssessedThere.get(id); final int CASGroup; if (corefAnnotation().CASesToIDs().containsKey(r.response().canonicalArgument())) { CASGroup = corefAnnotation().CASesToIDs().get(r.response().canonicalArgument()); } else { CASGroup = fallback.corefAnnotation().CASesToIDs().get(r.response().canonicalArgument()); } ret.addAnnotated(r, CASGroup); } } return ret.build(); }
@Test public void testLessSpecific() { final KBPTIMEXExpression specific = KBPTIMEXExpression.parseTIMEX("1982-12-31"); final Set<KBPTIMEXExpression> lessSpecific = specific.lessSpecificCompatibleTimes(); final Set<String> reference = ImmutableSet.of("1982-12-3X", "1982-12-XX", "1982-1X-XX", "1982-XX-XX", "198X-XX-XX", "19XX-XX-XX", "1XXX-XX-XX"); assertEquals(reference, FluentIterable.from(lessSpecific) .transform(Functions.toStringFunction()) .toSet()); }
private BreakdownComputer(Map<String, Function<ProvenanceType, Symbol>> breakdownFunctions) { final ImmutableMap.Builder<String, Function<? super ProvenanceType, Symbol>> builder = ImmutableMap.builder(); builder.put("Aggregate", Functions.constant(Symbol.from("Aggregate"))); builder.putAll(breakdownFunctions); this.breakdownFunctions = builder.build(); }
public static List<String> getListOfStringsMatching(String input, Collection<?> possibleCompletions) { List<String> list = Lists.<String>newArrayList(); if (!possibleCompletions.isEmpty()) { for (String s1 : Iterables.transform(possibleCompletions, Functions.toStringFunction())) { if (doesStringStartWith(input, s1)) { list.add(s1); } } if (list.isEmpty()) { for (Object object : possibleCompletions) { if (object instanceof ResourceLocation && doesStringStartWith(input, ((ResourceLocation)object).getResourcePath())) { list.add(String.valueOf(object)); } } } } return list; }
@Override protected Map<String, String> makePopulatedMap() { Map<String, Integer> underlying = Maps.newHashMap(); underlying.put("a", 1); underlying.put("b", 2); underlying.put("c", 3); return Maps.transformValues( new UnmodifiableIteratorMap<String, Integer>(underlying), Functions.toStringFunction()); }
public static List<String> getListOfStringsMatchingLastWord(String[] inputArgs, Collection<?> possibleCompletions) { String s = inputArgs[inputArgs.length - 1]; List<String> list = Lists.<String>newArrayList(); if (!possibleCompletions.isEmpty()) { for (String s1 : Iterables.transform(possibleCompletions, Functions.toStringFunction())) { if (doesStringStartWith(s, s1)) { list.add(s1); } } if (list.isEmpty()) { for (Object object : possibleCompletions) { if (object instanceof ResourceLocation && doesStringStartWith(s, ((ResourceLocation)object).getResourcePath())) { list.add(String.valueOf(object)); } } } } return list; }
public void testTransformRemoveEntry() { Map<String, Integer> underlying = Maps.newHashMap(); underlying.put("a", 1); Map<String, String> map = Maps.transformValues(underlying, Functions.toStringFunction()); assertEquals("1", map.remove("a")); assertNull(map.remove("b")); }
private static <N> GraphConnections<N, Presence> connectionsOf(Graph<N> graph, N node) { Function<Object, Presence> edgeValueFn = Functions.constant(Presence.EDGE_EXISTS); return graph.isDirected() ? DirectedGraphConnections.ofImmutable( graph.predecessors(node), Maps.asMap(graph.successors(node), edgeValueFn)) : UndirectedGraphConnections.ofImmutable( Maps.asMap(graph.adjacentNodes(node), edgeValueFn)); }
public void testIndex_nullValue() { try { ImmutableListMultimap<String, Integer> unused = fluent(1, null, 2).index(Functions.constant("foo")); fail(); } catch (NullPointerException expected) { } }
public void testTransformSingletonMapEquality() { Map<String, String> map = Maps.transformValues( ImmutableMap.of("a", 1), Functions.toStringFunction()); Map<String, String> expected = ImmutableMap.of("a", "1"); assertMapsEqual(expected, map); assertEquals(expected.get("a"), map.get("a")); }
/** Can't create the map if more than one value maps to the same key. */ public void testUniqueIndexDuplicates() { try { Map<Integer, String> unused = Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).contains("Multimaps.index"); } }
@Override protected SortedMap<String, String> makePopulatedMap() { SortedMap<String, Integer> underlying = Maps.newTreeMap(); underlying.put("a", 1); underlying.put("b", 2); underlying.put("c", 3); return Maps.transformValues(underlying, Functions.toStringFunction()); }
public void testToMapWithNullKeys() { Iterable<String> strings = Arrays.asList("one", null, "three"); try { Maps.toMap(strings, Functions.constant("foo")); fail(); } catch (NullPointerException expected) { } }
public void testIndex() { final Multimap<String, Object> stringToObject = new ImmutableMultimap.Builder<String, Object>() .put("1", 1) .put("1", 1L) .put("1", "1") .put("2", 2) .put("2", 2L) .build(); ImmutableMultimap<String, Object> outputMap = Multimaps.index(stringToObject.values(), Functions.toStringFunction()); assertEquals(stringToObject, outputMap); }
public void testIndex_nullKey() { try { ImmutableListMultimap<Object, Integer> unused = fluent(1, 2, 3).index(Functions.constant(null)); fail(); } catch (NullPointerException expected) { } }
/** Null keys aren't allowed either. */ public void testUniqueIndexNullKey() { List<String> oneStringList = Lists.newArrayList("foo"); try { Maps.uniqueIndex(oneStringList, Functions.constant(null)); fail(); } catch (NullPointerException expected) { } }
public void testToMap_nullKey() { try { fluent(1, null, 2).toMap(Functions.constant("foo")); fail(); } catch (NullPointerException expected) { } }
public void testToMap_nullValue() { try { fluent(1, 2, 3).toMap(Functions.constant(null)); fail(); } catch (NullPointerException expected) { } }