java.util.Optional#orElseThrow ( )源码实例Demo

下面列出了java.util.Optional#orElseThrow ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: taskana   文件: JaasExtension.java
private ExtensionContext getParentMethodExtensionContent(ExtensionContext extensionContext) {
  Optional<ExtensionContext> parent = extensionContext.getParent();
  // the class MethodExtensionContext is part of junit-jupiter-engine and has only a
  // package-private visibility thus this workaround is needed.
  while (!parent
      .map(Object::getClass)
      .map(Class::getName)
      .filter(s -> s.endsWith("MethodExtensionContext"))
      .isPresent()) {
    parent = parent.flatMap(ExtensionContext::getParent);
  }
  return parent.orElseThrow(
      () ->
          new JUnitException(
              String.format(
                  "Test '%s' does not have a parent method", extensionContext.getUniqueId())));
}
 
源代码2 项目: incubator-nemo   文件: BlockInputReader.java
@Override
public List<CompletableFuture<DataUtil.IteratorWithNumBytes>> read() {
  final Optional<CommunicationPatternProperty.Value> comValueOptional =
    runtimeEdge.getPropertyValue(CommunicationPatternProperty.class);
  final CommunicationPatternProperty.Value comValue = comValueOptional.orElseThrow(IllegalStateException::new);

  switch (comValue) {
    case ONE_TO_ONE:
      return Collections.singletonList(readOneToOne());
    case BROADCAST:
      return readBroadcast(index -> true);
    case SHUFFLE:
      return readDataInRange(index -> true);
    default:
      throw new UnsupportedCommPatternException(new Exception("Communication pattern not supported"));
  }
}
 
源代码3 项目: xlsmapper   文件: EnumFormatter.java
@SuppressWarnings("unchecked")
@Override
public T parse(final String text) throws TextParseException {
    final String keyText = ignoreCase ? text.toLowerCase() : text;
    final Optional<T> obj = Optional.ofNullable((T)toObjectMap.get(keyText));

    return obj.orElseThrow(() -> {

        final Map<String, Object> vars = new HashMap<>();
        vars.put("type", getType().getName());
        vars.put("ignoreCase", isIgnoreCase());

        getAliasMethod().ifPresent(method -> vars.put("alias", method.getName()));
        vars.put("enums", getToStringMap().values());

        return new TextParseException(text, type, vars);
    });
}
 
源代码4 项目: che   文件: NewWorkspace.java
public static Devfile getById(String id) {
  Optional<Devfile> first =
      asList(values()).stream().filter(devfile -> devfile.getId().equals(id)).findFirst();
  first.orElseThrow(
      () -> new RuntimeException(String.format("Devfile with id '%s' not found.", id)));
  return first.get();
}
 
private Adapter(Context context, RepositoryService repositoryService, String id) {

      Optional<String> key = Optional.empty();

      switch (context) {
      case bpmn:
        key = Optional.ofNullable(repositoryService.getProcessDefinition(id)).map(ProcessDefinition::getKey);
        break;
      case cmmn:
        key = Optional.ofNullable(repositoryService.getCaseDefinition(id)).map(CaseDefinition::getKey);
        break;
      }
      this.key = key.orElseThrow(() -> new IllegalStateException(String.format("could not load definition for %s/%s", context, id)));
    }
 
源代码6 项目: spring-data-keyvalue   文件: SpelSortAccessor.java
@Override
public Comparator<?> resolve(KeyValueQuery<?> query) {

	if (query.getSort().isUnsorted()) {
		return null;
	}

	Optional<Comparator<?>> comparator = Optional.empty();
	for (Order order : query.getSort()) {

		SpelPropertyComparator<Object> spelSort = new SpelPropertyComparator<>(order.getProperty(), parser);

		if (Direction.DESC.equals(order.getDirection())) {

			spelSort.desc();

			if (!NullHandling.NATIVE.equals(order.getNullHandling())) {
				spelSort = NullHandling.NULLS_FIRST.equals(order.getNullHandling()) ? spelSort.nullsFirst()
						: spelSort.nullsLast();
			}
		}

		if (!comparator.isPresent()) {
			comparator = Optional.of(spelSort);
		} else {

			SpelPropertyComparator<Object> spelSortToUse = spelSort;
			comparator = comparator.map(it -> it.thenComparing(spelSortToUse));
		}
	}

	return comparator.orElseThrow(
			() -> new IllegalStateException("No sort definitions have been added to this CompoundComparator to compare"));
}
 
源代码7 项目: flink   文件: HiveShimV100.java
@Override
public Writable hivePrimitiveToWritable(Object value) {
	if (value == null) {
		return null;
	}
	Optional<Writable> optional = javaToWritable(value);
	return optional.orElseThrow(() -> new FlinkHiveException("Unsupported primitive java value of class " + value.getClass().getName()));
}
 
源代码8 项目: keywhiz   文件: ClientAuthFactory.java
private Client authorizeClientFromCertificate(Principal clientPrincipal) {
  Optional<Client> possibleClient =
      authenticator.authenticate(clientPrincipal, true);
  return possibleClient.orElseThrow(() -> new NotAuthorizedException(
      format("No authorized Client for connection using principal %s",
          clientPrincipal.getName())));
}
 
源代码9 项目: jdk8u_jdk   文件: Basic.java
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseThrowNull() throws Throwable {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(null);
}
 
源代码10 项目: teku   文件: PeerChainValidator.java
private SignedBeaconBlock toBlock(
    UnsignedLong lookupSlot, Optional<SignedBeaconBlock> maybeBlock) {
  return maybeBlock.orElseThrow(
      () -> new IllegalStateException("Missing finalized block at slot " + lookupSlot));
}
 
