com.google.common.base.Functions Java Examples

The following examples show how to use com.google.common.base.Functions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HazelcastNodeImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
protected void connectSensors() {
    super.connectSensors();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting sensors for node: {} ", getAttribute(Attributes.HOSTNAME));
    }
    
    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getNodePort());

    String nodeUri = String.format("http://%s:%d/hazelcast/rest/cluster", hp.getHostText(), hp.getPort());
    sensors().set(Attributes.MAIN_URI, URI.create(nodeUri));

    if (LOG.isDebugEnabled()) {
        LOG.debug("Node {} is using {} as a main URI", this, nodeUri);
    }
    
    httpFeed = HttpFeed.builder()
            .entity(this)
            .period(3000, TimeUnit.MILLISECONDS)
            .baseUri(nodeUri)
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP)
                    .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .build();
}
 
Example #2
Source File: CameraResolver.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Action generate(ActionContext context, Address target, Map<String, Object> variables) {
   Object duration = (Object) variables.get("duration");
   Preconditions.checkNotNull(duration, "duration is required");
   int durationSec = AttributeTypes.coerceInt(duration);
   Preconditions.checkArgument(durationSec >= MIN_DURATION && durationSec <= MAX_DURATION, "Invalid duration");
   
   MessageBody payload =
      VideoService.StartRecordingRequest
         .builder()
         .withAccountId(getAccountId(context))
         .withCameraAddress(target.getRepresentation())
         .withDuration(durationSec)
         .withPlaceId(context.getPlaceId().toString())
         .withStream(false)
         .build();
      
   return new SendAction(payload.getMessageType(), Functions.constant(videoServiceAddress), payload.getAttributes());
}
 
Example #3
Source File: KBPEATestUtils.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
public static ResponseLinking dummyResponseLinkingFor(EventArgumentLinking linking) {
  final DummyResponseGenerator responseGenerator = new DummyResponseGenerator();
  final Map<TypeRoleFillerRealis, Response> canonicalResponses = Maps.newHashMap();

  final Iterable<TypeRoleFillerRealis> allTRFRs = ImmutableSet.copyOf(
      concat(concat(linking.eventFrames()), linking.incomplete()));

  for (final TypeRoleFillerRealis trfr : allTRFRs) {
    canonicalResponses.put(trfr, responseGenerator.responseFor(trfr));
  }

  final Function<TypeRoleFillerRealis, Response> canonicalResponseFunction =
      Functions.forMap(canonicalResponses);

  final ImmutableSet.Builder<ResponseSet> responseSets = ImmutableSet.builder();
  for (final TypeRoleFillerRealisSet trfrSet : linking.eventFrames()) {
    responseSets.add(ResponseSet.from(transform(trfrSet, canonicalResponseFunction)));
  }
  final Set<Response> incompletes = FluentIterable.from(linking.incomplete())
      .transform(canonicalResponseFunction).toSet();
  return ResponseLinking.builder().docID(linking.docID()).responseSets(responseSets.build())
    .incompleteResponses(incompletes).build();
}
 
Example #4
Source File: BaseJenkinsMockTest.java    From jenkins-rest with Apache License 2.0 6 votes vote down vote up
protected RecordedRequest assertSent(final MockWebServer server, 
        final String method, 
        final String expectedPath, 
        final Map<String, ?> queryParams) throws InterruptedException {

    RecordedRequest request = server.takeRequest();
    assertThat(request.getMethod()).isEqualTo(method);
    assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(APPLICATION_JSON);

    final String path = request.getPath();
    final String rawPath = path.contains("?") ? path.substring(0, path.indexOf('?')) : path;
    assertThat(rawPath).isEqualTo(expectedPath);

    final Map<String, String> normalizedParams = Maps.transformValues(queryParams, Functions.toStringFunction());
    assertThat(normalizedParams).isEqualTo(extractParams(path));

    return request;
}
 
