Java Code Examples for java.util.Optional#isPresent()

The following examples show how to use java.util.Optional#isPresent() . 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: BuildGraphTest.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private TargetInfo injectTargetInfo(
  Map<String, TargetInfo> targets,
  String targetAddress,
  String targetType,
  boolean is_target_root,
  Optional<String> dependee
) {
  TargetInfo source = TargetInfoTest.createTargetInfoWithTargetAddressInfo(targetType);
  source.getAddressInfos().forEach(s -> s.setIsTargetRoot(is_target_root));

  //getTarget here is actually getting dependencies :/
  if (dependee.isPresent()) {
    targets.entrySet().forEach(s -> {
      if (s.getKey().equals(dependee.get())) {
        s.getValue().addDependency(targetAddress);
      }
    });
  }

  targets.put(targetAddress, source);
  return source;
}
 
Example 2
Source File: FeignPageableEncodingTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
public void testPageable() {

	// given
	Pageable pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "sortProperty");

	// when
	final ResponseEntity<Page<Invoice>> response = this.invoiceClient
			.getInvoicesPaged(pageable);

	// then
	assertThat(response).isNotNull();
	assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
	assertThat(response.getBody()).isNotNull();
	assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
	assertThat(response.getBody().getPageable().getSort()).hasSize(1);
	Optional<Sort.Order> optionalOrder = response.getBody().getPageable().getSort()
			.get().findFirst();
	if (optionalOrder.isPresent()) {
		Sort.Order order = optionalOrder.get();
		assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC);
		assertThat(order.getProperty()).isEqualTo("sortProperty");
	}

}
 
Example 3
Source File: MultiPlansResource.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * @see PlansQueries
 */
@POST
@Path("{sanitizedServiceName}/plans/{planName}/forceComplete")
public Response forceComplete(
    @PathParam("sanitizedServiceName") String sanitizedServiceName,
    @PathParam("planName") String planName,
    @QueryParam("phase") String phase,
    @QueryParam("step") String step)
{
  Optional<PlanCoordinator> planCoordinator = getPlanCoordinator(sanitizedServiceName);
  if (!planCoordinator.isPresent()) {
    return ResponseUtils.serviceNotFoundResponse(sanitizedServiceName);
  }
  return PlansQueries.forceComplete(
      planCoordinator.get().getPlanManagers(),
      planName,
      phase,
      step);
}
 
Example 4
Source File: AuthenticationApiAction.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
private void addSAMLMetadata(FieldModel fieldModel) {
    try {
        boolean samlEnabled = fieldModel.getFieldValueModel(AuthenticationDescriptor.KEY_SAML_ENABLED)
                                  .flatMap(FieldValueModel::getValue)
                                  .map(BooleanUtils::toBoolean)
                                  .orElse(false);
        Optional<FieldValueModel> metadataURLFieldValueOptional = fieldModel.getFieldValueModel(AuthenticationDescriptor.KEY_SAML_METADATA_URL);
        Optional<FieldValueModel> metadataEntityFieldValueOptional = fieldModel.getFieldValueModel(AuthenticationDescriptor.KEY_SAML_ENTITY_ID);
        Optional<FieldValueModel> metadataBaseURLFieldValueOptional = fieldModel.getFieldValueModel(AuthenticationDescriptor.KEY_SAML_ENTITY_BASE_URL);
        if (metadataEntityFieldValueOptional.isPresent() && metadataBaseURLFieldValueOptional.isPresent()) {
            FieldValueModel metadataEntityFieldValue = metadataEntityFieldValueOptional.get();
            FieldValueModel metadataBaseUrValueModel = metadataBaseURLFieldValueOptional.get();
            String metadataURL = metadataURLFieldValueOptional.flatMap(FieldValueModel::getValue).orElse("");
            String entityId = metadataEntityFieldValue.getValue().orElse("");
            String baseUrl = metadataBaseUrValueModel.getValue().orElse("");
            samlManager.updateSAMLConfiguration(samlEnabled, metadataURL, entityId, baseUrl);
        }
    } catch (Exception ex) {
        logger.error("Error adding SAML settings", ex);
    }
}
 
