dagger.producers.Produces Java Examples

The following examples show how to use dagger.producers.Produces. 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: ScrapeLocationsGraph.java    From curiostack with MIT License 7 votes vote down vote up
@Produces
@FetchedPostPage
static ListenableFuture<List<@Nullable AggregatedHttpResponse>> fetchPosts(
    @HashtagPage List<@Nullable AggregatedHttpResponse> hashtagPages,
    SharedDataExtractor sharedDataExtractor,
    WebClient instagramClient,
    ServiceRequestContext ctx) {
  return Futures.successfulAsList(
      hashtagPages.stream()
          .filter(Objects::nonNull)
          .map(page -> sharedDataExtractor.extractSharedData(page, TagPage.class))
          .flatMap(
              page ->
                  page
                      .getEntryData()
                      .getTagPage()
                      .get(0)
                      .getGraphql()
                      .getHashtag()
                      .getPosts()
                      .getEdges()
                      .stream())
          .map(
              post ->
                  toListenableFuture(
                      instagramClient
                          .get("/p/" + post.getNode().getShortcode() + '/')
                          .aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc())))
          .collect(toImmutableList()));
}
 
Example #2
Source File: ListLandmarksGraph.java    From curiostack with MIT License 6 votes vote down vote up
@Produces
static ListenableFuture<List<List<Landmark>>> fetchDbLandmarks(
    S2CellUnion coveredCells, DSLContext db, @ForDatabase ListeningExecutorService dbExecutor) {
  return Futures.successfulAsList(
      Streams.stream(coveredCells)
          .map(
              cell ->
                  dbExecutor.submit(
                      () ->
                          db.selectFrom(LANDMARK)
                              .where(
                                  LANDMARK
                                      .S2_CELL
                                      .ge(ULong.valueOf(cell.rangeMin().id()))
                                      .and(
                                          LANDMARK.S2_CELL.le(
                                              ULong.valueOf(cell.rangeMax().id()))))
                              .fetchInto(Landmark.class)))
          .collect(toImmutableList()));
}
 
Example #3
Source File: GetPlacesGraph.java    From curiostack with MIT License 6 votes vote down vote up
@Produces
static ListenableFuture<List<Place>> fetchPlaces(
    S2LatLngRect viewport, DSLContext db, @ForDatabase ListeningExecutorService dbExecutor) {
  var coverer = new S2RegionCoverer();
  var coveredCells = coverer.getCovering(viewport);

  Condition locationCondition =
      DSL.or(
          Streams.stream(coveredCells)
              .map(
                  cell ->
                      PLACE
                          .S2_CELL
                          .ge(ULong.valueOf(cell.rangeMin().id()))
                          .and(PLACE.S2_CELL.le(ULong.valueOf(cell.rangeMax().id()))))
              .collect(toImmutableList()));

  return dbExecutor.submit(
      () -> db.selectFrom(PLACE).where(DSL.or(locationCondition)).fetchInto(Place.class));
}
 
Example #4
Source File: ProductionBinding.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
ProductionBinding forImplicitMapBinding(DependencyRequest explicitRequest,
    DependencyRequest implicitRequest) {
  checkNotNull(explicitRequest);
  checkNotNull(implicitRequest);
  ImmutableSet<DependencyRequest> dependencies = ImmutableSet.of(implicitRequest);
  return new AutoValue_ProductionBinding(
      explicitRequest.key(),
      implicitRequest.requestElement(),
      dependencies,
      findBindingPackage(explicitRequest.key()),
      false,
      Optional.<DeclaredType>absent(),
      Optional.<TypeElement>absent(),
      Kind.SYNTHETIC_PRODUCTION,
      Produces.Type.MAP,
      ImmutableList.<TypeMirror>of());
}
 
