import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;

// This class uses the Babelfish translation engine to translate entered text.
public class BabelTranslate {
	public static void main(String[] args) {
		System.out.println("Enter text to translate:");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		
		String encoded = null;
		try {
			String input = in.readLine();
			encoded = URLEncoder.encode(input, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		String urlStr = "http://babelfish.yahoo.com/translate_txt";
		
		try {
			URL url = new URL(urlStr);
			URLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestProperty("User-agent", "my agent name");
			conn.setDoOutput(true);
			
			PrintStream out = new PrintStream(conn.getOutputStream());
			out.print("ei=UTF-8");
			out.print("&doit=done");
			out.print("&fr=bf-home");
			out.print("&intl=1");
			out.print("&tt=urltext");
			out.print("&trtext=" + encoded);
			out.print("&lp=en_es");
			out.close();
			
			String content = "";
			BufferedInputStream pageIn = new BufferedInputStream(conn.getInputStream());
			byte[] buffer = new byte[5000];
			while (true) {
				int length = pageIn.read(buffer);
				if (length == -1) {
					break;
				}
				content += new String(buffer, 0, length);
			}
			pageIn.close();
			
			int index = content.indexOf("<div id=\"result\">");
			
			if (index != -1) {
				int endIndex = content.indexOf("</", index + 1);
				int startIndex = content.lastIndexOf(">", endIndex);
				String translation = content.substring(startIndex + 1, endIndex);
				System.out.println("Translation: " + translation);
			} else {
				System.out.println("Translation failed.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