Example 5
Source File: File.java    From salt-netapi-client with MIT License 6 votes vote down vote up
private static LocalCall<String> mkdir(String path, Optional<String> user,
        Optional<String> group, Optional<String> mode) {
    Map<String, Object> args = new LinkedHashMap<>();
    args.put("dir_path", path);
    if (user.isPresent()) {
        args.put("user", user.get());
    }
    if (group.isPresent()) {
        args.put("group", group.get());
    }
    if (mode.isPresent()) {
        args.put("mode", mode.get());
    }
    return new LocalCall<>("file.mkdir", Optional.empty(), Optional.of(args),
            new TypeToken<String>(){});
}
 
Example 6
Source File: SeleniumExtension.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
public Optional<String> getContainerId(WebDriver driver) {
    try {
        for (Map.Entry<String, Map<String, DockerContainer>> entry : containersMap
                .entrySet()) {
            DockerContainer selenoidContainer = containersMap
                    .get(entry.getKey()).values().iterator().next();
            URL selenoidUrl = new URL(selenoidContainer.getContainerUrl());
            URL selenoidBaseUrl = new URL(selenoidUrl.getProtocol(),
                    selenoidUrl.getHost(), selenoidUrl.getPort(), "/");

            SelenoidService selenoidService = new SelenoidService(
                    selenoidBaseUrl.toString());
            Optional<String> containerId = selenoidService
                    .getContainerId(driver);

            if (containerId.isPresent()) {
                return containerId;
            }
        }
        return empty();

    } catch (Exception e) {
        throw new SeleniumJupiterException(e);
    }
}
 
Example 7
Source File: UserServiceImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public User authenticate(final String username, final String password) {
    Optional<User> user = USERS.values().stream().
            filter(meta -> !meta.isDeleted() && username.equals(meta.getUser().getUsername())).
            findFirst().map(UserMetadata::getUser);

    if (!user.isPresent()) {
        throw new NotFoundException(username);
    }
    if (!password.equals(user.get().getPassword())) {
        throw new ForbiddenException();
    }

    return user.get();
}
 
Example 8
Source File: WorkerService.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public Worker getWorkerById(String jobId, Long workerId) {
  WorkerId workerIdObj = new WorkerId();
  workerIdObj.setJob(jobId);
  workerIdObj.setWorkerID(workerId);

  Optional<Worker> byId = this.workerRepository.findById(workerIdObj);
  if (byId.isPresent()) {
    return byId.get();
  } else {
    throwNoSuchWorker(jobId, workerId);
    return null;
  }
}
 
Example 9
Source File: BookDatabaseServiceUtils.java    From vertx-postgresql-starter with MIT License 5 votes vote down vote up
public static DynamicQuery generateDynamicQuery(String rawSql, Book book) {
  Optional<String> title = Optional.ofNullable(book.getTitle());
  Optional<String> category = Optional.ofNullable(book.getCategory());
  Optional<String> publicationDate = Optional.ofNullable(book.getPublicationDate());

  // Concat the SQL by conditions
  int count = 0;
  String dynamicSql = rawSql;
  Tuple params = Tuple.tuple();
  if (title.isPresent()) {
    count++;
    dynamicSql += SQL_FIND_BOOKS_CONDITION_BY_TITLE;
    dynamicSql += count;
    params.addString(title.get());
  }
  if (category.isPresent()) {
    count++;
    dynamicSql += SQL_FIND_BOOKS_CONDITION_BY_CATEGORY;
    dynamicSql += count;
    params.addString(category.get());
  }
  if (publicationDate.isPresent()) {
    count++;
    dynamicSql += SQL_FIND_BOOKS_CONDITION_BY_PUBLICATION_DATE;
    dynamicSql += count;
    params.addValue(publicationDate.get());
  }
  return new DynamicQuery(dynamicSql, params);
}
 