Example #5
Source File: ProductionBinding.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
ProductionBinding forComponentMethod(ExecutableElement componentMethod) {
  checkNotNull(componentMethod);
  checkArgument(componentMethod.getKind().equals(METHOD));
  checkArgument(componentMethod.getParameters().isEmpty());
  checkArgument(MoreTypes.isTypeOf(ListenableFuture.class, componentMethod.getReturnType()));
  return new AutoValue_ProductionBinding(
      keyFactory.forProductionComponentMethod(componentMethod),
      componentMethod,
      ImmutableSet.<DependencyRequest>of(),
      Optional.<String>absent(),
      false,
      Optional.<DeclaredType>absent(),
      Optional.<TypeElement>absent(),
      Kind.COMPONENT_PRODUCTION,
      Produces.Type.UNIQUE,
      ImmutableList.copyOf(componentMethod.getThrownTypes()));
}
 
Example #6
Source File: ProducerFactoryGenerator.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Snippet for the invocation of the producer method from the module.
 *
 * @param wrapWithFuture If true, wraps the result of the call to the producer method
 *        in an immediate future.
 * @param binding The binding to generate the invocation snippet for.
 * @param parameterSnippets The snippets for all the parameters to the producer method.
 */
private Snippet getInvocationSnippet(boolean wrapWithFuture, ProductionBinding binding,
    ImmutableList<Snippet> parameterSnippets) {
  Snippet moduleSnippet = Snippet.format("module.%s(%s)",
      binding.bindingElement().getSimpleName(),
      makeParametersSnippet(parameterSnippets));
  if (wrapWithFuture) {
    moduleSnippet = Snippet.format("%s.immediateFuture(%s)",
        ClassName.fromClass(Futures.class),
        moduleSnippet);
  }
  if (binding.productionType().equals(Produces.Type.SET)) {
    if (binding.bindingKind().equals(ProductionBinding.Kind.FUTURE_PRODUCTION)) {
      return Snippet.format("%s.createFutureSingletonSet(%s)",
          ClassName.fromClass(Producers.class),
          moduleSnippet);
    } else {
      return Snippet.format("%s.of(%s)",
          ClassName.fromClass(ImmutableSet.class),
          moduleSnippet);
    }
  } else {
    return moduleSnippet;
  }
}
 
Example #7
Source File: MainGraph.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Produces
static ListenableFuture<List<Long>> fetchFromFakeDb(ServiceRequestContext context,
                                                    ListeningScheduledExecutorService blockingExecutor) {
    // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
    checkState(ServiceRequestContext.current() == context);
    checkState(context.eventLoop().inEventLoop());
    // This logic mimics using a blocking method, which would usually be something like a MySQL database
    // query using JDBC.
    // Always run blocking logic on the blocking task executor. By using
    // ServiceRequestContext.blockingTaskExecutor (indirectly via the ListeningScheduledExecutorService
    // wrapper we defined in MainModule), you also ensure the context is mounted inside the logic (e.g.,
    // your DB call will be traced!).
    return blockingExecutor.submit(() -> {
        // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
        checkState(ServiceRequestContext.current() == context);
        checkState(!context.eventLoop().inEventLoop());

        Uninterruptibles.sleepUninterruptibly(Duration.ofMillis(50));
        return ImmutableList.of(23L, -23L);
    });
}
 
Example #8
Source File: MainGraph.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Produces
static ListenableFuture<List<AggregatedHttpResponse>> fetchFromBackend(
        AggregatedHttpRequest request, List<Long> dbNums, WebClient backendClient,
        ServiceRequestContext context) {
    // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
    checkState(ServiceRequestContext.current() == context);
    checkState(context.eventLoop().inEventLoop());

    final Stream.Builder<Long> nums = Stream.builder();
    for (String token : Iterables.concat(
            NUM_SPLITTER.split(request.path().substring(1)),
            NUM_SPLITTER.split(request.contentUtf8()))) {
        nums.add(Long.parseLong(token));
    }
    dbNums.forEach(nums::add);

    return Futures.allAsList(
            nums.build()
                .map(num -> toListenableFuture(backendClient.get("/square/" + num).aggregate()))
            .collect(toImmutableList()));
}
 
