/*
 * Copyright 2010 PC-NG Inc. All rights reserved.
 * PC-NG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nexiwave.search.client.sample;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

import org.apache.log4j.Logger;

public class ClientUtil {
	private static final Logger logger=Logger.getLogger(ClientUtil.class);

    public static interface LoopWork {
        boolean doLoopWork(int lpCount) throws Exception;
    }

    public static boolean doLoop(LoopWork work, long maxWaitInMS) throws Exception {
        long startedAt = System.currentTimeMillis();
        long interval=20000;
        int count = 0;
        while (true) {
            if (work.doLoopWork(count)) {
                logger.info("No more looping.");
                return true;
            }

            if (System.currentTimeMillis() - startedAt > maxWaitInMS) {
                throw new RuntimeException("Failed to exit the loop within configured time.");
            }

            logger.info("Loop: Entering sleep for " + (interval / 1000) + "s...");
            Thread.sleep(interval);

            logger.info("Wake up from sleep. Invoking...");
            count++;
        }
    }

	public static String get(String url)throws Exception{
		
		System.out.println("Invoking "+url);
		
		URL u=new URL(url);
		URLConnection conn=u.openConnection();
		conn.setReadTimeout((int)300000);
		InputStream in=conn.getInputStream();
		try{
			byte[] buf=new byte[512];
			int len;
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			while ((len = in.read(buf)) >= 0) {
				out.write(buf, 0, len);
			}
			String s=new String(out.toByteArray());
			out.close();
			System.out.println("Respionse: |"+s+"|");
			
			String lowerStr=s.toLowerCase();
			if(lowerStr.indexOf("soapenv:reason")>=0){
				throw new RuntimeException("RESTful response for "+url+" has error.");
			}
			if(lowerStr.indexOf("exception")>=0){
				throw new RuntimeException("RESTful response has error.");
			}
			if(lowerStr.indexOf("axisbfault")>=0){
				throw new RuntimeException("RESTful response has error.");
			}
			
			
			return s;
		}
		finally{
			in.close();
		}
	}

	public static XMLStreamReader toXMLStreamReader(String s)throws Exception{
		XMLInputFactory factory=XMLInputFactory.newInstance();
		XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(s));
		
		return reader;
	}
}