Example #5
Source File: SourceOrdering.java    From immutables with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: CssStringNodeTest.java    From closure-stylesheets with Apache License 2.0 6 votes vote down vote up
@Test
public void testEscape() throws Exception {
  for (String[] io : new String[][] {
      {"", ""},
      {"a", "a"},
      {"\\", "\\\\"},
      {"19\\3=6", "19\\\\3=6"},
      {"say \"hello\"", "say \\\"hello\\\""},
      {"say 'goodbye'", "say 'goodbye'"}}) {
    assertThat(
            CssStringNode.escape(
                CssStringNode.Type.DOUBLE_QUOTED_STRING, Functions.<String>identity(), io[0]))
        .isEqualTo(io[1]);
  }
  assertThat(
          CssStringNode.escape(
              CssStringNode.Type.SINGLE_QUOTED_STRING,
              Functions.<String>identity(),
              "say 'goodbye'"))
      .isEqualTo("say \\'goodbye\\'");
}
 
Example #7
Source File: DDLStatementDispatcher.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: MemoryGroupByAggregationTest.java    From hop with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testNullMin() throws Exception {
  variables.setVariable( Const.HOP_AGGREGATION_MIN_NULL_IS_VALUED, "Y" );

  addColumn( new ValueMetaInteger( "intg" ), null, 0L, 1L, -1L );
  addColumn( new ValueMetaString( "str" ), "A", null, "B", null );

  aggregates = Maps.toMap( ImmutableList.of( "min", "max" ), Functions.forMap( default_aggregates ) );

  RowMetaAndData output = runTransform();

  assertThat( output.getInteger( "intg_min" ), nullValue() );
  assertThat( output.getInteger( "intg_max" ), is( 1L ) );

  assertThat( output.getString( "str_min", null ), nullValue() );
  assertThat( output.getString( "str_max", "invalid" ), is( "B" ) );
}
 
Example #9
Source File: MemoryGroupByAggregationTest.java    From hop with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullMin() throws Exception {
  variables.setVariable( Const.HOP_AGGREGATION_MIN_NULL_IS_VALUED, "Y" );

  addColumn( new ValueMetaInteger( "intg" ), null, 0L, 1L, -1L );
  addColumn( new ValueMetaString( "str" ), "A", null, "B", null );

  aggregates = Maps.toMap( ImmutableList.of( "min", "max" ), Functions.forMap( default_aggregates ) );

  RowMetaAndData output = runTransform();

  assertThat( output.getInteger( "intg_min" ), nullValue() );
  assertThat( output.getInteger( "intg_max" ), is( 1L ) );

  assertThat( output.getString( "str_min", null ), nullValue() );
  assertThat( output.getString( "str_max", "invalid" ), is( "B" ) );
}
 
Example #10
Source File: ProguardTranslatorFactory.java    From buck with Apache License 2.0 6 votes vote down vote up
private Function<String, String> createFunction(
    final boolean isForObfuscation, final boolean isNullable) {
  if (!rawMap.isPresent()) {
    return Functions.identity();
  }

  ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
  for (Map.Entry<String, String> entry : rawMap.get().entrySet()) {
    String original = entry.getKey().replace('.', '/');
    String obfuscated = entry.getValue().replace('.', '/');
    builder.put(
        isForObfuscation ? original : obfuscated, isForObfuscation ? obfuscated : original);
  }
  Map<String, String> map = builder.build();

  return input -> {
    String mapped = map.get(input);
    if (isNullable || mapped != null) {
      return mapped;
    } else {
      return input;
    }
  };
}
 
