/*
*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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 org.wso2.carbon.apimgt.impl.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIManagerDatabaseException;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public final class APIMgtDBUtil {

    private static final Log log = LogFactory.getLog(APIMgtDBUtil.class);

    private static volatile DataSource dataSource = null;
    private static final String DB_CHECK_SQL = "SELECT * FROM AM_SUBSCRIBER";
    
    private static final String DATA_SOURCE_NAME = "DataSourceName";

    /**
     * Initializes the data source
     *
     * @throws APIManagementException if an error occurs while loading DB configuration
     */
    public static void initialize() throws APIManagerDatabaseException {
        if (dataSource != null) {
            return;
        }

        synchronized (APIMgtDBUtil.class) {
            if (dataSource == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Initializing data source");
                }
                APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
                        getAPIManagerConfigurationService().getAPIManagerConfiguration();
                String dataSourceName = config.getFirstProperty(DATA_SOURCE_NAME);

                if (dataSourceName != null) {
                    try {
                        Context ctx = new InitialContext();
                        dataSource = (DataSource) ctx.lookup(dataSourceName);
                    } catch (NamingException e) {
                        throw new APIManagerDatabaseException("Error while looking up the data " +
                                "source: " + dataSourceName, e);
                    }
                } else {
                    log.error(DATA_SOURCE_NAME + " not defined in api-manager.xml.");
                }
            }
            setupAPIManagerDatabase();
        }
    }

    /**
     * Creates the APIManager Database if not created already.
     *
     * @throws Exception if an error occurs while creating the APIManagerDatabase.
     */
    private static void setupAPIManagerDatabase() throws APIManagerDatabaseException {

        String value = System.getProperty("setup");
        if (value != null) {
            LocalDatabaseCreator databaseCreator = new LocalDatabaseCreator(dataSource);
            try {
                if (!databaseCreator.isDatabaseStructureCreated(DB_CHECK_SQL)) {
                    databaseCreator.createRegistryDatabase();
                } else {
                    log.info("APIManager database already exists. Not creating a new database.");
                }
            } catch (Exception e) {
                String msg = "Error in creating the APIManager database";
                log.fatal(msg,e);
                throw new APIManagerDatabaseException(msg, e);
            }
        }
    }

    /**
     * Utility method to get a new database connection
     *
     * @return Connection
     * @throws java.sql.SQLException if failed to get Connection
     */
    public static Connection getConnection() throws SQLException {
        if (dataSource != null) {
            return dataSource.getConnection();
        }
        throw new SQLException("Data source is not configured properly.");
    }

    /**
     * Utility method to close the connection streams.
     * @param preparedStatement PreparedStatement
     * @param connection Connection
     * @param resultSet ResultSet
     */
    public static void closeAllConnections(PreparedStatement preparedStatement, Connection connection,
                                           ResultSet resultSet) {
        closeConnection(connection);
        closeResultSet(resultSet);
        closeStatement(preparedStatement);
    }

    /**
     * Close Connection
     * @param dbConnection Connection
     */
    private static void closeConnection(Connection dbConnection) {
        if (dbConnection != null) {
            try {
                dbConnection.close();
            } catch (SQLException e) {
                log.warn("Database error. Could not close database connection. Continuing with " +
                        "others. - " + e.getMessage(), e);
            }
        }
    }

    /**
     * Close ResultSet
     * @param resultSet ResultSet
     */
    private static void closeResultSet(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.warn("Database error. Could not close ResultSet  - " + e.getMessage(), e);
            }
        }

    }

    /**
     * Close PreparedStatement
     * @param preparedStatement PreparedStatement
     */
    public static void closeStatement(PreparedStatement preparedStatement) {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                log.warn("Database error. Could not close PreparedStatement. Continuing with" +
                        " others. - " + e.getMessage(), e);
            }
        }

    }

    /**
     * Function converts IS to String
     * Used for handling blobs
     * @param is - The Input Stream
     * @return - The inputStream as a String
     */
    public static String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("Error occurred while reading from buffered reader.", e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing the buffered reader.", e);
                }
            }
        }
        return sb.toString();

    }
}

@@ -706,16 +706,54 @@
 utils;%0A%0A
+import org.apache.commons.io.IOUtils;%0A
 import o
@@ -942,32 +942,81 @@
 abaseException;%0A
+import org.wso2.carbon.apimgt.impl.APIConstants;%0A
 import org.wso2.
@@ -6707,102 +6707,25 @@
     
-BufferedReader br = null;%0A        StringBuilder sb = new StringBuilder();%0A%0A        String line
+String str = null
 ;%0A  
@@ -6736,17 +6736,16 @@
   try %7B%0A
-%0A
         
@@ -6752,564 +6752,163 @@
     
-b
+st
 r = 
-new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));%0A            while ((line = br.readLine()) != null) %7B%0A                sb.append(line);%0A            %7D%0A        %7D catch (IOException e) %7B%0A            log.error(%22Error occurred while reading from buffered reader.%22, e);%0A        %7D finally %7B%0A            if (br != null) %7B%0A                try %7B%0A                    br.close();%0A                %7D catch (IOException e) %7B%0A                    log.error(%22Error occurred while closing the buffered reader.%22, e);%0A                %7D%0A            %7D
+IOUtils.toString(is, %22UTF-8%22);%0A        %7D catch (IOException e) %7B%0A            log.error(%22Error occurred while converting input stream to string.%22, e);
 %0A   
@@ -6934,22 +6934,11 @@
 rn s
-b.toString();%0A
+tr;
 %0A   

fix inputStream -> String method add delimiters as well