Got it working with JSP

Discussion in 'Co-op Advertising Network' started by twi010, Dec 17, 2004.

  1. #1
    Hi,

    I put some effort into making it work with websites based on JSP. (I hope it's not against the terms of service)

    implement this class:

    
    /*
     * Created on Dec 18, 2004
     */
    package coop.techunity.de;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Vector;
    
    /**
     * @author Thomas Lange www.techunity.de
     */
    public class CoOp {
    	private static Vector ads = new Vector();
    	private static long lastAd = 0;
    
    	/**
    	 * Get one ad from remote ad server
    	 * @return
    	 */
    	private static String getAd() {
    		String url = "http://ads.digitalpoint.com/network.php?s=www.yourdomainDOTcom&type=link";
    		URL urlURL;
    		try {
    			urlURL = new URL(url);
    		} catch (MalformedURLException e1) {
    			System.out.println("Malformatted url");
    			e1.printStackTrace();
    			return null;
    		}
    		try {
    			URLConnection urlConnection = urlURL.openConnection();
    			BufferedReader in = new BufferedReader(
    					new InputStreamReader( urlConnection.getInputStream()));
    			String line = null;
    			String firstline = null;
    			while ((line = in.readLine()) != null) {
    				if (firstline == null) {
    					firstline = line;
    				}
    			}
    			in.close();
    			return firstline;
    		} catch (IOException e2) {
    			System.out.println("Couldn't read / send urlconnection failure");
    			e2.printStackTrace();
    			return null;
    		}
    	}
    
    	/**
    	 * get an ad to display (utilizes cache)
    	 * @return next ad as String or "" if an error occured
    	 */
    	public static String nextAd() {
    		// Less than 400 ads in cache or last update more than 900 ms ago?
    		if (ads.size() < 400 || lastAd + 900 < System.currentTimeMillis()) {
    			// Yes, get an additional new ad from the network.
    			String ad = getAd();
    			lastAd = System.currentTimeMillis();
    			if (ad != null) {
    				ads.add(ad);
    				synchronized (ads) {
    					if (ads.size() > 400) {
    						// Remove oldest ad from cache, if more than 400.
    						ads.remove(0);
    					}
    				}
    				return ad;
    			}
    			return "";
    		}
    		else {
    			// we've got enough ads in the cache already.
    			// return a random one.
    			synchronized (ads) {
    				return (String) ads.get((int)(Math.random() * ads.size()));
    			}
    		}
    	}
    
    }
    Code (markup):
    and use it in your jsp pages with

    <%=de.techunity.coop.CoOp.nextAd()>

    or implement a custom tag.

    Cheers
    Thomas
     
    twi010, Dec 17, 2004 IP