Example 10
Source File: UserModuleImpl.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private void start() {
    UserOptions.DefaultAdminUser defaultAdminUser = require(UserOptions.class).defaultAdminUser;
    if (defaultAdminUser != null) {
        UserWebService userWebService = require(UserWebService.class);
        UserGroupWebService userGroupWebService = require(UserGroupWebService.class);

        Optional<UserGroupResponse> userGroupResponseOptional = userGroupWebService.findByName("admin");
        UserGroupResponse userGroupResponse;
        if (!userGroupResponseOptional.isPresent()) {
            CreateUserGroupRequest createUserGroupRequest = new CreateUserGroupRequest();
            createUserGroupRequest.name = "admin";
            createUserGroupRequest.displayName = "admin";
            createUserGroupRequest.roles = Lists.newArrayList("*");
            createUserGroupRequest.status = UserGroupStatus.ACTIVE;
            userGroupResponse = userGroupWebService.create(createUserGroupRequest);
        } else {
            userGroupResponse = userGroupResponseOptional.get();
        }

        UserQuery query = new UserQuery();
        query.page = 0;
        query.limit = 0;
        if (userWebService.find(query).total == 0) {
            logger.info("create default admin user, username={}", defaultAdminUser.username);

            CreateUserRequest createUserRequest = new CreateUserRequest();
            createUserRequest.username = defaultAdminUser.username;
            createUserRequest.email = defaultAdminUser.email;
            createUserRequest.phone = defaultAdminUser.phone;
            createUserRequest.password = defaultAdminUser.password;
            createUserRequest.description = defaultAdminUser.description;
            createUserRequest.language = app().language();
            createUserRequest.status = UserStatus.ACTIVE;
            createUserRequest.userGroupIds = Lists.newArrayList(userGroupResponse.id);
            userWebService.create(createUserRequest);
        }
    }
}
 
Example 11
Source File: VirtualNetworkDeviceManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Port getPort(DeviceId deviceId, PortNumber portNumber) {
    checkNotNull(deviceId, DEVICE_NULL);

    Optional<VirtualPort> foundPort =
            manager.getVirtualPorts(this.networkId, deviceId)
            .stream()
            .filter(port -> port.number().equals(portNumber))
            .findFirst();
    if (foundPort.isPresent()) {
        return foundPort.get();
    }
    return null;
}
 
Example 12
Source File: ZKHostStore.java    From pravega with Apache License 2.0 5 votes vote down vote up
private Host getHostForContainer(int containerId) {
    tryInit();

    // Note: the reference for hostContainerMap may be updated as we are accessing it. However, the map is immutable.
    Optional<Host> host = hostContainerMap.get().getHostContainerMap().entrySet().stream()
                                 .filter(x -> x.getValue().contains(containerId)).map(Map.Entry::getKey).findAny();
    if (host.isPresent()) {
        log.debug("Found owning host: {} for containerId: {}", host.get(), containerId);
        return host.get();
    } else {
        throw new HostStoreException("Could not find host for container id: " + String.valueOf(containerId));
    }
}
 
Example 13
Source File: DefaultLexicon.java    From EasySRL with Apache License 2.0 5 votes vote down vote up
@Override
public Logic getEntry(final String word, final String pos, final Category category,
		final Coindexation coindexation, final Optional<CCGandSRLparse> parse, final int wordIndex) {
	final String lemma = getLemma(word, pos, parse, wordIndex);

	if (Category.valueOf("conj|conj").matches(category)) {
		// Special case, since we have other rules to deal with this non-compositionally.
		return new Constant(lemma, SemanticType.E);
	}

	final List<SRLLabel> labels;
	if (parse.isPresent()) {
		final List<ResolvedDependency> deps = parse.get().getOrderedDependenciesAtPredicateIndex(wordIndex);

		// Find the semantic role for each argument of the category.
		labels = deps.stream().map(x -> x == null ? SRLFrame.NONE : x.getSemanticRole())
				.collect(Collectors.toList());

	} else {
		labels = noLabels;
	}

	final HeadAndArguments headAndArguments = new HeadAndArguments(category, coindexation);

	return LambdaExpression.make(
			getEntry(lemma, category, coindexation, headAndArguments.argumentVariables,
					headAndArguments.headVariable, null, headAndArguments.coindexationIDtoVariable,
					isContentWord(lemma, pos, category), labels), headAndArguments.argumentVariables);
}
 
