/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007,2008 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.cmi.internal;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.ow2.cmi.controller.server.ServerClusterViewManager;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Cmi service helper.
 * @author eyindanga
 *
 */
public final class CmiServiceHelper {

    /**
     * The cmi configuration file.
     */
    public static final String CMI_CONFIGURATION_FILE_NAME = "cmi-config.xml";
    /**
     * The logger.
     */
    private static final Log LOGGER = LogFactory.getLog(CmiServiceHelper.class);

    /**
     * Size of Buffer.
     */
    private static final int BUFFER_SIZE = 1024;

    private CmiServiceHelper() {

    }

    /**
     * Sends bundle content to the server-side manager.
     * @param clusterViewManager the server-side manager
     * @param bundle the bundle to send.
     * @return Archive Id
     * @throws FileNotFoundException bundle does'nt exist
     */
    public static String sendBundle(
            final ServerClusterViewManager clusterViewManager,
            final BundleContent bundle) throws FileNotFoundException {
        LOGGER
                .debug("Sending new load balancing archive located at '"
                        + bundle.getLocation()
                        + "' step 2: trying to transfer data array of the archive to the server-side manager");
        InputStream inputStream = null;
        String archiveId = null;
        try {
            URL url = new URL(bundle.getLocation());
            inputStream = url.openStream();
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            LOGGER
                    .error("Unable to send load balancing archive bacause:  ",
                            e1);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            LOGGER.error("Unable to send load balancing archive bacause: ", e1);
        }
        ByteArrayOutputStream baos = null;
        int len;
        try {
            byte[] buf = new byte[BUFFER_SIZE];
            baos = new ByteArrayOutputStream();
            // Read bytes
            while ((len = inputStream.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            byte[] bytesOfFile = baos.toByteArray();
            archiveId = (String) clusterViewManager.addLoadBalancingArchive(
                    bytesOfFile, bundle.getLocation(), bundle.getPolicyClasses(), bundle.getStrategyClasses());
        } catch (Exception e) {
            LOGGER.error("Unable to send load balancing archive", e);
        } finally {
            try {
                inputStream.close();
                baos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                LOGGER
                        .error(
                                " Unable to close archive or stream for file located at ",
                                bundle.getLocation());
            }
        }
        return archiveId;
    }
}