Example #11
Source File: ActionInputHelper.java    From bazel with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public static ArtifactExpander actionGraphArtifactExpander(ActionGraph actionGraph) {
  return new ArtifactExpander() {
    @Override
    public void expand(Artifact mm, Collection<? super Artifact> output) {
      // Skyframe is stricter in that it checks that "mm" is a input of the action, because
      // it cannot expand arbitrary middlemen without access to a global action graph.
      // We could check this constraint here too, but it seems unnecessary. This code is
      // going away anyway.
      Preconditions.checkArgument(mm.isMiddlemanArtifact(), "%s is not a middleman artifact", mm);
      ActionAnalysisMetadata middlemanAction = actionGraph.getGeneratingAction(mm);
      Preconditions.checkState(middlemanAction != null, mm);
      // TODO(bazel-team): Consider expanding recursively or throwing an exception here.
      // Most likely, this code will cause silent errors if we ever have a middleman that
      // contains a middleman.
      if (middlemanAction.getActionType() == Action.MiddlemanType.AGGREGATING_MIDDLEMAN) {
        Artifact.addNonMiddlemanArtifacts(
            middlemanAction.getInputs().toList(), output, Functions.<Artifact>identity());
      }
    }
  };
}
 
Example #12
Source File: SQLiteArtifactCache.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Unit> store(ArtifactInfo info, BorrowablePath content) {
  if (!getCacheReadMode().isWritable()) {
    return Futures.immediateFuture(null);
  }

  ListenableFuture<Unit> metadataResult = Futures.immediateFuture(null);
  if (!info.getMetadata().isEmpty()) {
    metadataResult = storeMetadata(info);
  }

  ListenableFuture<Unit> contentResult = Futures.immediateFuture(null);
  if (!info.getMetadata().containsKey(TwoLevelArtifactCacheDecorator.METADATA_KEY)) {
    contentResult = storeContent(info.getRuleKeys(), content);
  }

  return Futures.transform(
      Futures.allAsList(metadataResult, contentResult),
      Functions.constant(null),
      MoreExecutors.directExecutor());
}
 
Example #13
Source File: FrequentSequenceMining.java    From sequence-mining with GNU General Public License v3.0 6 votes vote down vote up
/** Read in frequent sequences (sorted by support) */
public static SortedMap<Sequence, Integer> readFrequentSequences(final File output) throws IOException {
	final HashMap<Sequence, Integer> sequences = new HashMap<>();

	final LineIterator it = FileUtils.lineIterator(output);
	while (it.hasNext()) {
		final String line = it.nextLine();
		if (!line.trim().isEmpty()) {
			final String[] splitLine = line.split("#SUP:");
			final String[] items = splitLine[0].trim().split("-1");
			final Sequence seq = new Sequence();
			for (final String item : items)
				seq.add(Integer.parseInt(item.trim()));
			final int supp = Integer.parseInt(splitLine[1].trim());
			sequences.put(seq, supp);
		}
	}
	// Sort sequences by support
	final Ordering<Sequence> comparator = Ordering.natural().reverse().onResultOf(Functions.forMap(sequences))
			.compound(Ordering.usingToString());
	return ImmutableSortedMap.copyOf(sequences, comparator);
}
 
Example #14
Source File: GitDestinationTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testTagWithLabel() throws Exception {
  fetch = "master";
  push = "master";
  tagName = "tag_${my_tag}";
  tagMsg = "msg_${my_msg}";
  Files.write(workdir.resolve("test.txt"), "some content".getBytes());
  options.setForce(true);
  WriterContext writerContext =
      new WriterContext("piper_to_github", "TEST", false, new DummyRevision("test"),
          Glob.ALL_FILES.roots());
  evalDestination().newWriter(writerContext).write(TransformResults.of(
      workdir, new DummyRevision("ref1")), destinationFiles, console);
  options.setForce(false);
  Files.write(workdir.resolve("test.txt"), "some content 2".getBytes());
  evalDestinationWithTag(tagMsg).newWriter(writerContext).write(TransformResults.of(
      workdir, new DummyRevision("ref2")).withLabelFinder(Functions.forMap(
      ImmutableMap.of("my_tag", ImmutableList.of("12345"),
          "my_msg", ImmutableList.of("2345")))), destinationFiles, console);
  CommandOutput commandOutput = repo().simpleCommand("tag", "-n9");
  assertThat(commandOutput.getStdout()).matches(".*tag_12345.*msg_2345\n");
}
 
