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

The following examples show how to use com.google.common.base.Functions. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: presto   Source File: TestMemoryRevokingScheduler.java    License: 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 2
Source Project: hop   Source File: MemoryGroupByAggregationTest.java    License: 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 3
Source Project: hop   Source File: MemoryGroupByAggregationTest.java    License: 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 4
Source Project: closure-stylesheets   Source File: CssStringNodeTest.java    License: 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 5
Source Project: arcusplatform   Source File: CameraResolver.java    License: 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 6
Source Project: tac-kbp-eal   Source File: KBPEATestUtils.java    License: 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 7
Source Project: buck   Source File: ProguardTranslatorFactory.java    License: 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 8
/** 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 9
Source Project: bazel   Source File: ActionInputHelper.java    License: 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 10
Source Project: brooklyn-library   Source File: HazelcastNodeImpl.java    License: 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 11
Source Project: jenkins-rest   Source File: BaseJenkinsMockTest.java    License: 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 12
Source Project: immutables   Source File: SourceOrdering.java    License: 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 13
Source Project: Elasticsearch   Source File: DDLStatementDispatcher.java    License: 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 14
Source Project: buck   Source File: SQLiteArtifactCache.java    License: 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 15
Source Project: copybara   Source File: GitDestinationTest.java    License: 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 16
Source Project: buck   Source File: IjModuleGraphTest.java    License: 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 17
Source Project: besu   Source File: TestMineBlocks.java    License: Apache License 2.0 5 votes vote down vote up
private boolean mineNewBlock() {
  final RetestethClock retesethClock = context.getRetestethClock();
  final ProtocolSchedule protocolSchedule = context.getProtocolSchedule();
  final ProtocolContext protocolContext = context.getProtocolContext();
  final MutableBlockchain blockchain = context.getBlockchain();
  final HeaderValidationMode headerValidationMode = context.getHeaderValidationMode();
  final EthHashBlockCreator blockCreator =
      new EthHashBlockCreator(
          context.getCoinbase(),
          header -> context.getExtraData(),
          context.getTransactionPool().getPendingTransactions(),
          protocolContext,
          protocolSchedule,
          Functions.identity(),
          context.getEthHashSolver(),
          Wei.ZERO,
          0.0,
          blockchain.getChainHeadHeader());
  final Block block = blockCreator.createBlock(retesethClock.instant().getEpochSecond());

  // advance clock so next mine won't hit the same timestamp
  retesethClock.advanceSeconds(1);

  final BlockImporter blockImporter =
      protocolSchedule.getByBlockNumber(blockchain.getChainHeadBlockNumber()).getBlockImporter();
  return blockImporter.importBlock(
      protocolContext, block, headerValidationMode, headerValidationMode);
}
 
Example 18
Source Project: presto   Source File: TestSqlTask.java    License: Apache License 2.0 5 votes vote down vote up
private SqlTask createInitialTask()
{
    TaskId taskId = new TaskId("query", 0, nextTaskId.incrementAndGet());
    URI location = URI.create("fake://task/" + taskId);

    QueryContext queryContext = new QueryContext(new QueryId("query"),
            DataSize.of(1, MEGABYTE),
            DataSize.of(2, MEGABYTE),
            new MemoryPool(new MemoryPoolId("test"), DataSize.of(1, GIGABYTE)),
            new TestingGcMonitor(),
            taskNotificationExecutor,
            driverYieldExecutor,
            DataSize.of(1, MEGABYTE),
            new SpillSpaceTracker(DataSize.of(1, GIGABYTE)));

    queryContext.addTaskContext(new TaskStateMachine(taskId, taskNotificationExecutor), testSessionBuilder().build(), false, false, OptionalInt.empty());

    return createSqlTask(
            taskId,
            location,
            "fake",
            queryContext,
            sqlTaskExecutionFactory,
            taskNotificationExecutor,
            Functions.identity(),
            DataSize.of(32, MEGABYTE),
            new CounterStat());
}
 
Example 19
@Test
public void testAttributeWhenReadyWithPostProcessing() throws Exception {
    final Task<String> t = submit(DependentConfiguration.valueWhenAttributeReady(entity, TestEntity.SEQUENCE, Functions.toStringFunction()));
    assertNotDoneContinually(t);
    
    entity.sensors().set(TestEntity.SEQUENCE, 1);
    assertEquals(assertDoneEventually(t), "1");
}
 
Example 20
@Test
public void testAttributeWhenReadyWithPostProcessingWithBuilder() throws Exception {
    final Task<String> t = submit(DependentConfiguration.builder()
            .attributeWhenReady(entity, TestEntity.SEQUENCE)
            .postProcess(Functions.toStringFunction())
            .build());

    assertNotDoneContinually(t);
    
    entity.sensors().set(TestEntity.SEQUENCE, 1);
    assertEquals(assertDoneEventually(t), "1");
}
 
Example 21
Source Project: brooklyn-server   Source File: SshFeedTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration") // integration because slow 
public void testSharesCallWhenSameCommand() throws Exception {
    final RecordingSshMachineLocation recordingMachine = mgmt.getLocationManager().createLocation(LocationSpec.create(RecordingSshMachineLocation.class));
    app.start(ImmutableList.of(recordingMachine));
    
    final String cmd = "myCommand";
    
    feed = SshFeed.builder()
            .period(Duration.PRACTICALLY_FOREVER)
            .entity(entity)
            .poll(new SshPollConfig<String>(SENSOR_STRING)
                    .env(ImmutableMap.of("mykey", "myval"))
                    .command(cmd)
                    .onSuccess(Functions.constant("success")))
            .poll(new SshPollConfig<String>(SENSOR_STRING2)
                    .env(ImmutableMap.of("mykey", "myval"))
                    .command(cmd)
                    .onSuccess(Functions.constant("success2")))
            .build();
    
    // Expect it to only execute once (i.e. share exec result for both sensors).
    // Wait several seconds, in case it takes a while to do the second exec.
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            assertEquals(RecordingSshMachineLocation.execScriptCalls, ImmutableList.of(ImmutableList.of(cmd)));
        }});
    Asserts.succeedsContinually(ImmutableMap.of("timeout", Duration.FIVE_SECONDS), new Runnable() {
        @Override
        public void run() {
            assertEquals(RecordingSshMachineLocation.execScriptCalls, ImmutableList.of(ImmutableList.of(cmd)));
        }});
}
 
Example 22
@Override
public void init() {
    super.init();
    
    // By calling feeds().add(...), it will persist the feed, and rebind it
    functionFeed = feeds().add(FunctionFeed.builder()
            .entity(this)
            .period(Duration.millis(10))
            .uniqueTag("MyserviceWithFeeds-functionFeed")
            .poll(new FunctionPollConfig<Integer, Integer>(COUNTER)
                    .suppressDuplicates(true)
                    .onException(Functions.constant(-1))
                    .callable(new Callable<Integer>() {
                        @Override
                        public Integer call() {
                            if (!Entities.isManaged(MyServiceWithFeedsImpl.this)) {
                                feedCalledWhenNotManaged = true;
                                throw new IllegalStateException("Entity "+MyServiceWithFeedsImpl.this+" is not managed in feed.call");
                            }
                            Integer oldVal = sensors().get(COUNTER);
                            return (oldVal == null ? 0 : oldVal) + 1;
                        }
                    }))
            .build());
    
    subscribeToServiceState();
}
 
Example 23
Source Project: buck   Source File: PluginBasedCommandHelpPrinter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Prints the text with usage information for the given command to the provided stream.
 *
 * <p>This method divides command options into multiple categories: global options (common to all
 * commands), common options for this command and options for every plugin-based subcommand.
 */