Example #9
Source File: ScrapeLocationsGraph.java    From curiostack with MIT License 6 votes vote down vote up
@Produces
@UserPage
static ListenableFuture<List<@Nullable AggregatedHttpResponse>> fetchUserPages(
    ScrapeLocationsRequest request, WebClient instagramClient, ServiceRequestContext ctx) {
  return Futures.successfulAsList(
      request.getUsernameList().stream()
          .map(
              username ->
                  toListenableFuture(
                      instagramClient
                          .get('/' + username + '/')
                          .aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc())))
          .collect(toImmutableList()));
}
 
Example #10
Source File: MainGraph.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Produces
static ListenableFuture<AggregatedHttpRequest> aggregateRequest(
        HttpRequest request, ServiceRequestContext context) {
    // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
    checkState(ServiceRequestContext.current() == context);
    checkState(context.eventLoop().inEventLoop());
    return toListenableFuture(request.aggregate());
}
 
Example #11
Source File: ScrapeLocationsGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
@HashtagPage
static ListenableFuture<List<@Nullable AggregatedHttpResponse>> fetchHashtags(
    ScrapeLocationsRequest request, WebClient instagramClient, ServiceRequestContext ctx) {
  return Futures.successfulAsList(
      request.getHashtagList().stream()
          .map(
              hashtag ->
                  toListenableFuture(
                      instagramClient
                          .get("/explore/tags/" + hashtag + '/')
                          .aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc())))
          .collect(toImmutableList()));
}
 
Example #12
Source File: ProductionBinding.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
ProductionBinding forProducesMethod(
    ExecutableElement producesMethod, TypeMirror contributedBy) {
  checkNotNull(producesMethod);
  checkArgument(producesMethod.getKind().equals(METHOD));
  checkArgument(contributedBy.getKind().equals(TypeKind.DECLARED));
  Produces producesAnnotation = producesMethod.getAnnotation(Produces.class);
  checkArgument(producesAnnotation != null);
  DeclaredType declaredContainer = MoreTypes.asDeclared(contributedBy);
  ExecutableType resolvedMethod =
      MoreTypes.asExecutable(types.asMemberOf(declaredContainer, producesMethod));
  Key key = keyFactory.forProducesMethod(resolvedMethod, producesMethod);
  ImmutableSet<DependencyRequest> dependencies =
      dependencyRequestFactory.forRequiredResolvedVariables(
          declaredContainer,
          producesMethod.getParameters(),
          resolvedMethod.getParameterTypes());
  Kind kind = MoreTypes.isTypeOf(ListenableFuture.class, producesMethod.getReturnType())
      ? Kind.FUTURE_PRODUCTION
      : Kind.IMMEDIATE;
  return new AutoValue_ProductionBinding(
      key,
      producesMethod,
      dependencies,
      findBindingPackage(key),
      false,
      ConfigurationAnnotations.getNullableType(producesMethod),
      Optional.of(MoreTypes.asTypeElement(declaredContainer)),
      kind,
      producesAnnotation.type(),
      ImmutableList.copyOf(producesMethod.getThrownTypes()));
}
 
Example #13
Source File: CheckIngredientsGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static CheckIngredientsResponse response(SearchResponse searchResponse) {
  List<Ingredient> availableIngredients =
      searchResponse.facetCounts().ingredient().entrySet().stream()
          .filter(e -> SUPPORTED_INGREDIENTS.contains(e.getKey()) && e.getValue() > 0)
          .map(e -> IngredientConverter.REVERSE.convert(e.getKey()))
          .collect(toImmutableList());
  return CheckIngredientsResponse.newBuilder()
      .addAllSelectableIngredient(availableIngredients)
      .build();
}
 
Example #14
Source File: CheckIngredientsGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static ListenableFuture<SearchResponse> doSearch(
    CheckIngredientsRequest request, YummlyApi yummly) {
  List<String> ingredients =
      ImmutableList.<String>builder()
          .addAll(IngredientConverter.FORWARD.convertAll(request.getSelectedIngredientList()))
          .add(EggworldConstants.EGGS_INGREDIENT)
          .build();
  return yummly.search(EggworldConstants.EGG_QUERY, ingredients, 0, 1, true, INGREDIENT_FACET);
}
 
