/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.as.testsuite.integration.osgi;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;


/**
 * OSGi integration test support.
 *
 * @author thomas.diesler@jboss.com
 * @since 24-May-2011
 */
public abstract class OSGiTestSupport {

    /**
     * Changes the framework start level and waits for the STARTLEVEL_CHANGED event
     * Note, changing the framework start level is an asynchronous operation.
     */
    protected void changeStartLevel(BundleContext context, int level, long timeout, TimeUnit units) throws InterruptedException, TimeoutException {
        ServiceReference sref = context.getServiceReference(StartLevel.class.getName());
        StartLevel startLevel = (StartLevel) context.getService(sref);
        if (level != startLevel.getStartLevel()) {
            final CountDownLatch latch = new CountDownLatch(1);
            context.addFrameworkListener(new FrameworkListener() {
                public void frameworkEvent(FrameworkEvent event) {
                    if (event.getType() == FrameworkEvent.STARTLEVEL_CHANGED) {
                        latch.countDown();
                    }
                }
            });
            startLevel.setStartLevel(level);
            if (latch.await(timeout, units) == false)
                throw new TimeoutException("Timeout changing start level");
        }
    }

    /**
     * Use {@link PackageAdmin#getBundles(String, String)} to find a deployed bundle by
     * symbolic name and version range
     */
    protected Bundle getDeployedBundle(BundleContext context, String symbolicName, String versionRange) {
        ServiceReference sref = context.getServiceReference(PackageAdmin.class.getName());
        PackageAdmin packageAdmin = (PackageAdmin) context.getService(sref);
        Bundle[] bundles = packageAdmin.getBundles(symbolicName, versionRange);
        assertNotNull("Bundles found", bundles);
        assertEquals("One bundle found", 1, bundles.length);
        return bundles[0];
    }

    protected  String getHttpResponse(String host, int port, String reqPath, int timeout) throws IOException
    {
       int fraction = 200;

       String line = null;
       IOException lastException = null;
       while (line == null && 0 < (timeout -= fraction))
       {
          try
          {
             URL url = new URL("http://" + host + ":" + port + reqPath);
             BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
             line = br.readLine();
             br.close();
          }
          catch (IOException ex)
          {
             lastException = ex;
             try
             {
                Thread.sleep(fraction);
             }
             catch (InterruptedException ie)
             {
                // ignore
             }
          }
       }

       if (line == null && lastException != null)
          throw lastException;

       return line;
    }
}
@@ -2056,16 +2056,22 @@
 rtLevel(
+final 
 BundleCo
@@ -2084,16 +2084,22 @@
 context,
+ final
  int lev
@@ -2101,16 +2101,22 @@
 t level,
+ final
  long ti
@@ -2121,16 +2121,22 @@
 timeout,
+ final
  TimeUni
@@ -2192,32 +2192,38 @@
 ption %7B%0A        
+final 
 ServiceReference
@@ -2295,16 +2295,22 @@
         
+final 
 StartLev
@@ -2689,16 +2689,55 @@
 _CHANGED
+ && level == startLevel.getStartLevel()
 ) %7B%0A    

Fix a condition where a test that dependes on a defined start level might start too early