canonical example by Tabnine
private Double calculateAverageGrade(Map<String, List<Integer>> gradesList, String studentName) throws Exception { return Optional.ofNullable(gradesList.get(studentName)) .map(list -> list.stream().collect(Collectors.averagingDouble(x -> x))) .orElseThrow(() -> new Exception("Student not found - " + studentName)); }
private static <T> HttpMessageWriter<T> findWriter( BodyInserter.Context context, ResolvableType elementType, @Nullable MediaType mediaType) { return context.messageWriters().stream() .filter(messageWriter -> messageWriter.canWrite(elementType, mediaType)) .findFirst() .map(BodyInserters::<T>cast) .orElseThrow(() -> new IllegalStateException( "No HttpMessageWriter for \"" + mediaType + "\" and \"" + elementType + "\"")); }
@Override public RouterFunction<ServerResponse> build() { RouterFunction<ServerResponse> result = this.routerFunctions.stream() .reduce(RouterFunction::and) .orElseThrow(IllegalStateException::new); if (this.filterFunctions.isEmpty()) { return result; } else { HandlerFilterFunction<ServerResponse, ServerResponse> filter = this.filterFunctions.stream() .reduce(HandlerFilterFunction::andThen) .orElseThrow(IllegalStateException::new); return result.filter(filter); } }
private <K, V> V loadValue(Cache<K, V> cache, K key, Supplier<V> valueSupplier) { if (replay) { return Optional.ofNullable(cache.getIfPresent(key)) .orElseThrow(() -> new PrestoException(NOT_FOUND, "Missing entry found for key: " + key)); } V value = valueSupplier.get(); cache.put(key, value); return value; }
private static String findVersion(Map<Interval, String> versions, Interval interval) { return versions.entrySet().stream() .filter(entry -> entry.getKey().contains(interval)) .map(Entry::getValue) .findFirst() .orElseThrow(() -> new ISE("Cannot find a version for interval[%s]", interval)); }
@GetMapping(value = "/md5/{md5}") @ApiOperation("根据MD5获取文件信息") public ResponseMessage<FileInfoEntity> uploadStatic(@PathVariable String md5) throws IOException { return ofNullable(fileInfoService.selectByMd5(md5)) .map(ResponseMessage::ok) .orElseThrow(() -> new NotFoundException("file not found")); } }
private void closeWorker() throws Exception { int nodeCount = getNodeCount(); DistributedQueryRunner queryRunner = (DistributedQueryRunner) getQueryRunner(); TestingPrestoServer worker = queryRunner.getServers().stream() .filter(server -> !server.isCoordinator()) .findAny() .orElseThrow(() -> new IllegalStateException("No worker nodes")); worker.close(); waitForNodes(nodeCount - 1); }
private IndexSetConfig findDefaultIndexSet() { final List<IndexSetConfig> indexSetConfigs = indexSetService.findAll(); // If there is more than one index set, we have a problem. Since there wasn't a way to create index sets // manually until now, this should not happen. checkState(indexSetConfigs.size() < 2, "Found more than one index set config!"); // If there is no index set, a previous migration didn't work. return indexSetConfigs.stream() .findFirst() .orElseThrow(() -> new IllegalStateException("Couldn't find any index set config!")); }
private static Project createProject(org.sonar.ce.task.CeTask ceTask) { return ceTask.getMainComponent() .map(c -> new ProjectImpl( c.getUuid(), c.getKey().orElseThrow(() -> new IllegalStateException("Missing project key")), c.getName().orElseThrow(() -> new IllegalStateException("Missing project name")))) .orElseThrow(() -> new IllegalStateException("Report processed for a task of a deleted component")); }
private ClassTree getTopLevelClass(VisitorState state) { return (ClassTree) Streams.findLast( Streams.stream(state.getPath().iterator()) .filter((Tree t) -> t.getKind() == Kind.CLASS)) .orElseThrow(() -> new IllegalArgumentException("No enclosing class found")); }
@Test void lookupFileByDatabaseFile() { DatabaseLayout layout = testDirectory.databaseLayout(); DatabaseFile[] databaseFiles = DatabaseFile.values(); for ( DatabaseFile databaseFile : databaseFiles ) { assertNotNull( layout.file( databaseFile ).findAny().orElseThrow( () -> new RuntimeException( "Mapping was expected to be found" ) ) ); } File metadata = layout.file( DatabaseFile.METADATA_STORE ).findFirst().orElseThrow( () -> new RuntimeException( "Mapping was expected to be found" ) ); assertEquals( "neostore", metadata.getName() ); }
private static <T> HttpMessageReader<T> findReader( ResolvableType elementType, MediaType mediaType, BodyExtractor.Context context) { return context.messageReaders().stream() .filter(messageReader -> messageReader.canRead(elementType, mediaType)) .findFirst() .map(BodyExtractors::<T>cast) .orElseThrow(() -> new IllegalStateException( "No HttpMessageReader for \"" + mediaType + "\" and \"" + elementType + "\"")); }
private static String findVersion(Map<Interval, String> versions, Interval interval) { return versions.entrySet().stream() .filter(entry -> entry.getKey().contains(interval)) .map(Entry::getValue) .findFirst() .orElseThrow(() -> new ISE("Cannot find a version for interval[%s]", interval)); }
/** * Run the client, pulling credentials from the environment. * Throws an IllegalStateException if the required environment variables aren't set. * These are: * * <ul> * <li>CORENLP_HOST</li> * <li>CORENLP_KEY</li> * <li>CORENLP_SECRET</li> * </ul> * * @throws IllegalStateException Thrown if we could not read the required environment variables. */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties) throws IllegalStateException { this(properties, Optional.ofNullable(System.getenv("CORENLP_HOST")).orElseThrow(() -> new IllegalStateException("Environment variable CORENLP_HOST not specified")), Optional.ofNullable(System.getenv("CORENLP_HOST")).map(x -> x.startsWith("http://") ? 80 : 443).orElse(443), 1, Optional.ofNullable(System.getenv("CORENLP_KEY")).orElse(null), Optional.ofNullable(System.getenv("CORENLP_SECRET")).orElse(null) ); }
QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getTable()); TableHandle tableHandle = metadata.getTableHandle(session, tableName) .orElseThrow(() -> new SemanticException(MISSING_TABLE, statement, "Table '%s' does not exist", tableName)); if (metadata.getTableMetadata(session, tableHandle).getColumns().stream() .filter(info -> !info.isHidden()).count() <= 1) { throw new SemanticException(NOT_SUPPORTED, statement, "Cannot drop the only column in a table");
/** * Resolve the current {@link Subscriber}. * * @return An {@link Optional} of the subscriber * @throws IllegalStateException If no {@link Subscriber} is present */ protected Subscriber<? super T> getDownstreamSubscriber() { return Optional.ofNullable(this.downstreamSubscriber.get()).orElseThrow(() -> new IllegalStateException("No subscriber present!")); } }
private String getPartitionName(String databaseName, String tableName, List<String> partitionValues) { Table table = getTable(databaseName, tableName) .orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName))); List<String> columnNames = table.getPartitionColumns().stream() .map(Column::getName) .collect(toImmutableList()); return makePartName(columnNames, partitionValues); }
public VncRecordingContainer(@NonNull GenericContainer<?> targetContainer) { this( targetContainer.getNetwork(), targetContainer.getNetworkAliases().stream() .findFirst() .orElseThrow(() -> new IllegalStateException("Target container must have a network alias")) ); }
@GET @Path("{id}/stats") @Timed @ApiOperation(value = "Get index set statistics") @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), @ApiResponse(code = 404, message = "Index set not found"), }) public IndexSetStats indexSetStatistics(@ApiParam(name = "id", required = true) @PathParam("id") String id) { checkPermission(RestPermissions.INDEXSETS_READ, id); return indexSetRegistry.get(id) .map(indexSetStatsCreator::getForIndexSet) .orElseThrow(() -> new NotFoundException("Couldn't load index set with ID <" + id + ">")); }
private static ClassTree getTopLevelClassTree(VisitorState state) { return (ClassTree) Streams.findLast( Streams.stream(state.getPath().iterator()) .filter((Tree t) -> t.getKind() == Kind.CLASS)) .orElseThrow(() -> new IllegalArgumentException("No enclosing class found")); }