下面列出了java.util.Optional#orElseThrow ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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())));
}
@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"));
}
}
@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);
});
}
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)));
}
@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"));
}
@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()));
}
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())));
}
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseThrowNull() throws Throwable {
Optional<Boolean> empty = Optional.empty();
Boolean got = empty.orElseThrow(null);
}
private SignedBeaconBlock toBlock(
UnsignedLong lookupSlot, Optional<SignedBeaconBlock> maybeBlock) {
return maybeBlock.orElseThrow(
() -> new IllegalStateException("Missing finalized block at slot " + lookupSlot));
}
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
Optional<Boolean> empty = Optional.empty();
Boolean got = empty.orElseThrow(ObscureException::new);
}
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));
}
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
Optional<Boolean> empty = Optional.empty();
Boolean got = empty.orElseThrow(ObscureException::new);
}
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"));
});
}
public Collection getCollectionMetadata(String collectionName) throws InvalidCollectionException {
Vres vres = loadVres();
Optional<Collection> collection = vres.getCollection(collectionName);
return collection.orElseThrow(() -> new InvalidCollectionException(collectionName));
}
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));
}
@Override
public ServiceInfo getServiceInfo(int serviceId) {
Optional<ServiceInfo> serviceInfoOpt = serviceInfoRepository.findById(serviceId);
return serviceInfoOpt.orElseThrow(() -> new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND));
}
@Override
public AppInfo getAppInfo(int appId) {
Optional<AppInfo> appInfoOpt = appInfoRepository.findById(appId);
return appInfoOpt.orElseThrow(() -> new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND));
}
@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);
}
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)));
}