Example #15
Source File: TestMemoryRevokingScheduler.java    From presto with Apache License 2.0 6 votes vote down vote up
private SqlTask newSqlTask()
{
    TaskId taskId = new TaskId("query", 0, idGeneator.incrementAndGet());
    URI location = URI.create("fake://task/" + taskId);

    return createSqlTask(
            taskId,
            location,
            "fake",
            new QueryContext(new QueryId("query"),
                    DataSize.of(1, MEGABYTE),
                    DataSize.of(2, MEGABYTE),
                    memoryPool,
                    new TestingGcMonitor(),
                    executor,
                    scheduledExecutor,
                    DataSize.of(1, GIGABYTE),
                    spillSpaceTracker),
            sqlTaskExecutionFactory,
            executor,
            Functions.identity(),
            DataSize.of(32, MEGABYTE),
            new CounterStat());
}
 
Example #16
Source File: PathService.java    From jimfs with Apache License 2.0 5 votes vote down vote up
/** Returns the string form of the given path. */
public String toString(JimfsPath path) {
  Name root = path.root();
  String rootString = root == null ? null : root.toString();
  Iterable<String> names = Iterables.transform(path.names(), Functions.toStringFunction());
  return type.toString(rootString, names);
}
 
Example #17
Source File: ElasticsearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Function<? super String, ? extends SpatialContext> createSpatialContextMapper(
		Map<String, String> parameters) {
	// this should really be based on the schema
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	SpatialContext geoContext = SpatialContextFactory.makeSpatialContext(parameters, classLoader);
	return Functions.constant(geoContext);
}
 
Example #18
Source File: RetroFacebookProcessor.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
private static String wildcardTypeParametersString(TypeElement type) {
  List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
  if (typeParameters.isEmpty()) {
    return "";
  } else {
    return "<"
        + Joiner.on(", ").join(
        FluentIterable.from(typeParameters).transform(Functions.constant("?")))
        + ">";
  }
}
 
Example #19
Source File: FluentEqualityConfig.java    From curiostack with MIT License 5 votes vote down vote up
final Builder addUsingCorrespondenceFieldDescriptorsString(
    String fmt, Iterable<FieldDescriptor> fieldDescriptors) {
  return setUsingCorrespondenceStringFunction(
      FieldScopeUtil.concat(
          usingCorrespondenceStringFunction(),
          Functions.constant(String.format(fmt, join(fieldDescriptors)))));
}
 
Example #20
Source File: ElasticSearchRefresh.java    From metacat with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processCatalogs(final List<String> catalogNames) {
    log.info("Start: Full refresh of catalogs: {}", catalogNames);
    final List<ListenableFuture<CatalogDto>> getCatalogFutures = catalogNames.stream()
        .map(catalogName -> service.submit(() -> {
            CatalogDto result = null;
            try {
                result = getCatalog(catalogName);
            } catch (Exception e) {
                log.error("Failed to retrieve catalog: {}", catalogName);
                elasticSearchUtil.log("ElasticSearchRefresh.getCatalog",
                    ElasticSearchDoc.Type.catalog.name(), catalogName, null,
                    e.getMessage(), e, true);
            }
            return result;
        }))
        .collect(Collectors.toList());
    return Futures.transformAsync(Futures.successfulAsList(getCatalogFutures),
        input -> {
            final List<ListenableFuture<Void>> processCatalogFutures = input.stream().filter(NOT_NULL).map(
                catalogDto -> {
                    final List<QualifiedName> databaseNames = getDatabaseNamesToRefresh(catalogDto);
                    return _processDatabases(catalogDto.getName(), databaseNames);
                }).filter(NOT_NULL).collect(Collectors.toList());
            return Futures.transform(Futures.successfulAsList(processCatalogFutures),
                Functions.constant(null), defaultService);
        }, defaultService);
}
 
