/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package samples.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.SkipPageException;

import org.apache.jsp.functional.AbortException;
import org.apache.jsp.functional.Fragment;
import static org.apache.jsp.functional.Fragment.evaluate;
import static org.apache.jsp.functional.Fragment.write;
import org.apache.jsp.functional.Page;
import samples.basic.CoreTagLibrary;
import samples.jsp.PageImpl;

/**
 * Alternative that uses a List to contain all the fragments comprising a page rather than using
 * .andThen() to chain them. This pattern may be useful to a JSP engine that does not rely on code
 * generation to build the page. On the other hand it might just be able to perform the chaining
 * dynamically where it would otherwise construct the array.
 */
public class FragmentStream extends HttpServlet {

    private final Collection<Fragment> pageBody;

    @Inject
    public FragmentStream(CoreTagLibrary core) {
        pageBody = Arrays.asList(
                write("Hello World"),
                evaluate("${x}"),
                core.out(Optional.of("Value param"), Optional.empty()),
                write("Goodbye World"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try (Page page = new PageImpl(this, req, resp)) {
            pageBody.stream().forEachOrdered(page);
        } catch (AbortException e) {
            Throwable cause = e.getCause();
            if (cause != null) {
                if (cause instanceof ServletException) {
                    throw (ServletException) cause;
                } else if (cause instanceof IOException) {
                    throw (IOException) cause;
                } else if (!(cause instanceof SkipPageException)) {
                    throw new ServletException(cause);
                }
            }
        }
    }
}
