Usuário:SandroHcBot/Código Fonte/Utils

De RuneScape Wiki
Ir para: navegação, pesquisa

Utilidade de suporte de métodos para outras classes.

/*--------------------------------------------------------
 * AmauriceBot - RuneScape Wikia update task robot
 * Copyright (c) 2009-2012  Maurice Abraham.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contributors:
 *   None
 *------------------------------------------------------*/

package amauricebot;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Description(summary = "Utilidade de suporte de métodos para outras classes.")
public class Utils {
	private static ArrayList<String> s_logList = new ArrayList<String>();
	private final static int LOG_LIMIT = 100;

	private static Pattern m_cookiePattern = Pattern.compile("([^=]+)=([^;]*).*");

	public static String getInternetPage(String url, String post, HashMap<String, String> cookieStore) throws IOException {
		// In case of briefly lost connection, try 10 times
		for (int tries = 1; true; tries++) {
			URL theURL = new URL(url);

			try {
				HttpURLConnection connection = (HttpURLConnection) theURL.openConnection();
				connection.setConnectTimeout(30 * 1000); // 30 seconds
				connection.setReadTimeout(120 * 1000); // 120 seconds
				connection.setDoInput(true);
				connection.setAllowUserInteraction(false);

				prepareInternetRequest(connection, post, cookieStore);

				return processInternetReply(connection, cookieStore);
			} catch (IOException e) {
				if (tries > 10 || e.toString().contains("Error 404"))
					throw e; // too many tries, so give up

				System.err.println("Erro de conexão '" + theURL.getHost() + "': " + e.toString() + " (#" + tries + " tentativas)");

				try {
					int delay = (tries + 5) * 1000;
					Thread.sleep(delay);
				} catch (Exception ex) { }
			}
		}
	}

	private static void prepareInternetRequest(HttpURLConnection connection,
			String post, HashMap<String, String> cookieStore)
			throws IOException {
		connection.setRequestProperty("User-Agent", "AmauriceBot/1.0 (compatible; Windows XP)");
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

		if (cookieStore != null) {
			StringBuilder cookieList = new StringBuilder();
			for (String name : cookieStore.keySet()) {
				if (cookieList.length() > 0)
					cookieList.append("; ");
				cookieList.append(name).append("=")
						.append(cookieStore.get(name));
			}
			connection.setRequestProperty("Cookie", cookieList.toString());
		}

		if (post != null) {
			byte[] postBytes = post.getBytes("utf-8");
			String postLen = Integer.toString(postBytes.length);

			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-length", postLen);
			connection.setDoOutput(true);

			OutputStream out = connection.getOutputStream();
			try {
				out.write(postBytes);
				out.flush();
			} finally {
				out.close();
			}
		}
	}

	private static String processInternetReply(HttpURLConnection connection,
			HashMap<String, String> cookieStore) throws IOException {
		int status = connection.getResponseCode();
		if (status != 200)
			throw new IOException("HTTP Status Error " + status);

		if (cookieStore != null) {
			for (int i = 0; true; i++) {
				String fieldName = connection.getHeaderFieldKey(i);
				String fieldValue = connection.getHeaderField(i);
				if (fieldName == null && fieldValue == null)
					break;

				if ("Set-Cookie".equalsIgnoreCase(fieldName)) {
					String[] toks = Utils.extract(m_cookiePattern, fieldValue);
					if (toks != null)
						cookieStore.put(toks[1], toks[2]);
				}
			}
		}

		String reply = "";
		InputStream in = connection.getInputStream();
		try {
			int replyLen = connection.getContentLength();
			if (replyLen >= 0) {
				// we know the length, so could be reusing connection
				byte[] replyBuf = new byte[replyLen];
				int numRead = 0;
				while (numRead < replyLen) {
					int res = in.read(replyBuf, numRead, replyLen - numRead);
					if (res < 0)
						throw new IOException("Unexpected EOF");
					numRead += res;
				}
				reply = new String(replyBuf, "utf-8");
			} else {
				// web server didn't send content length
				StringBuilder replyBuf = new StringBuilder();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in, "utf-8"));
				int c;
				while ((c = reader.read()) != -1) {
					replyBuf.append((char) c);
				}
				reply = replyBuf.toString();
			}
		} finally {
			in.close();
		}

		return reply;
	}

	public static String[] extract(Pattern pattern, String str) {
		if (str == null)
			return null;

		Matcher matcher = pattern.matcher(str);
		if (matcher.find()) {
			int totalGroups = matcher.groupCount() + 1;
			String[] subStrs = new String[totalGroups];
			for (int i = 0; i < totalGroups; i++) {
				subStrs[i] = matcher.group(i);
			}
			return subStrs;
		}
		return null;
	}

	public static String decodeEntities(String str) {
		if (str == null || !str.contains("&"))
			return str;

		return str.replaceAll("&#039;", "'").replaceAll("&apos;", "'")
				.replaceAll("&lt;", "<").replaceAll("&gt;", ">")
				.replaceAll("&quot;", "\"").replaceAll("&amp;", "&"); // &amp; should be last
	}

	public static double parseDouble(String numStr, String unitStr,
			double notNumber) {
		if (numStr == null | numStr.length() == 0)
			return 0;

		double num;
		try {
			num = Double.parseDouble(numStr.replaceAll("[, ]", ""));
		} catch (Exception ex) {
			return notNumber;
		}

		if (unitStr != null) {
			if (unitStr.contains("k"))
				num *= 1000;
			if (unitStr.contains("m"))
				num *= 1000000;
			if (unitStr.contains("b"))
				num *= 1000000000L;
		}

		return num;
	}

	public static long parseNum(String numStr, String unitStr, long notNumber) {
		return (long) (parseDouble(numStr, unitStr, notNumber) + 0.5);
	}

	public static String formatNum(long num) {
		NumberFormat fmt = NumberFormat.getIntegerInstance(Locale.UK);
		return fmt.format(num);
	}

	public static void log(String msg) {
		System.out.println(msg);

		if (s_logList.size() < 2 * LOG_LIMIT) {
			s_logList.add(msg);
		}
	}

	public static boolean excessiveLog() {
		return s_logList.size() >= LOG_LIMIT;
	}

	public static List<String> getLogList() {
		return s_logList;
	}

	public static long ageDays(Date when) {
		long age = System.currentTimeMillis()
				- (when != null ? when.getTime() : 0);

		// round up if within 6 hours
		long days = ((age / 3600000) + 6) / 24;

		return days;
	}
}