Example #21
Source File: CatalogTraversal.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Process the list of tables in batches.
 *
 * @param databaseDto database dto
 * @param tableNames   table names
 * @return A future containing the tasks
 */
private ListenableFuture<Void> processTables(final DatabaseDto databaseDto,
                                             final List<QualifiedName> tableNames) {
    final List<List<QualifiedName>> tableNamesBatches = Lists.partition(tableNames, 500);
    final List<ListenableFuture<Void>> processTablesBatchFutures = tableNamesBatches.stream().map(
        subTableNames -> _processTables(databaseDto, subTableNames)).collect(Collectors.toList());

    return Futures.transform(Futures.successfulAsList(processTablesBatchFutures),
        Functions.constant(null), defaultService);
}
 
Example #22
Source File: FunctionSensor.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final EntityLocal entity) {
    super.apply(entity);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding HTTP JSON sensor {} to {}", name, entity);
    }

    final ConfigBag allConfig = ConfigBag.newInstanceCopying(this.params).putAll(params);
    
    final Callable<?> function = EntityInitializers.resolve(allConfig, FUNCTION);
    final Boolean suppressDuplicates = EntityInitializers.resolve(allConfig, SUPPRESS_DUPLICATES);
    final Duration logWarningGraceTimeOnStartup = EntityInitializers.resolve(allConfig, LOG_WARNING_GRACE_TIME_ON_STARTUP);
    final Duration logWarningGraceTime = EntityInitializers.resolve(allConfig, LOG_WARNING_GRACE_TIME);

    FunctionPollConfig<?, T> pollConfig = new FunctionPollConfig<Object, T>(sensor)
            .callable(function)
            .onFailureOrException(Functions.constant((T) null))
            .suppressDuplicates(Boolean.TRUE.equals(suppressDuplicates))
            .logWarningGraceTimeOnStartup(logWarningGraceTimeOnStartup)
            .logWarningGraceTime(logWarningGraceTime)
            .period(period);

    FunctionFeed feed = FunctionFeed.builder().entity(entity)
            .poll(pollConfig)
            .build();

    entity.addFeed(feed);
}
 
Example #23
Source File: SyncData.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
static ImmutableMap<Class<? extends SyncData>, SyncData<?>> extract(
    ProjectData.SyncState syncState) {
  return Arrays.stream(Extractor.EP_NAME.getExtensions())
      .map(extractor -> extractor.extract(syncState))
      .filter(Objects::nonNull)
      .collect(ImmutableMap.toImmutableMap(SyncData::getClass, Functions.identity()));
}
 
Example #24
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected final static <T> HttpPollConfig<T> getSensorFromNodeStat(AttributeSensor<T> sensor, String ...jsonPath) {
    return new HttpPollConfig<T>(sensor)
        .onSuccess(Functionals.chain(GET_THIS_NODE_STATS,
            MaybeFunctions.<JsonElement>wrap(),
            JsonFunctions.walkM(jsonPath),
            JsonFunctions.castM(TypeTokens.getRawRawType(sensor.getTypeToken()), null)))
        .onFailureOrException(Functions.<T>constant(null));
}
 
Example #25
Source File: SequenceMiningCore.java    From sequence-mining with GNU General Public License v3.0 5 votes vote down vote up
/** Sort sequences by interestingness */
public static Map<Sequence, Double> sortSequences(final HashMap<Sequence, Double> sequences,
		final HashMap<Sequence, Double> intMap) {

	final Ordering<Sequence> comparator = Ordering.natural().reverse().onResultOf(Functions.forMap(intMap))
			.compound(Ordering.natural().reverse().onResultOf(Functions.forMap(sequences)))
			.compound(Ordering.usingToString());
	final Map<Sequence, Double> sortedSequences = ImmutableSortedMap.copyOf(sequences, comparator);

	return sortedSequences;
}
 
