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

The following examples show how to use java.util.Optional#orElseThrow() . 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: EnumFormatter.java    From xlsmapper with Apache License 2.0 6 votes vote down vote up
@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);
    });
}
 
Example 2
Source File: BlockInputReader.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
@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"));
  }
}
 
Example 3
Source File: JaasExtension.java    From taskana with Apache License 2.0 6 votes vote down vote up
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())));
}
 
Example 4
Source File: GetProcessDefinitionKey.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
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)));
    }
 
Example 5
Source File: ClientAuthFactory.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
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())));
}
 
Example 6
Source File: HiveShimV100.java    From flink with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example 7
Source File: SpelSortAccessor.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 8
Source File: NewWorkspace.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
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();
}
 
Example 9
Source File: SetupVerifier.java    From quarkus with Apache License 2.0 4 votes vote down vote up
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"));
    });
}
 
Example 10
Source File: TimbuctooActions.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public Collection getCollectionMetadata(String collectionName) throws InvalidCollectionException {
  Vres vres = loadVres();
  Optional<Collection> collection = vres.getCollection(collectionName);

  return collection.orElseThrow(() -> new InvalidCollectionException(collectionName));
}
 
Example 11
Source File: JobService.java    From edison-microservice with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example 12
Source File: Basic.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseThrowNull() throws Throwable {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(null);
}
 
Example 13
Source File: Basic.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(ObscureException::new);
}
 
Example 14
Source File: DBClusterRepository.java    From moon-api-gateway with MIT License 4 votes vote down vote up
@Override
public ServiceInfo getServiceInfo(int serviceId) {
    Optional<ServiceInfo> serviceInfoOpt = serviceInfoRepository.findById(serviceId);
    return serviceInfoOpt.orElseThrow(() -> new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND));
}
 
Example 15
Source File: DBClusterRepository.java    From moon-api-gateway with MIT License 4 votes vote down vote up
@Override
public AppInfo getAppInfo(int appId) {
    Optional<AppInfo> appInfoOpt = appInfoRepository.findById(appId);
    return appInfoOpt.orElseThrow(() -> new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND));
}
 
Example 16
Source File: NotificationService.java    From eas-ddd with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example 17
Source File: JPASieveRepository.java    From james-project with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 18
Source File: Basic.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseThrow(ObscureException::new);
}
 
Example 19
Source File: StackService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
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)));
}
 
Example 20
Source File: PeerChainValidator.java    From teku with Apache License 2.0 4 votes vote down vote up
private SignedBeaconBlock toBlock(
    UnsignedLong lookupSlot, Optional<SignedBeaconBlock> maybeBlock) {
  return maybeBlock.orElseThrow(
      () -> new IllegalStateException("Missing finalized block at slot " + lookupSlot));
}