源代码11 项目: jdk8u-dev-jdk   文件: Basic.java
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(ObscureException::new);
}
 
源代码12 项目: eas-ddd   文件: NotificationService.java
private ValidDate retrieveValidDate(Ticket ticket) {
    Optional<ValidDate> optionalValidDate = validDateRepository.validDateOf(ticket.trainingId(), ValidDateType.PODeadline);
    String validDateNotFoundMessage = String.format("valid date by training id {%s} was not found.", ticket.trainingId());
    return optionalValidDate.orElseThrow(() -> new ValidDateException(validDateNotFoundMessage));
}
 
源代码13 项目: openjdk-jdk8u-backup   文件: Basic.java
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(ObscureException::new);
}
 
源代码14 项目: quarkus   文件: SetupVerifier.java
public static void verifySetup(File pomFile) throws Exception {
    assertNotNull(pomFile, "Unable to find pom.xml");
    MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
    Model model = xpp3Reader.read(new FileInputStream(pomFile));

    MavenProject project = new MavenProject(model);

    Optional<Plugin> maybe = hasPlugin(project, ToolsConstants.IO_QUARKUS + ":" + ToolsConstants.QUARKUS_MAVEN_PLUGIN);
    assertThat(maybe).isNotEmpty();

    //Check if the properties have been set correctly
    Properties properties = model.getProperties();
    assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLATFORM_GROUP_ID_NAME)).isTrue();
    assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLATFORM_ARTIFACT_ID_NAME)).isTrue();
    assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLATFORM_VERSION_NAME)).isTrue();
    assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLUGIN_VERSION_NAME)).isTrue();

    // Check plugin is set
    Plugin plugin = maybe.orElseThrow(() -> new AssertionError("Plugin expected"));
    assertThat(plugin).isNotNull().satisfies(p -> {
        assertThat(p.getArtifactId()).isEqualTo(ToolsConstants.QUARKUS_MAVEN_PLUGIN);
        assertThat(p.getGroupId()).isEqualTo(ToolsConstants.IO_QUARKUS);
        assertThat(p.getVersion()).isEqualTo(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLUGIN_VERSION_VALUE);
    });

    // Check build execution Configuration
    assertThat(plugin.getExecutions()).hasSize(1).allSatisfy(execution -> {
        assertThat(execution.getGoals()).containsExactly("build");
        assertThat(execution.getConfiguration()).isNull();
    });

    // Check profile
    assertThat(model.getProfiles()).hasSize(1);
    Profile profile = model.getProfiles().get(0);
    assertThat(profile.getId()).isEqualTo("native");
    Plugin actual = profile.getBuild().getPluginsAsMap()
            .get(ToolsConstants.IO_QUARKUS + ":" + ToolsConstants.QUARKUS_MAVEN_PLUGIN);
    assertThat(actual).isNotNull();
    assertThat(actual.getExecutions()).hasSize(1).allSatisfy(exec -> {
        assertThat(exec.getGoals()).containsExactly("native-image");
        assertThat(exec.getConfiguration()).isInstanceOf(Xpp3Dom.class)
                .satisfies(o -> assertThat(o.toString()).contains("enableHttpUrlHandler"));
    });
}
 
源代码15 项目: timbuctoo   文件: TimbuctooActions.java
public Collection getCollectionMetadata(String collectionName) throws InvalidCollectionException {
  Vres vres = loadVres();
  Optional<Collection> collection = vres.getCollection(collectionName);

  return collection.orElseThrow(() -> new InvalidCollectionException(collectionName));
}
 
源代码16 项目: edison-microservice   文件: JobService.java
private JobRunnable findJobRunnable(final String jobType) {
    final Optional<JobRunnable> optionalRunnable = jobRunnables.stream().filter(r -> r.getJobDefinition().jobType().equalsIgnoreCase(jobType)).findFirst();
    return optionalRunnable.orElseThrow(() -> new IllegalArgumentException("No JobRunnable for " + jobType));
}
 
源代码17 项目: moon-api-gateway   文件: DBClusterRepository.java
@Override
public ServiceInfo getServiceInfo(int serviceId) {
    Optional<ServiceInfo> serviceInfoOpt = serviceInfoRepository.findById(serviceId);
    return serviceInfoOpt.orElseThrow(() -> new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND));
}
 
源代码18 项目: moon-api-gateway   文件: DBClusterRepository.java
@Override
public AppInfo getAppInfo(int appId) {
    Optional<AppInfo> appInfoOpt = appInfoRepository.findById(appId);
    return appInfoOpt.orElseThrow(() -> new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND));
}
 
源代码19 项目: james-project   文件: JPASieveRepository.java
@Override
public InputStream getScript(Username username, ScriptName name) throws ScriptNotFoundException, StorageException {
    Optional<JPASieveScript> script = findSieveScript(username, name);
    JPASieveScript sieveScript = script.orElseThrow(() -> new ScriptNotFoundException("Unable to find script " + name.getValue() + " for user " + username.asString()));
    return IOUtils.toInputStream(sieveScript.getScriptContent(), StandardCharsets.UTF_8);
}
 
源代码20 项目: cloudbreak   文件: StackService.java
public Stack getByNameOrCrnInWorkspace(NameOrCrn nameOrCrn, Long workspaceId) {
    Optional<Stack> foundStack = nameOrCrn.hasName()
            ? stackRepository.findByNameAndWorkspaceId(nameOrCrn.getName(), workspaceId)
            : stackRepository.findByCrnAndWorkspaceId(nameOrCrn.getCrn(), workspaceId);
    return foundStack.orElseThrow(() -> new NotFoundException(String.format(STACK_NOT_FOUND_BY_NAME_OR_CRN_EXCEPTION_MESSAGE, nameOrCrn)));
}