73 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			Plaintext
		
	
	
	
		
		
			
		
	
	
			73 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			Plaintext
		
	
	
	
|  | package com.novelbook.android.netapi; | ||
|  | 
 | ||
|  | import java.util.Random; | ||
|  | 
 | ||
|  | 
 | ||
|  | import org.json.JSONArray; | ||
|  | import org.json.JSONException; | ||
|  | import org.json.JSONObject; | ||
|  | 
 | ||
|  | public class RandomHost { | ||
|  | 
 | ||
|  | 	private static final int MAX = 5; | ||
|  | 	private static final Random random = new Random(); | ||
|  | 	//private static final Map<String, int[]> indexsMap = new HashMap<String, int[]>(); | ||
|  | 
 | ||
|  | 	private JSONObject hosts = null; | ||
|  | 	private String uri = null; | ||
|  | 	 | ||
|  | 	private int[] indexs = new int[10]; | ||
|  | 	 | ||
|  | 	public RandomHost(JSONObject hosts, String uri) throws JSONException { | ||
|  | 		this.hosts = hosts; | ||
|  | 		this.uri = uri; | ||
|  | 		String hostName = UrlFactory.getHost(uri); | ||
|  | 		indexs = new int[MAX]; | ||
|  | 		JSONArray us = hosts.getJSONArray(hostName); | ||
|  | 		int maxFixIndex = us == null ||us.length()==0 ? 0 :us.length(); | ||
|  | 		if (maxFixIndex > 0) { | ||
|  | 			randomFill(indexs, 0, 0, maxFixIndex - 1); | ||
|  | 		} | ||
|  | 		for (int i = maxFixIndex; i < MAX; i++) { | ||
|  | 			indexs[i] = i; | ||
|  | 		} | ||
|  | 		//randomFill(indexs, maxFixIndex, maxFixIndex, MAX - 1); | ||
|  | 	} | ||
|  | 	 | ||
|  | 	private static boolean in(int[] values, int maxIndex, int value) { | ||
|  | 		for (int i = 0; i <= maxIndex; i++) { | ||
|  | 			if (values[i] == value) return true; | ||
|  |  		} | ||
|  | 		 | ||
|  | 		return false; | ||
|  | 	} | ||
|  | 	 | ||
|  | 	private static void randomFill(int[] indexs, int fromIndex, int min, int max) { | ||
|  | 		for (int i = min; i <= max; i++) { | ||
|  | 			while (true) { | ||
|  | 				int value = random.nextInt(max + 1); | ||
|  | 				if (value < min) continue; | ||
|  | 				if (in(indexs, fromIndex + i - min - 1, value)) continue; | ||
|  | 				indexs[ fromIndex + i - min] = value; | ||
|  | 				break; | ||
|  | 			} | ||
|  | 		} | ||
|  | 	} | ||
|  | 	 | ||
|  | 	private int currentIndex = 0; | ||
|  | 	public String next() { | ||
|  | 		if (indexs == null || indexs.length == 0) return ""; | ||
|  | 		if (currentIndex >= indexs.length) { | ||
|  | 			return ""; | ||
|  | 		} | ||
|  | 		else { | ||
|  | 			try { | ||
|  | 				return UrlFactory.getUrl(hosts, uri, indexs[currentIndex++]); | ||
|  | 			} catch (JSONException e) { | ||
|  | 				e.printStackTrace(); | ||
|  | 			} | ||
|  | 		} | ||
|  | 		return ""; | ||
|  | 	} | ||
|  | } |