public void printUsage(PluginBasedCommand command, PrintStream stream) {
  printShortDescription(command, stream);
  CmdLineParserWithPrintInformation parser = new CmdLineParserWithPrintInformation(command);
  ImmutableSortedMap<PluginBasedSubCommand, CmdLineParserWithPrintInformation> subCommands =
      command.getSubCommands().stream()
          .collect(
              ImmutableSortedMap.toImmutableSortedMap(
                  Comparator.comparing(PluginBasedSubCommand::getOptionValue),
                  Functions.identity(),
                  CmdLineParserWithPrintInformation::new));

  int len = calculateTotalMaxLen(parser, subCommands.values());

  OutputStreamWriter writer = new OutputStreamWriter(stream);

  printGlobalOptionsUsage(stream, writer, parser, len);
  printCommonOptionsUsage(stream, writer, parser, len);

  for (Map.Entry<PluginBasedSubCommand, CmdLineParserWithPrintInformation> subCommand :
      subCommands.entrySet()) {
    printSubCommandUsage(
        stream,
        writer,
        subCommand.getKey(),
        subCommand.getValue(),
        command.getTypeOptionName(),
        len);
  }

  stream.println();
}
 
Example 24
Source Project: buck   Source File: BuckQueryEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<ListenableFuture<Unit>> discoverNewTargetsConcurrently(
    BuildTarget buildTarget,
    DependencyStack dependencyStack,
    ConcurrentHashMap<BuildTarget, ListenableFuture<Unit>> jobsCache)
    throws BuildFileParseException {
  ListenableFuture<Unit> job = jobsCache.get(buildTarget);
  if (job != null) {
    return Optional.empty();
  }
  SettableFuture<Unit> newJob = SettableFuture.create();
  if (jobsCache.putIfAbsent(buildTarget, newJob) != null) {
    return Optional.empty();
  }

  ListenableFuture<Unit> future =
      Futures.transformAsync(
          parser.getTargetNodeJobAssertCompatible(parserState, buildTarget, dependencyStack),
          targetNode -> {
            targetsToNodes.put(buildTarget, targetNode);
            checker.addTarget(buildTarget, dependencyStack);
            List<ListenableFuture<Unit>> depsFuture = new ArrayList<>();
            Set<BuildTarget> parseDeps = targetNode.getParseDeps();
            for (BuildTarget parseDep : parseDeps) {
              discoverNewTargetsConcurrently(parseDep, dependencyStack.child(parseDep), jobsCache)
                  .ifPresent(
                      depWork ->
                          depsFuture.add(
                              attachParentNodeToErrorMessage(buildTarget, parseDep, depWork)));
            }
            return Futures.transform(
                Futures.allAsList(depsFuture),
                Functions.constant(null),
                MoreExecutors.directExecutor());
          });
  newJob.setFuture(future);
  return Optional.of(newJob);
}
 