Example #15
Source File: FindRecipeGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static ListenableFuture<Recipe> recipe(
    List<String> ingredients,
    SearchResponse searchResponse,
    Supplier<Random> randomSupplier,
    YummlyApi yummly) {
  int totalCount = searchResponse.totalMatchCount();

  ListenableFuture<SearchResponse> future = Futures.immediateFuture(null);
  // Get a random recipe to return. Search request fails randomly so try a few times.
  Executor executor = RequestContext.current().contextAwareEventLoop();
  Random random = randomSupplier.get();
  for (int i = 0; i < 5; i++) {
    int resultIndex = random.nextInt(totalCount);
    future =
        Futures.transformAsync(
            future,
            result -> {
              if (result != null && !result.matches().isEmpty()) {
                return Futures.immediateFuture(result);
              }
              return yummly.search(
                  EggworldConstants.EGG_QUERY,
                  ingredients,
                  resultIndex,
                  1,
                  true,
                  ImmutableList.of());
            },
            executor);
  }

  return Futures.transform(future, r -> r.matches().get(0), MoreExecutors.directExecutor());
}
 
Example #16
Source File: FindRecipeGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static List<String> ingredients(FindRecipeRequest request) {
  return ImmutableList.<String>builder()
      .addAll(IngredientConverter.FORWARD.convertAll(request.getIngredientList()))
      .add(EggworldConstants.EGGS_INGREDIENT)
      .build();
}
 
Example #17
Source File: GetPlacesGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static GetPlacesResponse response(List<Place> places, S2LatLngRect viewport) {
  return GetPlacesResponse.newBuilder()
      .addAllPlace(
          places.stream()
                  .filter(
                      place ->
                          !Strings.isNullOrEmpty(place.getGooglePlaceId())
                              && viewport.contains(
                                  S2LatLng.fromDegrees(
                                      place.getLatitude(), place.getLongitude())))
                  .map(PlaceUtil::convertPlace)
              ::iterator)
      .build();
}
 
Example #18
Source File: MainGraph.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Produces
static HttpResponse buildResponse(List<AggregatedHttpResponse> backendResponse,
                                  ServiceRequestContext context) {
    // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
    checkState(ServiceRequestContext.current() == context);
    checkState(context.eventLoop().inEventLoop());
    return HttpResponse.of(backendResponse.stream()
                                          .map(AggregatedHttpResponse::contentUtf8)
                                          .collect(Collectors.joining("\n")));
}
 
Example #19
Source File: ScrapeLocationsGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
@LocationPage
static ListenableFuture<List<@Nullable AggregatedHttpResponse>> fetchLocations(
    @FetchedPostPage List<@Nullable AggregatedHttpResponse> postPages,
    @UserPage List<@Nullable AggregatedHttpResponse> userPages,
    WebClient instagramClient,
    SharedDataExtractor sharedDataExtractor,
    ServiceRequestContext ctx) {
  return Futures.successfulAsList(
      Stream.concat(
              userPages.stream()
                  .filter(Objects::nonNull)
                  .map(page -> sharedDataExtractor.extractSharedData(page, ProfilePage.class))
                  .flatMap(ScrapeLocationsGraph::getLocationPageIds),
              postPages.stream()
                  .filter(Objects::nonNull)
                  .map(page -> sharedDataExtractor.extractSharedData(page, PostPage.class))
                  .map(ScrapeLocationsGraph::getLocationPageId)
                  .filter(s -> !s.isEmpty()))
          .distinct()
          .map(
              locationId ->
                  toListenableFuture(
                      instagramClient
                          .get("/explore/locations/" + locationId + '/')
                          .aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc())))
          .collect(toImmutableList()));
}
 