Example 14
Source File: RolesController.java    From pulsar-manager with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Update a role")
@ApiResponses({
        @ApiResponse(code = 200, message = "ok"),
        @ApiResponse(code = 404, message = "Not found"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@RequestMapping(value = "/roles/role", method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> updateRole(@RequestBody RoleInfoEntity roleInfoEntity) {
    Map<String, Object> result = Maps.newHashMap();
    String token = request.getHeader("token");
    String tenant = request.getHeader("tenant");
    Map<String, String> validateResult = rolesService.validateCurrentTenant(token, tenant);
    if (validateResult.get("error") != null) {
        result.put("error", validateResult.get("error"));
        return ResponseEntity.ok(result);
    }
    Optional<RoleInfoEntity> optionalRoleInfoEntity = rolesRepository.findByRoleName(
            roleInfoEntity.getRoleName(), tenant);
    if (!optionalRoleInfoEntity.isPresent()) {
        result.put("error", "Failed update a role, role does not exist.");
        return ResponseEntity.ok(result);
    }
    RoleInfoEntity roleInfo = optionalRoleInfoEntity.get();
    if (ResourceType.NAMESPACES.name().equals(roleInfoEntity.getResourceType())
            || ResourceType.TOPICS.name().equals(roleInfoEntity.getResourceType())) {
        // More resource type need be added
        Map<String, String> roleInfoEntityValidate = rolesService.validateRoleInfoEntity(roleInfoEntity);
        if (roleInfoEntityValidate.get("error") != null) {
            result.put("error", roleInfoEntityValidate.get("error"));
            return ResponseEntity.ok(result);
        }
        roleInfoEntity.setFlag(roleInfo.getFlag());
        roleInfoEntity.setRoleSource(tenant);
        rolesRepository.update(roleInfoEntity);
        result.put("message", "Update a role success");
        return ResponseEntity.ok(result);
    }
    result.put("error", "Unsupported resource types");
    return ResponseEntity.ok(result);
}
 
Example 15
Source File: EditCommand.java    From rug-cli with GNU General Public License v3.0 5 votes vote down vote up
@Command
public void run(Rugs operations, ArtifactDescriptor artifact,
        @Argument(index = 1) String fqArtifactName,
        @Argument(start = 2) ParameterValues arguments, @Option("change-dir") String root,
        @Option("dry-run") boolean dryRun, @Option("repo") boolean repo, RugResolver resolver) {

    String editorName = OperationUtils.extractRugTypeName(fqArtifactName);
    Optional<ProjectEditor> opt = asJavaCollection(operations.editors()).stream()
            .filter(g -> g.name().equals(editorName)).findFirst();

    if (opt.isPresent()) {
        arguments = validate(artifact, opt.get(), arguments);
        invoke(artifact, opt.get(), arguments, root, dryRun, repo, resolver);
    }
    else {
        if (!operations.editors().isEmpty()) {
            log.newline();
            log.info(Style.cyan(Constants.DIVIDER) + " " + Style.bold("Editors"));
            asJavaCollection(operations.editors()).forEach(e -> log.info(
                    Style.yellow("  %s", StringUtils.stripName(e.name(), artifact)) + "\n    "
                            + WordUtils.wrap(
                                    org.apache.commons.lang3.StringUtils
                                            .capitalize(e.description()),
                                    Constants.WRAP_LENGTH, "\n    ", false)));
            StringUtils.printClosestMatch(editorName, artifact, operations.editorNames());
        }
        throw new CommandException(
                String.format("Specified editor %s could not be found in %s:%s",
                        StringUtils.stripName(editorName, artifact), artifact.group(),
                        artifact.artifact()));
    }
}
 
Example 16
Source File: CustomerRepository.java    From Mastering-Spring-Cloud with MIT License 5 votes vote down vote up
public Customer findById(Long id) {
	Optional<Customer> customer = customers.stream().filter(p -> p.getId().equals(id)).findFirst();
	if (customer.isPresent())
		return customer.get();
	else
		return null;
}
 
Example 17
Source File: GoogleCalendarExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private ExportResult<CalendarContainerResource> getCalendarEvents(
    TokensAndUrlAuthData authData, String id, Optional<PaginationData> pageData) {
  Calendar.Events.List listRequest;
  Events listResult;

  // Get event information
  try {
    listRequest =
        getOrCreateCalendarInterface(authData)
            .events()
            .list(id)
            .setMaxAttendees(GoogleStaticObjects.MAX_ATTENDEES);
    if (pageData.isPresent()) {
      StringPaginationToken paginationToken = (StringPaginationToken) pageData.get();
      Preconditions.checkState(
          paginationToken.getToken().startsWith(EVENT_TOKEN_PREFIX), "Token is not applicable");
      listRequest.setPageToken(
          ((StringPaginationToken) pageData.get())
              .getToken()
              .substring(EVENT_TOKEN_PREFIX.length()));
    }
    listResult = listRequest.execute();
  } catch (IOException e) {
    return new ExportResult<>(e);
  }

  // Set up continuation data
  PaginationData nextPageData = null;
  if (listResult.getNextPageToken() != null) {
    nextPageData = new StringPaginationToken(EVENT_TOKEN_PREFIX + listResult.getNextPageToken());
  }
  ContinuationData continuationData = new ContinuationData(nextPageData);

  // Process event list
  List<CalendarEventModel> eventModels = new ArrayList<>(listResult.getItems().size());
  for (Event eventData : listResult.getItems()) {
    CalendarEventModel model = convertToCalendarEventModel(id, eventData);
    eventModels.add(model);
  }
  CalendarContainerResource calendarContainerResource =
      new CalendarContainerResource(null, eventModels);

  // Get result type
  ExportResult.ResultType resultType = ResultType.CONTINUE;
  if (nextPageData == null) {
    resultType = ResultType.END;
  }

  return new ExportResult<>(resultType, calendarContainerResource, continuationData);
}
 
Example 18
Source File: AmazonLambdaProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep
List<AmazonLambdaBuildItem> discover(CombinedIndexBuildItem combinedIndexBuildItem,
        Optional<ProvidedAmazonLambdaHandlerBuildItem> providedLambda,
        BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer,
        BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer) throws BuildException {

    Collection<ClassInfo> allKnownImplementors = combinedIndexBuildItem.getIndex().getAllKnownImplementors(REQUEST_HANDLER);
    allKnownImplementors.addAll(combinedIndexBuildItem.getIndex()
            .getAllKnownImplementors(REQUEST_STREAM_HANDLER));
    allKnownImplementors.addAll(combinedIndexBuildItem.getIndex()
            .getAllKnownSubclasses(SKILL_STREAM_HANDLER));

    if (allKnownImplementors.size() > 0 && providedLambda.isPresent()) {
        throw new BuildException(
                "Multiple handler classes.  You have a custom handler class and the " + providedLambda.get().getProvider()
                        + " extension.  Please remove one of them from your deployment.",
                Collections.emptyList());

    }
    AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable();
    List<AmazonLambdaBuildItem> ret = new ArrayList<>();

    for (ClassInfo info : allKnownImplementors) {
        if (Modifier.isAbstract(info.flags())) {
            continue;
        }

        final DotName name = info.name();
        final String lambda = name.toString();
        builder.addBeanClass(lambda);
        reflectiveClassBuildItemBuildProducer.produce(new ReflectiveClassBuildItem(true, false, lambda));

        String cdiName = null;
        AnnotationInstance named = info.classAnnotation(NAMED);
        if (named != null) {
            cdiName = named.value().asString();
        }

        ClassInfo current = info;
        boolean done = false;
        boolean streamHandler = info.superName().equals(SKILL_STREAM_HANDLER) ? true : false;
        while (current != null && !done) {
            for (MethodInfo method : current.methods()) {
                if (method.name().equals("handleRequest")) {
                    if (method.parameters().size() == 3) {
                        streamHandler = true;
                        done = true;
                        break;
                    } else if (method.parameters().size() == 2
                            && !method.parameters().get(0).name().equals(DotName.createSimple(Object.class.getName()))) {
                        reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(method.parameters().get(0)));
                        reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(method.returnType()));
                        done = true;
                        break;
                    }
                }
            }
            current = combinedIndexBuildItem.getIndex().getClassByName(current.superName());
        }
        ret.add(new AmazonLambdaBuildItem(lambda, cdiName, streamHandler));
    }
    additionalBeanBuildItemBuildProducer.produce(builder.build());
    reflectiveClassBuildItemBuildProducer
            .produce(new ReflectiveClassBuildItem(true, true, true, FunctionError.class));
    return ret;
}
 
Example 19
Source File: DefaultScheduler.java    From dcos-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new DefaultScheduler. See information about parameters in {@link SchedulerBuilder}.
 */
protected DefaultScheduler(
    ServiceSpec serviceSpec,
    SchedulerConfig schedulerConfig,
    Optional<String> namespace,
    Collection<Object> customResources,
    PlanCoordinator planCoordinator,
    Optional<PlanCustomizer> planCustomizer,
    FrameworkStore frameworkStore,
    StateStore stateStore,
    ConfigStore<ServiceSpec> configStore,
    ArtifactQueries.TemplateUrlFactory templateUrlFactory,
    Map<String, EndpointProducer> customEndpointProducers) throws ConfigStoreException
{
  super(serviceSpec, schedulerConfig, stateStore, planCoordinator, planCustomizer, namespace);
  this.logger = LoggingUtils.getLogger(getClass(), namespace);
  this.namespace = namespace;
  this.frameworkStore = frameworkStore;
  this.configStore = configStore;
  this.goalState = serviceSpec.getGoal();
  this.customResources = customResources;
  this.customEndpointProducers = customEndpointProducers;

  this.launchRecorder = new PersistentLaunchRecorder(stateStore, serviceSpec, namespace);
  Optional<DecommissionPlanManager> decommissionManager = getDecommissionManager(planCoordinator);
  if (decommissionManager.isPresent()) {
    this.decommissionRecorder =

        Optional.of(new UninstallRecorder(stateStore, decommissionManager.get().getResourceSteps()));
  } else {
    this.decommissionRecorder = Optional.empty();
  }

  // Get the recovery and deploy plan managers. We store the PlanManagers, not the underlying Plans, because
  // PlanManagers can change their plans at any time.
  this.deploymentPlanManager = planCoordinator.getPlanManagers().stream()
      .filter(pm -> pm.getPlan().isDeployPlan())
      .findAny()
      .get();
  this.deploymentCompletionWasStored = false;
  this.recoveryPlanManager = planCoordinator.getPlanManagers().stream()
      .filter(pm -> pm.getPlan().isRecoveryPlan())
      .findAny()
      .get();

  // If the service is namespaced (i.e. part of a multi-service scheduler), disable the OfferOutcomeTracker to
  // reduce memory consumption.
  this.offerOutcomeTrackerV2 = namespace.isPresent() ? Optional.empty() : Optional.of(new OfferOutcomeTrackerV2());
  this.statusesTracker = Optional.of(new TaskStatusesTracker(getPlanCoordinator(), stateStore));
  this.reservationsTracker = Optional.of(new TaskReservationsTracker(stateStore));

  this.planScheduler = new PlanScheduler(
      new OfferEvaluator(
          frameworkStore,
          stateStore,
          offerOutcomeTrackerV2,
          serviceSpec.getName(),
          configStore.getTargetConfig(),
          templateUrlFactory,
          schedulerConfig,
          namespace),
      stateStore,
      namespace);

  customizePlans();
  this.plansTracker = Optional.of(new PlansTracker(getPlanCoordinator(), stateStore));
}
 
Example 20
Source File: PBXTestUtils.java    From buck with Apache License 2.0 4 votes vote down vote up
public static void assertHasSingleSourcesPhaseWithSourcesAndFlags(
    PBXTarget target,
    ImmutableMap<String, Optional<String>> sourcesAndFlags,
    ProjectFilesystem projectFilesystem,
    Path outputDirectory) {

  PBXSourcesBuildPhase sourcesBuildPhase =
      ProjectGeneratorTestUtils.getSingleBuildPhaseOfType(target, PBXSourcesBuildPhase.class);

  assertEquals(
      "Sources build phase should have correct number of sources",
      sourcesAndFlags.size(),
      sourcesBuildPhase.getFiles().size());

  // map keys to absolute paths
  ImmutableMap.Builder<String, Optional<String>> absolutePathFlagMapBuilder =
      ImmutableMap.builder();
  for (Map.Entry<String, Optional<String>> name : sourcesAndFlags.entrySet()) {
    absolutePathFlagMapBuilder.put(
        projectFilesystem.getRootPath().resolve(name.getKey()).normalize().toString(),
        name.getValue());
  }
  ImmutableMap<String, Optional<String>> absolutePathFlagMap = absolutePathFlagMapBuilder.build();

  for (PBXBuildFile file : sourcesBuildPhase.getFiles()) {
    String filePath =
        assertFileRefIsRelativeAndResolvePath(
            file.getFileRef(), projectFilesystem, outputDirectory);
    Optional<String> flags = absolutePathFlagMap.get(filePath);
    assertNotNull(String.format("Unexpected file ref '%s' found", filePath), flags);
    if (flags.isPresent()) {
      assertTrue("Build file should have settings dictionary", file.getSettings().isPresent());

      NSDictionary buildFileSettings = file.getSettings().get();
      NSString compilerFlags = (NSString) buildFileSettings.get("COMPILER_FLAGS");

      assertNotNull("Build file settings should have COMPILER_FLAGS entry", compilerFlags);
      assertEquals(
          "Build file settings should be expected value",
          flags.get(),
          compilerFlags.getContent());
    } else {
      assertFalse(
          "Build file should not have settings dictionary", file.getSettings().isPresent());
    }
  }
}