/**
 *
 * Copyright (c) 2006-2016, Speedment, Inc. All Rights Reserved.
 *
 * Licensed 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.
 */
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.speedment.runtime.internal.db;

import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.runtime.db.AsynchronousQueryResult;
import com.speedment.runtime.exception.SpeedmentException;
import com.speedment.runtime.internal.stream.StreamUtil;
import com.speedment.runtime.stream.ParallelStrategy;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

import static java.util.Objects.requireNonNull;

/**
 *
 * @author pemi
 * @param <T> The type that the ResultSet shall be mapped to
 */
public final class AsynchronousQueryResultImpl<T> implements AsynchronousQueryResult<T> {

    private static final Logger LOGGER = LoggerManager.getLogger(AsynchronousQueryResultImpl.class);
    public static final String LOGGER_SELECT_NAME = AsynchronousQueryResultImpl.class.getName()+"#SELECT";
    private static final Logger LOGGER_SELECT = LoggerManager.getLogger(LOGGER_SELECT_NAME);

    private String sql;
    private List<?> values;
    private Function<ResultSet, T> rsMapper;
    private final Supplier<Connection> connectionSupplier;
    private ParallelStrategy parallelStrategy;
    private Connection connection;
    private PreparedStatement ps;
    private ResultSet rs;
    private State state;

    public enum State {
        INIT, ESTABLISH, OPEN, CLOSED;
    }

    public AsynchronousQueryResultImpl(
        final String sql,
        final List<?> values,
        final Function<ResultSet, T> rsMapper,
        Supplier<Connection> connectionSupplier
    ) {
        setSql(sql); // requireNonNull in setter
        setValues(values);
        setRsMapper(rsMapper);
        this.connectionSupplier = requireNonNull(connectionSupplier);
        parallelStrategy = ParallelStrategy.DEFAULT;
        setState(State.INIT);
    }

    @Override
    public Stream<T> stream() {
        setState(State.ESTABLISH);
        try {
            LOGGER_SELECT.debug("sql:%s, values:%s", getSql(), getValues());
            connection = connectionSupplier.get();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(getSql());
            int i = 1;
            for (final Object o : getValues()) {
                ps.setObject(i++, o);
            }
            rs = ps.executeQuery();
        } catch (SQLException sqle) {
            LOGGER.error(sqle, "Error executing " + getSql() + ", values=" + getValues());
            throw new SpeedmentException(sqle);
        }
        setState(State.OPEN);
        return StreamUtil.asStream(rs, getRsMapper(), parallelStrategy);
    }

    @Override
    public void close() {
        closeSilently(rs);
        closeSilently(ps);
        try {
            connection.commit();
        } catch (SQLException e) {
            LOGGER.error(e, "Failed to commit connection upon close");
        }
        closeSilently(connection);
        setState(State.CLOSED);
    }

    protected void closeSilently(final AutoCloseable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
            LOGGER.error(e, "Error closing " + closeable);
            // Just log the error. No re-throw
        }
    }

    @Override
    public String toString() {
        return getState() + " \"" + getSql() + "\" <- " + getValues();
    }

    @Override
    public String getSql() {
        return sql;
    }

    @Override
    public void setSql(String sql) {
        this.sql = requireNonNull(sql);
    }

    @Override
    public List<?> getValues() {
        return values;
    }

    @Override
    public void setValues(List<?> values) {
        this.values = requireNonNull(values);
    }

    @Override
    public Function<ResultSet, T> getRsMapper() {
        return rsMapper;
    }

    @Override
    public void setRsMapper(Function<ResultSet, T> rsMapper) {
        this.rsMapper = requireNonNull(rsMapper);
    }

    public State getState() {
        return state;
    }

    protected void setState(State state) {
        this.state = requireNonNull(state);
    }
    
    @Override
    public ParallelStrategy getParallelStrategy() {
        return parallelStrategy;
    }

    @Override
    public void setParallelStrategy(ParallelStrategy parallelStrategy) {
        this.parallelStrategy = parallelStrategy;
    }
    

}

@@ -2189,16 +2189,67 @@
 nection;
+  // null allowed if the stream() method is not run
 %0A    pri
@@ -2667,24 +2667,52 @@
 ues(values);
+ // requireNonNull in setter
 %0A        set
@@ -2726,24 +2726,52 @@
 r(rsMapper);
+ // requireNonNull in setter
 %0A        thi
@@ -3794,38 +3794,212 @@
 ly(ps);%0A        
-try %7B%0A
+commitSilently(connection);%0A        setState(State.CLOSED);%0A    %7D%0A%0A    private void commitSilently(Connection connection) %7B%0A        try %7B%0A            if (connection != null) %7B%0A    
             conn
@@ -4011,24 +4011,38 @@
 n.commit();%0A
+            %7D%0A
         %7D ca
@@ -4149,75 +4149,8 @@
   %7D%0A
-        closeSilently(connection);%0A        setState(State.CLOSED);%0A
     
@@ -4154,31 +4154,29 @@
    %7D%0A%0A    pr
-otec
+iva
 te
-d
  void closeS

Fix NullpointerException in connection commit introduced in c921b97