Example #20
Source File: ScrapeLocationsGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static ScrapeLocationsResponse buildResponse(
    @LocationPage List<@Nullable AggregatedHttpResponse> locationPages,
    SharedDataExtractor sharedDataExtractor) {
  return ScrapeLocationsResponse.newBuilder()
      .addAllLocation(
          locationPages.stream()
                  .filter(response -> response != null && response.status().equals(HttpStatus.OK))
                  .map(page -> sharedDataExtractor.extractSharedData(page, LocationsPage.class))
                  .map(ScrapeLocationsGraph::convertLocationPage)
              ::iterator)
      .build();
}
 
Example #21
Source File: GetPlaceGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static ListenableFuture<Place> fetchPlace(
    GetPlaceRequest request,
    DSLContext cafemapDb,
    @ForDatabase ListeningExecutorService dbExecutor) {
  return dbExecutor.submit(
      () ->
          cafemapDb
              .selectFrom(PLACE)
              .where(PLACE.ID.eq(ULong.valueOf(request.getId())))
              .fetchOneInto(Place.class));
}
 
Example #22
Source File: ListLandmarksGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static ListLandmarksResponse createResponse(
    List<List<Landmark>> oldLandmarks, List<Landmark> newLandmarks) {
  ListLandmarksResponse.Builder response = ListLandmarksResponse.newBuilder();

  response.addAllLandmark(
      Stream.concat(oldLandmarks.stream().flatMap(List::stream), newLandmarks.stream())
              .map(ListLandmarksGraph::convertLandmark)
          ::iterator);

  return response.build();
}
 
Example #23
Source File: ListLandmarksGraph.java    From curiostack with MIT License 5 votes vote down vote up
@Produces
static ListenableFuture<List<Landmark>> writeNewLandmarksToDb(
    PlacesSearchResponse searchResponse,
    List<List<Landmark>> dbLandmarks,
    DSLContext cafemapdb,
    @ForDatabase ListeningExecutorService dbExecutor) {
  if (searchResponse.results.length == 0) {
    return immediateFuture(ImmutableList.of());
  }

  Set<String> dbPlaceIds =
      dbLandmarks.stream()
          .flatMap(List::stream)
          .map(Landmark::getGooglePlaceId)
          .collect(toImmutableSet());

  List<LandmarkRecord> newLandmarks =
      Arrays.stream(searchResponse.results)
          .filter(result -> !dbPlaceIds.contains(result.placeId))
          .map(
              result ->
                  new LandmarkRecord()
                      .setGooglePlaceId(result.placeId)
                      .setType("park")
                      .setS2Cell(
                          ULong.valueOf(
                              S2CellId.fromLatLng(
                                      S2Util.convertFromLatLng(result.geometry.location))
                                  .id())))
          .collect(toImmutableList());

  return dbExecutor.submit(
      () -> {
        int[] numInserted = cafemapdb.batchStore(newLandmarks).execute();
        return newLandmarks.stream().map(Landmark::new).collect(toImmutableList());
      });
}
 
Example #24
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces ListenableFuture<String> produceFutureString() {
  return null;
}
 
Example #25
Source File: MultibindingProducerModule.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces(type = SET) ListenableFuture<String> futureStr() {
  return Futures.immediateFuture("foo");
}
 
Example #26
Source File: MultibindingProducerModule.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces(type = SET) String str() {
  return "bar";
}
 
Example #27
Source File: MultibindingProducerModule.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces(type = SET_VALUES) ListenableFuture<Set<String>> futureStrs() {
  return Futures.<Set<String>>immediateFuture(ImmutableSet.of("foo1", "foo2"));
}
 
Example #28
Source File: MultibindingProducerModule.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces(type = SET_VALUES) Set<String> strs() {
  return ImmutableSet.of("bar1", "bar2");
}
 
Example #29
Source File: MultibindingProducerModule.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces int strCount(Set<String> strs) {
  return strs.size();
}
 
Example #30
Source File: SimpleProducerModule.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
@Produces ListenableFuture<String> str() {
  return Futures.immediateFuture("Hello, World!");
}