Example 25
Source Project: brooklyn-server   Source File: BrooklynTaskTags.java    License: Apache License 2.0 5 votes vote down vote up
/** creates a tag suitable for marking a stream available on a task, but which might be GC'd */
// TODO only make it soft if/when stream exceeds a given size eg 1kb ?
public static WrappedStream tagForStreamSoft(String streamType, ByteArrayOutputStream stream) {
    MemoryUsageTracker.SOFT_REFERENCES.track(stream, stream.size());
    Maybe<ByteArrayOutputStream> softStream = Maybe.softThen(stream, STREAM_GARBAGE_COLLECTED_MAYBE);
    return new WrappedStream(streamType,
        Suppliers.compose(Functions.toStringFunction(), softStream),
        Suppliers.compose(Streams.sizeFunction(), softStream));
}
 
Example 26
Source Project: attic-aurora   Source File: PairTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractors() {
  Function<Pair<Pair<String, Integer>, Character>, Pair<String, Integer>> first = Pair.first();
  Function<Pair<String, Integer>, Integer> second = Pair.second();
  assertEquals(Integer.valueOf(42),
      Functions.compose(second, first).apply(Pair.of(Pair.of("arthur", 42), 'z')));
}
 
Example 27
Source Project: sonar-esql-plugin   Source File: PathClauseTreeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Tree> childrenIterator() {
	return Iterators.concat(
			Iterators.singletonIterator(pathToken), 
			schemaNames.elementsAndSeparators(Functions.<SchemaNameTree>identity())
	);
}
 
Example 28
Source Project: auto   Source File: FactoryDescriptorGenerator.java    License: Apache License 2.0 5 votes vote down vote up
FactoryMethodDescriptor generateDescriptorForConstructor(final AutoFactoryDeclaration declaration,
    ExecutableElement constructor) {
  checkNotNull(constructor);
  checkArgument(constructor.getKind() == ElementKind.CONSTRUCTOR);
  TypeElement classElement = MoreElements.asType(constructor.getEnclosingElement());
  ImmutableListMultimap<Boolean, ? extends VariableElement> parameterMap =
      Multimaps.index(constructor.getParameters(), Functions.forPredicate(
          new Predicate<VariableElement>() {
            @Override
            public boolean apply(VariableElement parameter) {
              return isAnnotationPresent(parameter, Provided.class);
            }
          }));
  ImmutableSet<Parameter> providedParameters =
      Parameter.forParameterList(parameterMap.get(true), types);
  ImmutableSet<Parameter> passedParameters =
      Parameter.forParameterList(parameterMap.get(false), types);
  return FactoryMethodDescriptor.builder(declaration)
      .name("create")
      .returnType(classElement.asType())
      .publicMethod(classElement.getModifiers().contains(PUBLIC))
      .providedParameters(providedParameters)
      .passedParameters(passedParameters)
      .creationParameters(Parameter.forParameterList(constructor.getParameters(), types))
      .isVarArgs(constructor.isVarArgs())
      .build();
}
 
Example 29
Source Project: ZjDroid   Source File: BuilderClassDef.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull @Override
public Set<String> getInterfaces() {
    return new AbstractSet<String>() {
        @Nonnull @Override public Iterator<String> iterator() {
            return Iterators.transform(interfaces.iterator(), Functions.toStringFunction());
        }

        @Override public int size() {
            return interfaces.size();
        }
    };
}
 
Example 30
Source Project: arcusplatform   Source File: MethodInvokerFactory.java    License: Apache License 2.0 5 votes vote down vote up
public Function<I, R> wrapWithThis(Method method, Object ths) {
   Preconditions.checkNotNull(method, "method may not be null");
   return wrapWithThisProvider(
         method, 
         Functions.constant(ths)
   );
}