Example #26
Source File: DynamicSnitchDumper.java    From cassandra-opstools with Apache License 2.0 5 votes vote down vote up
private static Map<InetAddress, Double> sortMap(Map<InetAddress, Double> scores) {
  return ImmutableSortedMap.copyOf(scores, Ordering.natural().onResultOf(Functions.forMap(scores)).compound(new Comparator<InetAddress>() {
        @Override
        public int compare(InetAddress o1, InetAddress o2) {
          return o1.toString().compareTo(o2.toString());
        }

        @Override
        public boolean equals(Object obj) {
          return false;
        }
      }));
}
 
Example #27
Source File: SlaGroup.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
public Multimap<String, IScheduledTask> createNamedGroups(Iterable<IScheduledTask> tasks) {
  return Multimaps.index(tasks, Functions.compose(new Function<IJobKey, String>() {
    @Override
    public String apply(IJobKey jobKey) {
      return "sla_" + JobKeys.canonicalString(jobKey) + "_";
    }
  }, Tasks::getJob));
}
 
Example #28
Source File: IjModuleGraphTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiCellModule() {
  ProjectFilesystem depFileSystem =
      new FakeProjectFilesystem(
          CanonicalCellName.unsafeOf(Optional.of("dep")), Paths.get("dep").toAbsolutePath());
  ProjectFilesystem mainFileSystem =
      new FakeProjectFilesystem(
          CanonicalCellName.unsafeOf(Optional.of("main")), Paths.get("main").toAbsolutePath());

  TargetNode<?> depTargetNode =
      JavaLibraryBuilder.createBuilder(
              BuildTargetFactory.newInstance("dep//java/com/example:dep"), depFileSystem)
          .addSrc(Paths.get("java/com/example/Dep.java"))
          .build();

  TargetNode<?> mainTargetNode =
      JavaLibraryBuilder.createBuilder(
              BuildTargetFactory.newInstance("main//java/com/example:main"), mainFileSystem)
          .addSrc(Paths.get("java/com/example/Main.java"))
          .addDep(depTargetNode.getBuildTarget())
          .build();

  IjModuleGraph moduleGraph =
      createModuleGraph(
          mainFileSystem,
          ImmutableSet.of(depTargetNode, mainTargetNode),
          ImmutableMap.of(),
          Functions.constant(Optional.empty()),
          AggregationMode.NONE,
          true);
  IjModule depModule = getModuleForTarget(moduleGraph, depTargetNode);
  assertEquals(Paths.get("../dep/java/com/example"), depModule.getModuleBasePath());
  assertEquals("___dep_java_com_example", depModule.getName());
}
 
Example #29
Source File: FunctionFeedTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallsOnFailureWithResultOfCallable() throws Exception {
    feed = FunctionFeed.builder()
            .entity(entity)
            .poll(new FunctionPollConfig<Integer, Integer>(SENSOR_INT)
                    .period(1)
                    .callable(Callables.returning(1))
                    .checkSuccess(Predicates.alwaysFalse())
                    .onSuccess(new AddOneFunction())
                    .onFailure(Functions.constant(-1)))
            .build();

    EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_INT, -1);
}
 
Example #30
Source File: CasStatCounter.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
private void logStats() {
	Ordering<String> a = Ordering.natural().reverse().onResultOf(Functions.forMap(counters)).compound(Ordering.natural());
	Map<String, MutableInt> map = ImmutableSortedMap.copyOf(counters, a);
	
	Iterator<Entry<String, MutableInt>> it = map.entrySet().iterator();
	if(it.hasNext()) {// it will be empty if pipeline is run on empty collection
		Entry<String, MutableInt> mostFrequentAnno = it.next();
		LOGGER.info("[{}] {}: {} ", statName, mostFrequentAnno.getKey(), mostFrequentAnno.getValue().intValue());
	}
}