001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.reactive.reactor;
018
019import org.apache.juneau.rest.server.reactive.*;
020import org.reactivestreams.*;
021
022import reactor.core.publisher.*;
023
024/**
025 * {@link ReactiveStreamsAdapter} for <a class="doclink" href="https://projectreactor.io/">Project Reactor</a>
026 * return types.
027 *
028 * <ul>
029 *    <li>{@link Mono Mono&lt;T&gt;} &rarr; single value (via {@link Mono#toFuture()}). An empty {@code Mono}
030 *       completes the response with a {@code null} body.
031 *    <li>{@link Flux Flux&lt;T&gt;} &rarr; stream (via {@link org.reactivestreams.FlowAdapters#toFlowPublisher(Publisher)}).
032 * </ul>
033 *
034 * <p>
035 * Registered ahead of {@link ReactiveStreamsPublisherAdapter} so a {@code Mono} (which also implements
036 * {@code org.reactivestreams.Publisher}) is treated as a single value rather than a one-element stream.
037 *
038 * @since 10.0.0
039 */
040public class ReactorReactiveAdapter implements ReactiveStreamsAdapter {
041
042   @Override /* Overridden from ReactiveStreamsAdapter */
043   public boolean canAdapt(Object value) {
044      return value instanceof Mono || value instanceof Flux;
045   }
046
047   @Override /* Overridden from ReactiveStreamsAdapter */
048   public Adaptation adapt(Object value) {
049      if (value instanceof Mono<?> value2)
050         return Adaptation.single(value2.toFuture());
051      var f = (Flux<?>) value;
052      return Adaptation.stream(FlowAdapters.toFlowPublisher(f));
053   }
054}