Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit 797914f44264c7e5110dd2c1ebb558f6443feb31 0 parents
@richmidwinter authored
9 .classpath
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" output="target/classes" path="src/main/java"/>
+ <classpathentry kind="src" path="src/main/test"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
2  .gitignore
@@ -0,0 +1,2 @@
+.settings/
+target/
23 .project
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>google-api-translate-java</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.maven.ide.eclipse.maven2Builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.maven.ide.eclipse.maven2Nature</nature>
+ </natures>
+</projectDescription>
27 README
@@ -0,0 +1,27 @@
+Provides a simple, unofficial, Java client API for using Google Translate.
+
+Features:
+=========
+
+Small library size - less than 50Kb.
+
+Uses English as an intermediate language to attempt translations between language pairings that are unsupported directly by Google Translate.
+
+The jar is runnable and has a very lightweight GUI to demonstrate translation functionality.
+
+Quickstart:
+===========
+
+import com.google.api.translate.Language;
+import com.google.api.translate.Translate;
+
+public class Main {
+ public static void main(String[] args) throws Exception {
+ // Set the HTTP referrer to your website address.
+ Translate.setHttpReferrer(/* Enter the URL of your site here */);
+
+ String translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
+
+ System.out.println(translatedText);
+ }
+}
100 gt-checkstyle.xml
@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ This configuration file was written by the eclipse-cs plugin configuration editor
+-->
+<!--
+Checkstyle-Configuration: Quative Settings
+Description:
+
+-->
+<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
+<module name="Checker">
+ <property name="severity" value="warning"/>
+ <module name="TreeWalker">
+ <module name="FileContentsHolder"/>
+ <module name="JavadocMethod"/>
+ <module name="JavadocType"/>
+ <module name="JavadocVariable"/>
+ <module name="JavadocStyle"/>
+ <module name="ConstantName"/>
+ <module name="LocalFinalVariableName"/>
+ <module name="LocalVariableName"/>
+ <module name="MemberName"/>
+ <module name="MethodName"/>
+ <module name="PackageName"/>
+ <module name="ParameterName"/>
+ <module name="StaticVariableName"/>
+ <module name="TypeName"/>
+ <module name="AvoidStarImport"/>
+ <module name="IllegalImport"/>
+ <module name="RedundantImport"/>
+ <module name="UnusedImports"/>
+ <module name="FileLength"/>
+ <module name="LineLength">
+ <property name="max" value="120"/>
+ </module>
+ <module name="MethodLength"/>
+ <module name="ParameterNumber"/>
+ <module name="EmptyForIteratorPad"/>
+ <module name="MethodParamPad"/>
+ <module name="NoWhitespaceAfter"/>
+ <module name="NoWhitespaceBefore"/>
+ <module name="OperatorWrap"/>
+ <module name="ParenPad"/>
+ <module name="TypecastParenPad"/>
+ <!-- <module name="TabCharacter"/> -->
+ <module name="WhitespaceAfter"/>
+ <module name="WhitespaceAround">
+ <metadata name="com.atlassw.tools.eclipse.checkstyle.comment" value="Removed generic types args spaces as looks untidy."/>
+ <property name="tokens" value="ASSIGN,BAND,BAND_ASSIGN,BOR,BOR_ASSIGN,BSR,BSR_ASSIGN,BXOR,BXOR_ASSIGN,COLON,DIV,DIV_ASSIGN,EQUAL,GE,GT,LAND,LCURLY,LE,LITERAL_ASSERT,LITERAL_CATCH,LITERAL_DO,LITERAL_ELSE,LITERAL_FINALLY,LITERAL_FOR,LITERAL_IF,LITERAL_RETURN,LITERAL_SYNCHRONIZED,LITERAL_TRY,LITERAL_WHILE,LOR,LT,MINUS,MINUS_ASSIGN,MOD,MOD_ASSIGN,NOT_EQUAL,PLUS,PLUS_ASSIGN,QUESTION,RCURLY,SL,SLIST,SL_ASSIGN,SR,SR_ASSIGN,STAR,STAR_ASSIGN,LITERAL_ASSERT,TYPE_EXTENSION_AND,WILDCARD_TYPE"/>
+ </module>
+ <module name="ModifierOrder"/>
+ <module name="RedundantModifier"/>
+ <module name="AvoidNestedBlocks"/>
+ <module name="EmptyBlock"/>
+ <module name="LeftCurly"/>
+ <module name="NeedBraces"/>
+ <module name="RightCurly"/>
+ <module name="AvoidInlineConditionals">
+ <property name="severity" value="ignore"/>
+ </module>
+ <module name="DoubleCheckedLocking"/>
+ <module name="EmptyStatement"/>
+ <module name="EqualsHashCode"/>
+ <module name="HiddenField"/>
+ <module name="IllegalInstantiation"/>
+ <module name="InnerAssignment"/>
+ <module name="MagicNumber"/>
+ <module name="MissingSwitchDefault"/>
+ <module name="RedundantThrows"/>
+ <module name="SimplifyBooleanExpression"/>
+ <module name="SimplifyBooleanReturn"/>
+ <module name="DesignForExtension">
+ <metadata name="com.atlassw.tools.eclipse.checkstyle.comment" value="Services must not have annotated methods which are final. This causes problems with Spring proxying."/>
+ <property name="severity" value="info"/>
+ </module>
+ <module name="FinalClass"/>
+ <module name="HideUtilityClassConstructor"/>
+ <module name="InterfaceIsType"/>
+ <module name="VisibilityModifier"/>
+ <module name="ArrayTypeStyle"/>
+ <module name="FinalParameters"/>
+ <module name="GenericIllegalRegexp">
+ <property name="severity" value="ignore"/>
+ <property name="format" value="\s+$"/>
+ <property name="message" value="Line has trailing spaces."/>
+ </module>
+ <module name="TodoComment"/>
+ <module name="UpperEll"/>
+ </module>
+ <module name="PackageHtml"/>
+ <module name="NewlineAtEndOfFile">
+ <property name="severity" value="ignore"/>
+ </module>
+ <module name="Translation"/>
+ <module name="SuppressionCommentFilter">
+ <property name="offCommentFormat" value="CHECKSTYLE OFF\: ([\w\|]+)"/>
+ <property name="onCommentFormat" value="CHECKSTYLE ON\: ([\w\|]+)"/>
+ <property name="checkFormat" value="$1"/>
+ </module>
+</module>
39 pom.xml
@@ -0,0 +1,39 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>com.google.api</groupId>
+ <artifactId>google-api-translate-java</artifactId>
+ <version>0.93-SNAPSHOT</version>
+ <name>google-api-translate-java</name>
+ <description>A Java wrapper for the Google Translate service</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ <version>20090211</version>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ <mainClass>com.google.api.translate.TranslatorFrame</mainClass>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
66 src/main/java/com/google/api/Files.java
@@ -0,0 +1,66 @@
+/**
+ * Files.java
+ *
+ * Copyright (C) 2009, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+
+public class Files {
+
+ private Files() {
+ }
+
+ /**
+ * Writes a String to a given file.
+ *
+ * @param file The file to write to.
+ * @param content The text to write to the given file.
+ * @throws IOException Thrown on IO errors.
+ */
+ public static void write(final File file, final String content) throws IOException {
+ BufferedWriter bw = new BufferedWriter(new FileWriter(file));
+ bw.write(content);
+ bw.close();
+ }
+
+ /**
+ * Reads a file to a String.
+ * @param file The file to read from.
+ * @return The content of the file as a String.
+ * @throws IOException Thrown on IO errors.
+ */
+ public static String read(final File file) throws IOException {
+ final StringBuilder sb = new StringBuilder();
+ String line;
+
+ final BufferedReader br = new BufferedReader(new FileReader(file));
+ while ((line = br.readLine()) != null) {
+ sb.append(line);
+ sb.append('\n');
+ }
+
+ return sb.toString();
+ }
+}
151 src/main/java/com/google/api/GoogleAPI.java
@@ -0,0 +1,151 @@
+/**
+ * GoogleAPI.java
+ *
+ * Copyright (C) 2009, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+import org.json.JSONObject;
+
+/**
+ * Makes generic Google API functionality available to specific API classes.
+ *
+ * @author Richard Midwinter
+ * @author Kramar Tomas
+ */
+public abstract class GoogleAPI {
+
+ protected static final String ENCODING = "UTF-8";
+
+ /**
+ * The HTTP referrer attribute.
+ *
+ * This allows Google to distinguish between programs.
+ */
+ protected static String referrer;
+
+ /**
+ * Sets the HTTP Referrer.
+ * @param pReferrer The HTTP referrer parameter.
+ */
+ public static void setHttpReferrer(final String pReferrer) {
+ referrer = pReferrer;
+ }
+
+ public static void validateReferrer() throws Exception {
+ if (referrer == null || referrer.length() == 0) {
+ throw new Exception("[google-api-translate-java] Referrer is not set. Call setHttpReferrer().");
+ }
+ }
+
+ /**
+ * Forms an HTTP request, sends it using GET method and returns the result of the request as a JSONObject.
+ *
+ * @param url The URL to query for a JSONObject.
+ * @return The translated String.
+ * @throws Exception on error.
+ */
+ protected static JSONObject retrieveJSON(final URL url) throws Exception {
+ try {
+ final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
+ uc.setRequestProperty("referer", referrer);
+ uc.setRequestMethod("GET");
+ uc.setDoOutput(true);
+
+ try {
+ final String result = inputStreamToString(uc.getInputStream());
+
+ return new JSONObject(result);
+ } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
+ uc.getInputStream().close();
+ if (uc.getErrorStream() != null) {
+ uc.getErrorStream().close();
+ }
+ }
+ } catch (Exception ex) {
+ throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
+ }
+ }
+
+ /**
+ * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
+ *
+ * @param url The URL to query for a JSONObject.
+ * @param parameters Additional POST parameters
+ * @return The translated String.
+ * @throws Exception on error.
+ */
+ protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
+ try {
+ final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
+ uc.setRequestProperty("referer", referrer);
+ uc.setRequestMethod("POST");
+ uc.setDoOutput(true);
+
+ final PrintWriter pw = new PrintWriter(uc.getOutputStream());
+ pw.write(parameters);
+ pw.flush();
+
+ try {
+ final String result = inputStreamToString(uc.getInputStream());
+
+ return new JSONObject(result);
+ } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
+ uc.getInputStream().close();
+ if (uc.getErrorStream() != null) {
+ uc.getErrorStream().close();
+ }
+ pw.close();
+ }
+ } catch (Exception ex) {
+ throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
+ }
+ }
+
+ /**
+ * Reads an InputStream and returns its contents as a String.
+ * Also effects rate control.
+ * @param inputStream The InputStream to read from.
+ * @return The contents of the InputStream as a String.
+ * @throws Exception on error.
+ */
+ private static String inputStreamToString(final InputStream inputStream) throws Exception {
+ final StringBuilder outputBuilder = new StringBuilder();
+
+ try {
+ String string;
+ if (inputStream != null) {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
+ while (null != (string = reader.readLine())) {
+ outputBuilder.append(string).append('\n');
+ }
+ }
+ } catch (Exception ex) {
+ throw new Exception("[google-api-translate-java] Error reading translation stream.", ex);
+ }
+
+ return outputBuilder.toString();
+ }
+}
63 src/main/java/com/google/api/detect/Detect.java
@@ -0,0 +1,63 @@
+/**
+ * Detect.java
+ *
+ * Copyright (C) 2009, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api.detect;
+
+import java.net.URL;
+import java.net.URLEncoder;
+
+import org.json.JSONObject;
+
+import com.google.api.GoogleAPI;
+import com.google.api.translate.Language;
+
+/**
+ * Makes the Google Detect API available to Java applications.
+ *
+ * @author Richard Midwinter
+ * @author Soren AD <soren@tanesha.net>
+ */
+public class Detect extends GoogleAPI {
+
+ /**
+ * Constants.
+ */
+ private static String URL = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=";
+
+ /**
+ * Detects the language of a supplied String.
+ *
+ * @param text The String to detect the language of.
+ * @return A DetectResult object containing the language, confidence and reliability.
+ * @throws Exception on error.
+ */
+ public static DetectResult execute(final String text) throws Exception {
+ validateReferrer();
+
+ final URL url = new URL(URL +URLEncoder.encode(text, ENCODING));
+
+ final JSONObject json = retrieveJSON(url);
+
+ return new DetectResult(
+ Language.fromString(json.getJSONObject("responseData").getString("language")),
+ json.getJSONObject("responseData").getBoolean("isReliable"),
+ json.getJSONObject("responseData").getDouble("confidence"));
+ }
+}
61 src/main/java/com/google/api/detect/DetectResult.java
@@ -0,0 +1,61 @@
+/**
+ * DetectResult.java
+ *
+ * Copyright (C) 2009, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api.detect;
+
+import com.google.api.translate.Language;
+
+/**
+ * Represents the result of a Detect query.
+ *
+ * @author Richard Midwinter
+ * @author Soren AD <soren@tanesha.net>
+ */
+public class DetectResult {
+
+ private Language language;
+ private boolean reliable;
+ private double confidence;
+
+ public DetectResult(final Language language, final boolean reliable, final double confidence) {
+ this.language = language;
+ this.reliable = reliable;
+ this.confidence = confidence;
+ }
+
+ public Language getLanguage() {
+ return language;
+ }
+ public void setLanguage(Language language) {
+ this.language = language;
+ }
+ public boolean isReliable() {
+ return reliable;
+ }
+ public void setReliable(boolean reliable) {
+ this.reliable = reliable;
+ }
+ public double getConfidence() {
+ return confidence;
+ }
+ public void setConfidence(double confidence) {
+ this.confidence = confidence;
+ }
+}
153 src/main/java/com/google/api/translate/Language.java
@@ -0,0 +1,153 @@
+/**
+ * Language.java
+ *
+ * Copyright (C) 2007, Richard Midwinter
+ *
+ * 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 2
+ * 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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ */
+package com.google.api.translate;
+
+/**
+ * Defines language information for the Google Translate API.
+ *
+ * @author Richard Midwinter
+ * @author alosii
+ * @author bjkuczynski
+ */
+public enum Language {
+ AUTO_DETECT(""),
+ AFRIKAANS("af"),
+ ALBANIAN("sq"),
+ AMHARIC("am"),
+ ARABIC("ar"),
+ ARMENIAN("hy"),
+ AZERBAIJANI("az"),
+ BASQUE("eu"),
+ BELARUSIAN("be"),
+ BENGALI("bn"),
+ BIHARI("bh"),
+ BULGARIAN("bg"),
+ BURMESE("my"),
+ CATALAN("ca"),
+ CHEROKEE("chr"),
+ CHINESE("zh"),
+ CHINESE_SIMPLIFIED("zh-CN"),
+ CHINESE_TRADITIONAL("zh-TW"),
+ CROATIAN("hr"),
+ CZECH("cs"),
+ DANISH("da"),
+ DHIVEHI("dv"),
+ DUTCH("nl"),
+ ENGLISH("en"),
+ ESPERANTO("eo"),
+ ESTONIAN("et"),
+ FILIPINO("tl"),
+ FINNISH("fi"),
+ FRENCH("fr"),
+ GALICIAN("gl"),
+ GEORGIAN("ka"),
+ GERMAN("de"),
+ GREEK("el"),
+ GUARANI("gn"),
+ GUJARATI("gu"),
+ HEBREW("iw"),
+ HINDI("hi"),
+ HUNGARIAN("hu"),
+ ICELANDIC("is"),
+ INDONESIAN("id"),
+ INUKTITUT("iu"),
+ IRISH("ga"),
+ ITALIAN("it"),
+ JAPANESE("ja"),
+ KANNADA("kn"),
+ KAZAKH("kk"),
+ KHMER("km"),
+ KOREAN("ko"),
+ KURDISH("ku"),
+ KYRGYZ("ky"),
+ LAOTHIAN("lo"),
+ LATVIAN("lv"),
+ LITHUANIAN("lt"),
+ MACEDONIAN("mk"),
+ MALAY("ms"),
+ MALAYALAM("ml"),
+ MALTESE("mt"),
+ MARATHI("mr"),
+ MONGOLIAN("mn"),
+ NEPALI("ne"),
+ NORWEGIAN("no"),
+ ORIYA("or"),
+ PASHTO("ps"),
+ PERSIAN("fa"),
+ POLISH("pl"),
+ PORTUGUESE("pt"),
+ PUNJABI("pa"),
+ ROMANIAN("ro"),
+ RUSSIAN("ru"),
+ SANSKRIT("sa"),
+ SERBIAN("sr"),
+ SINDHI("sd"),
+ SINHALESE("si"),
+ SLOVAK("sk"),
+ SLOVENIAN("sl"),
+ SPANISH("es"),
+ SWAHILI("sw"),
+ SWEDISH("sv"),
+ TAJIK("tg"),
+ TAMIL("ta"),
+ TAGALOG("tl"),
+ TELUGU("te"),
+ THAI("th"),
+ TIBETAN("bo"),
+ TURKISH("tr"),
+ UKRANIAN("uk"),
+ URDU("ur"),
+ UZBEK("uz"),
+ UIGHUR("ug"),
+ VIETNAMESE("vi"),
+ WELSH("cy"),
+ YIDDISH("yi");
+
+ /**
+ * Google's String representation of this language.
+ */
+ private final String language;
+
+ /**
+ * Enum constructor.
+ * @param pLanguage The language identifier.
+ */
+ private Language(final String pLanguage) {
+ language = pLanguage;
+ }
+
+ public static Language fromString(final String pLanguage) {
+ for (Language l : values()) {
+ if (pLanguage.equals(l.toString())) {
+ return l;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the String representation of this language.
+ * @return The String representation of this language.
+ */
+ @Override
+ public String toString() {
+ return language;
+ }
+}
194 src/main/java/com/google/api/translate/Translate.java
@@ -0,0 +1,194 @@
+/**
+ * Translate.java
+ *
+ * Copyright (C) 2007, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api.translate;
+
+import java.net.URL;
+import java.net.URLEncoder;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+
+import com.google.api.GoogleAPI;
+import com.tecnick.htmlutils.htmlentities.HTMLEntities;
+
+/**
+ * Makes the Google Translate API available to Java applications.
+ *
+ * @author Richard Midwinter
+ * @author Mike Nereson
+ * @author Emeric Vernat
+ * @author Juan B Cabral
+ * @author Kramar Tomas
+ */
+public final class Translate extends GoogleAPI {
+
+ /**
+ * Constants.
+ */
+ private static final String
+ LANG_PARAM = "&langpair=",
+ TEXT_PARAM = "&q=",
+ PIPE_PARAM = "%7C",
+ URL = "http://ajax.googleapis.com/ajax/services/language/translate",
+ PARAMETERS = "v=1.0&langpair=#FROM#%7C#TO#&q=";
+
+ /**
+ * Translates text from a given Language to another given Language using Google Translate.
+ *
+ * @param text The String to translate.
+ * @param from The language code to translate from.
+ * @param to The language code to translate to.
+ * @return The translated String.
+ * @throws Exception on error.
+ */
+ public static String execute(final String text, final Language from, final Language to) throws Exception {
+ validateReferrer();
+
+ final URL url = new URL(URL);
+ final String parameters = PARAMETERS.replaceAll("#FROM#", from.toString()).replaceAll("#TO#", to.toString())
+ +URLEncoder.encode(text, ENCODING);
+
+ final JSONObject json = retrieveJSON(url, parameters);
+
+ return getJSONResponse(json);
+ }
+
+ /**
+ * Translates an array of text Strings from a given Language to another given Language using Google Translate.
+ *
+ * @param text The array of Strings to translate.
+ * @param from The language code to translate from.
+ * @param to The language code to translate to.
+ * @return The translated array of String results.
+ * @throws Exception on error.
+ */
+ public static String[] execute(final String[] text, final Language from, final Language to) throws Exception {
+ validateReferrer();
+
+ final Language[] fromArgs = new Language[text.length];
+ final Language[] toArgs = new Language[text.length];
+
+ for (int i = 0; i<text.length; i++) {
+ fromArgs[i] = from;
+ toArgs[i] = to;
+ }
+
+ return execute(text, fromArgs, toArgs);
+ }
+
+ /**
+ * Translates a String from a given Language to an Array of Languages using Google Translate.
+ *
+ * @param text The String to translate.
+ * @param from The language code to translate from.
+ * @param to The array of Languages to translate to.
+ * @return The translated array of String results.
+ * @throws Exception on error.
+ */
+ public static String[] execute(final String text, final Language from, final Language[] to) throws Exception {
+ validateReferrer();
+
+ final String[] textArgs = new String[to.length];
+ final Language[] fromArgs = new Language[to.length];
+
+ for (int i = 0; i<to.length; i++) {
+ textArgs[i] = text;
+ fromArgs[i] = from;
+ }
+
+ return execute(textArgs, fromArgs, to);
+ }
+
+ /**
+ * Translates text from a given Language to another given Language using Google Translate.
+ *
+ * @param text The array of Strings to translate.
+ * @param from The array of Language codes to translate from.
+ * @param to The array of Language codes to translate to.
+ * @return The translated array of String results.
+ * @throws Exception on error.
+ */
+ public static String[] execute(final String[] text, final Language from[], final Language[] to) throws Exception {
+ validateReferrer();
+
+ if (text.length != from.length || from.length != to.length) {
+ throw new Exception(
+ "[google-api-translate-java] The same number of texts, from and to languages must be supplied.");
+ }
+
+ if (text.length == 1) {
+ return new String[] { execute(text[0], from[0], to[0]) };
+ }
+
+ final String[] responses = new String[text.length];
+
+ final StringBuilder parametersBuilder = new StringBuilder();
+
+ parametersBuilder.append(PARAMETERS.replaceAll("#FROM#", from[0].toString()).replaceAll("#TO#", to[0].toString()));
+ parametersBuilder.append(URLEncoder.encode(text[0], ENCODING));
+
+ for (int i = 1; i<text.length; i++) {
+ parametersBuilder.append(LANG_PARAM);
+ parametersBuilder.append(from[i].toString());
+ parametersBuilder.append(PIPE_PARAM);
+ parametersBuilder.append(to[i].toString());
+ parametersBuilder.append(TEXT_PARAM);
+ parametersBuilder.append(URLEncoder.encode(text[i].toString(), ENCODING));
+ }
+
+ final URL url = new URL(URL);
+
+ final JSONArray json = retrieveJSON(url, parametersBuilder.toString()).getJSONArray("responseData");
+
+ for (int i = 0; i<json.length(); i++) {
+ final JSONObject obj = json.getJSONObject(i);
+
+ responses[i] = getJSONResponse(obj);
+ }
+
+ return responses;
+ }
+
+ /**
+ * Returns the JSON response data as a String. Throws an exception if the status is not a 200 OK.
+ *
+ * @param json The JSON object to retrieve the response data from.
+ * @return The responseData from the JSONObject.
+ * @throws Exception If the responseStatus is not 200 OK.
+ */
+ private static String getJSONResponse(final JSONObject json) throws Exception {
+ if (json.getString("responseStatus").equals("200")) {
+ final String translatedText = json.getJSONObject("responseData").getString("translatedText");
+ return HTMLEntities.unhtmlentities(translatedText);
+ } else {
+ throw new Exception("Google returned the following error: [" +json.getString("responseStatus") +"] "
+ +json.getString("responseDetails"));
+ }
+ }
+
+ /**
+ * @deprecated Replaced by {@link execute()}.
+ */
+ @Deprecated
+ public static String translate(final String text, final Language from, final Language to) throws Exception {
+ return execute(text, from, to);
+ }
+}
262 src/main/java/com/google/api/translate/TranslatorFrame.java
@@ -0,0 +1,262 @@
+/**
+ * TranslatorFrame.java
+ *
+ * Copyright (C) 2009, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api.translate;
+
+/*
+ * TranslatorFrame.java
+ *
+ * Created on 03 February 2008, 19:47
+ */
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.io.File;
+import java.io.IOException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.swing.JOptionPane;
+import javax.swing.JRadioButtonMenuItem;
+
+import com.google.api.Files;
+
+/**
+ *
+ * @author rich.midwinter
+ */
+public class TranslatorFrame extends javax.swing.JFrame {
+
+ /**
+ * Serial version UID.
+ */
+ private static final long serialVersionUID = 7916697355146649532L;
+
+ private static final String REFERRER_PATH = System.getProperty("user.home") +"/.gtReferrer";
+
+ private Language languageFrom = Language.FRENCH;
+ private Language languageTo = Language.ENGLISH;
+
+ /** Creates new form TranslatorFrame */
+ public TranslatorFrame() throws IOException {
+ initComponents();
+ setLocationRelativeTo(null);
+
+ String referrer = null;
+
+ final File ref = new File(REFERRER_PATH);
+ if (ref.exists()) {
+ referrer = Files.read(ref).trim();
+ } else {
+ referrer = (String) JOptionPane.showInputDialog(this,
+ "Please enter the address of your website.\n(This is just to help Google identify how their translation tools are used).",
+ "Website address", JOptionPane.OK_OPTION);
+ Files.write(ref, referrer);
+ }
+
+ if (referrer.length() > 0) {
+ Translate.setHttpReferrer(referrer);
+ } else {
+ System.exit(1);
+ }
+ }
+
+ private void translate() {
+ try {
+ toTextArea.setText(Translate.translate(fromTextArea.getText().trim(), languageFrom, languageTo));
+ } catch (Exception ex) {
+ Logger.getLogger(TranslatorFrame.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ }
+
+ /**
+ * This method is called from within the constructor to
+ * initialize the form.
+ */
+ private void initComponents() {
+ buttonGroup1 = new javax.swing.ButtonGroup();
+ buttonGroup2 = new javax.swing.ButtonGroup();
+ jPanel2 = new javax.swing.JPanel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ fromTextArea = new javax.swing.JTextArea();
+ jPanel3 = new javax.swing.JPanel();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ toTextArea = new javax.swing.JTextArea();
+ jMenuBar1 = new javax.swing.JMenuBar();
+ jMenu1 = new javax.swing.JMenu();
+ jMenuItem1 = new javax.swing.JMenuItem();
+ jMenuTo = new javax.swing.JMenu();
+ jMenuFrom = new javax.swing.JMenu();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
+ setTitle("Translator");
+ getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));
+
+ fromTextArea.setColumns(20);
+ fromTextArea.setLineWrap(true);
+ fromTextArea.setRows(5);
+ fromTextArea.setWrapStyleWord(true);
+ fromTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
+ public void keyPressed(java.awt.event.KeyEvent evt) {
+ fromTextAreaKeyPressed(evt);
+ }
+ });
+ jScrollPane1.setViewportView(fromTextArea);
+
+ javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ getContentPane().add(jPanel2);
+
+ toTextArea.setColumns(20);
+ toTextArea.setEditable(false);
+ toTextArea.setLineWrap(true);
+ toTextArea.setRows(5);
+ toTextArea.setWrapStyleWord(true);
+ jScrollPane2.setViewportView(toTextArea);
+
+ javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
+ jPanel3.setLayout(jPanel3Layout);
+ jPanel3Layout.setHorizontalGroup(
+ jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel3Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ jPanel3Layout.setVerticalGroup(
+ jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel3Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ getContentPane().add(jPanel3);
+
+ jMenu1.setText("File");
+
+ jMenuItem1.setText("Exit");
+ jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jMenuItem1ActionPerformed(evt);
+ }
+ });
+ jMenu1.add(jMenuItem1);
+
+ jMenuBar1.add(jMenu1);
+
+ jMenuFrom.setText("From");
+ jMenuTo.setText("To");
+
+ for (final Language language : Language.values()) {
+ JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem();
+ menuItem.setText(language.name());
+ if (language.equals(languageFrom)) {
+ menuItem.setSelected(true);
+ }
+ menuItem.addActionListener(new ActionListener() {
+ public void actionPerformed(final ActionEvent evt) {
+ languageFrom = language;
+ }
+ });
+ buttonGroup1.add(menuItem);
+ jMenuFrom.add(menuItem);
+
+ if (language != Language.AUTO_DETECT) {
+ menuItem = new JRadioButtonMenuItem();
+ menuItem.setText(language.name());
+ if (language.equals(languageTo)) {
+ menuItem.setSelected(true);
+ }
+ menuItem.addActionListener(new ActionListener() {
+ public void actionPerformed(final ActionEvent evt) {
+ languageTo = language;
+ }
+ });
+ buttonGroup2.add(menuItem);
+ jMenuTo.add(menuItem);
+ }
+ }
+
+ jMenuBar1.add(jMenuFrom);
+ jMenuBar1.add(jMenuTo);
+
+ setJMenuBar(jMenuBar1);
+
+ pack();
+ }
+
+ private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
+ System.exit(0);
+ }
+
+ private void fromTextAreaKeyPressed(java.awt.event.KeyEvent evt) {
+ if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
+ translate();
+ evt.consume();
+ }
+ }
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ try {
+ new TranslatorFrame().setVisible(true);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ }
+
+ // Variables declaration
+ private javax.swing.ButtonGroup buttonGroup1;
+ private javax.swing.ButtonGroup buttonGroup2;
+ private javax.swing.JTextArea fromTextArea;
+ private javax.swing.JMenu jMenu1;
+ private javax.swing.JMenu jMenuFrom;
+ private javax.swing.JMenu jMenuTo;
+ private javax.swing.JMenuBar jMenuBar1;
+ private javax.swing.JMenuItem jMenuItem1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JPanel jPanel3;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JTextArea toTextArea;
+ // End of variables declaration
+}
520 src/main/java/com/tecnick/htmlutils/htmlentities/HTMLEntities.java
@@ -0,0 +1,520 @@
+package com.tecnick.htmlutils.htmlentities;
+
+import java.util.Hashtable;
+
+/**
+ * Collection of static methods to convert special and extended
+ * characters into HTML entitities and vice versa.<br/><br/>
+ * Copyright (c) 2004-2005 Tecnick.com S.r.l (www.tecnick.com) Via Ugo Foscolo
+ * n.19 - 09045 Quartu Sant'Elena (CA) - ITALY - www.tecnick.com -
+ * info@tecnick.com<br/>
+ * Project homepage: <a href="http://htmlentities.sourceforge.net" target="_blank">http://htmlentities.sourceforge.net</a><br/>
+ * License: http://www.gnu.org/copyleft/lesser.html LGPL
+ * @author Nicola Asuni [www.tecnick.com].
+ * @version 1.0.004
+ */
+public class HTMLEntities {
+
+ /**
+ * Translation table for HTML entities.<br/>
+ * reference: W3C - Character entity references in HTML 4 [<a href="http://www.w3.org/TR/html401/sgml/entities.html" target="_blank">http://www.w3.org/TR/html401/sgml/entities.html</a>].
+ */
+ private static final Object[][] html_entities_table = {
+ { new String("&Aacute;"), new Integer(193) },
+ { new String("&aacute;"), new Integer(225) },
+ { new String("&Acirc;"), new Integer(194) },
+ { new String("&acirc;"), new Integer(226) },
+ { new String("&acute;"), new Integer(180) },
+ { new String("&AElig;"), new Integer(198) },
+ { new String("&aelig;"), new Integer(230) },
+ { new String("&Agrave;"), new Integer(192) },
+ { new String("&agrave;"), new Integer(224) },
+ { new String("&alefsym;"), new Integer(8501) },
+ { new String("&Alpha;"), new Integer(913) },
+ { new String("&alpha;"), new Integer(945) },
+ { new String("&amp;"), new Integer(38) },
+ { new String("&and;"), new Integer(8743) },
+ { new String("&ang;"), new Integer(8736) },
+ { new String("&Aring;"), new Integer(197) },
+ { new String("&aring;"), new Integer(229) },
+ { new String("&asymp;"), new Integer(8776) },
+ { new String("&Atilde;"), new Integer(195) },
+ { new String("&atilde;"), new Integer(227) },
+ { new String("&Auml;"), new Integer(196) },
+ { new String("&auml;"), new Integer(228) },
+ { new String("&bdquo;"), new Integer(8222) },
+ { new String("&Beta;"), new Integer(914) },
+ { new String("&beta;"), new Integer(946) },
+ { new String("&brvbar;"), new Integer(166) },
+ { new String("&bull;"), new Integer(8226) },
+ { new String("&cap;"), new Integer(8745) },
+ { new String("&Ccedil;"), new Integer(199) },
+ { new String("&ccedil;"), new Integer(231) },
+ { new String("&cedil;"), new Integer(184) },
+ { new String("&cent;"), new Integer(162) },
+ { new String("&Chi;"), new Integer(935) },
+ { new String("&chi;"), new Integer(967) },
+ { new String("&circ;"), new Integer(710) },
+ { new String("&clubs;"), new Integer(9827) },
+ { new String("&cong;"), new Integer(8773) },
+ { new String("&copy;"), new Integer(169) },
+ { new String("&crarr;"), new Integer(8629) },
+ { new String("&cup;"), new Integer(8746) },
+ { new String("&curren;"), new Integer(164) },
+ { new String("&dagger;"), new Integer(8224) },
+ { new String("&Dagger;"), new Integer(8225) },
+ { new String("&darr;"), new Integer(8595) },
+ { new String("&dArr;"), new Integer(8659) },
+ { new String("&deg;"), new Integer(176) },
+ { new String("&Delta;"), new Integer(916) },
+ { new String("&delta;"), new Integer(948) },
+ { new String("&diams;"), new Integer(9830) },
+ { new String("&divide;"), new Integer(247) },
+ { new String("&Eacute;"), new Integer(201) },
+ { new String("&eacute;"), new Integer(233) },
+ { new String("&Ecirc;"), new Integer(202) },
+ { new String("&ecirc;"), new Integer(234) },
+ { new String("&Egrave;"), new Integer(200) },
+ { new String("&egrave;"), new Integer(232) },
+ { new String("&empty;"), new Integer(8709) },
+ { new String("&emsp;"), new Integer(8195) },
+ { new String("&ensp;"), new Integer(8194) },
+ { new String("&Epsilon;"), new Integer(917) },
+ { new String("&epsilon;"), new Integer(949) },
+ { new String("&equiv;"), new Integer(8801) },
+ { new String("&Eta;"), new Integer(919) },
+ { new String("&eta;"), new Integer(951) },
+ { new String("&ETH;"), new Integer(208) },
+ { new String("&eth;"), new Integer(240) },
+ { new String("&Euml;"), new Integer(203) },
+ { new String("&euml;"), new Integer(235) },
+ { new String("&euro;"), new Integer(8364) },
+ { new String("&exist;"), new Integer(8707) },
+ { new String("&fnof;"), new Integer(402) },
+ { new String("&forall;"), new Integer(8704) },
+ { new String("&frac12;"), new Integer(189) },
+ { new String("&frac14;"), new Integer(188) },
+ { new String("&frac34;"), new Integer(190) },
+ { new String("&frasl;"), new Integer(8260) },
+ { new String("&Gamma;"), new Integer(915) },
+ { new String("&gamma;"), new Integer(947) },
+ { new String("&ge;"), new Integer(8805) },
+ { new String("&harr;"), new Integer(8596) },
+ { new String("&hArr;"), new Integer(8660) },
+ { new String("&hearts;"), new Integer(9829) },
+ { new String("&hellip;"), new Integer(8230) },
+ { new String("&Iacute;"), new Integer(205) },
+ { new String("&iacute;"), new Integer(237) },
+ { new String("&Icirc;"), new Integer(206) },
+ { new String("&icirc;"), new Integer(238) },
+ { new String("&iexcl;"), new Integer(161) },
+ { new String("&Igrave;"), new Integer(204) },
+ { new String("&igrave;"), new Integer(236) },
+ { new String("&image;"), new Integer(8465) },
+ { new String("&infin;"), new Integer(8734) },
+ { new String("&int;"), new Integer(8747) },
+ { new String("&Iota;"), new Integer(921) },
+ { new String("&iota;"), new Integer(953) },
+ { new String("&iquest;"), new Integer(191) },
+ { new String("&isin;"), new Integer(8712) },
+ { new String("&Iuml;"), new Integer(207) },
+ { new String("&iuml;"), new Integer(239) },
+ { new String("&Kappa;"), new Integer(922) },
+ { new String("&kappa;"), new Integer(954) },
+ { new String("&Lambda;"), new Integer(923) },
+ { new String("&lambda;"), new Integer(955) },
+ { new String("&lang;"), new Integer(9001) },
+ { new String("&laquo;"), new Integer(171) },
+ { new String("&larr;"), new Integer(8592) },
+ { new String("&lArr;"), new Integer(8656) },
+ { new String("&lceil;"), new Integer(8968) },
+ { new String("&ldquo;"), new Integer(8220) },
+ { new String("&le;"), new Integer(8804) },
+ { new String("&lfloor;"), new Integer(8970) },
+ { new String("&lowast;"), new Integer(8727) },
+ { new String("&loz;"), new Integer(9674) },
+ { new String("&lrm;"), new Integer(8206) },
+ { new String("&lsaquo;"), new Integer(8249) },
+ { new String("&lsquo;"), new Integer(8216) },
+ { new String("&macr;"), new Integer(175) },
+ { new String("&mdash;"), new Integer(8212) },
+ { new String("&micro;"), new Integer(181) },
+ { new String("&middot;"), new Integer(183) },
+ { new String("&minus;"), new Integer(8722) },
+ { new String("&Mu;"), new Integer(924) },
+ { new String("&mu;"), new Integer(956) },
+ { new String("&nabla;"), new Integer(8711) },
+ { new String("&nbsp;"), new Integer(160) },
+ { new String("&ndash;"), new Integer(8211) },
+ { new String("&ne;"), new Integer(8800) },
+ { new String("&ni;"), new Integer(8715) },
+ { new String("&not;"), new Integer(172) },
+ { new String("&notin;"), new Integer(8713) },
+ { new String("&nsub;"), new Integer(8836) },
+ { new String("&Ntilde;"), new Integer(209) },
+ { new String("&ntilde;"), new Integer(241) },
+ { new String("&Nu;"), new Integer(925) },
+ { new String("&nu;"), new Integer(957) },
+ { new String("&Oacute;"), new Integer(211) },
+ { new String("&oacute;"), new Integer(243) },
+ { new String("&Ocirc;"), new Integer(212) },
+ { new String("&ocirc;"), new Integer(244) },
+ { new String("&OElig;"), new Integer(338) },
+ { new String("&oelig;"), new Integer(339) },
+ { new String("&Ograve;"), new Integer(210) },
+ { new String("&ograve;"), new Integer(242) },
+ { new String("&oline;"), new Integer(8254) },
+ { new String("&Omega;"), new Integer(937) },
+ { new String("&omega;"), new Integer(969) },
+ { new String("&Omicron;"), new Integer(927) },
+ { new String("&omicron;"), new Integer(959) },
+ { new String("&oplus;"), new Integer(8853) },
+ { new String("&or;"), new Integer(8744) },
+ { new String("&ordf;"), new Integer(170) },
+ { new String("&ordm;"), new Integer(186) },
+ { new String("&Oslash;"), new Integer(216) },
+ { new String("&oslash;"), new Integer(248) },
+ { new String("&Otilde;"), new Integer(213) },
+ { new String("&otilde;"), new Integer(245) },
+ { new String("&otimes;"), new Integer(8855) },
+ { new String("&Ouml;"), new Integer(214) },
+ { new String("&ouml;"), new Integer(246) },
+ { new String("&para;"), new Integer(182) },
+ { new String("&part;"), new Integer(8706) },
+ { new String("&permil;"), new Integer(8240) },
+ { new String("&perp;"), new Integer(8869) },
+ { new String("&Phi;"), new Integer(934) },
+ { new String("&phi;"), new Integer(966) },
+ { new String("&Pi;"), new Integer(928) },
+ { new String("&pi;"), new Integer(960) },
+ { new String("&piv;"), new Integer(982) },
+ { new String("&plusmn;"), new Integer(177) },
+ { new String("&pound;"), new Integer(163) },
+ { new String("&prime;"), new Integer(8242) },
+ { new String("&Prime;"), new Integer(8243) },
+ { new String("&prod;"), new Integer(8719) },
+ { new String("&prop;"), new Integer(8733) },
+ { new String("&Psi;"), new Integer(936) },
+ { new String("&psi;"), new Integer(968) },
+ { new String("&quot;"), new Integer(34) },
+ { new String("&radic;"), new Integer(8730) },
+ { new String("&rang;"), new Integer(9002) },
+ { new String("&raquo;"), new Integer(187) },
+ { new String("&rarr;"), new Integer(8594) },
+ { new String("&rArr;"), new Integer(8658) },
+ { new String("&rceil;"), new Integer(8969) },
+ { new String("&rdquo;"), new Integer(8221) },
+ { new String("&real;"), new Integer(8476) },
+ { new String("&reg;"), new Integer(174) },
+ { new String("&rfloor;"), new Integer(8971) },
+ { new String("&Rho;"), new Integer(929) },
+ { new String("&rho;"), new Integer(961) },
+ { new String("&rlm;"), new Integer(8207) },
+ { new String("&rsaquo;"), new Integer(8250) },
+ { new String("&rsquo;"), new Integer(8217) },
+ { new String("&sbquo;"), new Integer(8218) },
+ { new String("&Scaron;"), new Integer(352) },
+ { new String("&scaron;"), new Integer(353) },
+ { new String("&sdot;"), new Integer(8901) },
+ { new String("&sect;"), new Integer(167) },
+ { new String("&shy;"), new Integer(173) },
+ { new String("&Sigma;"), new Integer(931) },
+ { new String("&sigma;"), new Integer(963) },
+ { new String("&sigmaf;"), new Integer(962) },
+ { new String("&sim;"), new Integer(8764) },
+ { new String("&spades;"), new Integer(9824) },
+ { new String("&sub;"), new Integer(8834) },
+ { new String("&sube;"), new Integer(8838) },
+ { new String("&sum;"), new Integer(8721) },
+ { new String("&sup1;"), new Integer(185) },
+ { new String("&sup2;"), new Integer(178) },
+ { new String("&sup3;"), new Integer(179) },
+ { new String("&sup;"), new Integer(8835) },
+ { new String("&supe;"), new Integer(8839) },
+ { new String("&szlig;"), new Integer(223) },
+ { new String("&Tau;"), new Integer(932) },
+ { new String("&tau;"), new Integer(964) },
+ { new String("&there4;"), new Integer(8756) },
+ { new String("&Theta;"), new Integer(920) },
+ { new String("&theta;"), new Integer(952) },
+ { new String("&thetasym;"), new Integer(977) },
+ { new String("&thinsp;"), new Integer(8201) },
+ { new String("&THORN;"), new Integer(222) },
+ { new String("&thorn;"), new Integer(254) },
+ { new String("&tilde;"), new Integer(732) },
+ { new String("&times;"), new Integer(215) },
+ { new String("&trade;"), new Integer(8482) },
+ { new String("&Uacute;"), new Integer(218) },
+ { new String("&uacute;"), new Integer(250) },
+ { new String("&uarr;"), new Integer(8593) },
+ { new String("&uArr;"), new Integer(8657) },
+ { new String("&Ucirc;"), new Integer(219) },
+ { new String("&ucirc;"), new Integer(251) },
+ { new String("&Ugrave;"), new Integer(217) },
+ { new String("&ugrave;"), new Integer(249) },
+ { new String("&uml;"), new Integer(168) },
+ { new String("&upsih;"), new Integer(978) },
+ { new String("&Upsilon;"), new Integer(933) },
+ { new String("&upsilon;"), new Integer(965) },
+ { new String("&Uuml;"), new Integer(220) },
+ { new String("&uuml;"), new Integer(252) },
+ { new String("&weierp;"), new Integer(8472) },
+ { new String("&Xi;"), new Integer(926) },
+ { new String("&xi;"), new Integer(958) },
+ { new String("&Yacute;"), new Integer(221) },
+ { new String("&yacute;"), new Integer(253) },
+ { new String("&yen;"), new Integer(165) },
+ { new String("&yuml;"), new Integer(255) },
+ { new String("&Yuml;"), new Integer(376) },
+ { new String("&Zeta;"), new Integer(918) },
+ { new String("&zeta;"), new Integer(950) },
+ { new String("&zwj;"), new Integer(8205) },
+ { new String("&zwnj;"), new Integer(8204) } };
+
+ /**
+ * Map to convert extended characters in html entities.
+ */
+ private static final Hashtable htmlentities_map = new Hashtable();
+
+ /**
+ * Map to convert html entities in exteden characters.
+ */
+ private static final Hashtable unhtmlentities_map = new Hashtable();
+
+ //==============================================================================
+ // METHODS
+ //==============================================================================
+
+ /**
+ * Initialize HTML translation maps.
+ */
+ public HTMLEntities() {
+ initializeEntitiesTables();
+ }
+
+ /**
+ * Initialize HTML entities table.
+ */
+ private static void initializeEntitiesTables() {
+ // initialize html translation maps
+ for (int i = 0; i < html_entities_table.length; ++i) {
+ htmlentities_map.put(html_entities_table[i][1],
+ html_entities_table[i][0]);
+ unhtmlentities_map.put(html_entities_table[i][0],
+ html_entities_table[i][1]);
+ }
+ }
+
+ /**
+ * Get the html entities translation table.
+ *
+ * @return translation table
+ */
+ public static Object[][] getEntitiesTable() {
+ return html_entities_table;
+ }
+
+ /**
+ * Convert special and extended characters into HTML entitities.
+ * @param str input string
+ * @return formatted string
+ * @see #unhtmlentities(String)
+ */
+ public static String htmlentities(String str) {
+
+ if (str == null) {
+ return "";
+ }
+ //initialize html translation maps table the first time is called
+ if (htmlentities_map.isEmpty()) {
+ initializeEntitiesTables();
+ }
+
+ StringBuffer buf = new StringBuffer(); //the otput string buffer
+
+ for (int i = 0; i < str.length(); ++i) {
+ char ch = str.charAt(i);
+ String entity = (String) htmlentities_map.get(new Integer((int) ch)); //get equivalent html entity
+ if (entity == null) { //if entity has not been found
+ if (((int) ch) > 128) { //check if is an extended character
+ buf.append("&#" + ((int) ch) + ";"); //convert extended character
+ } else {
+ buf.append(ch); //append the character as is
+ }
+ } else {
+ buf.append(entity); //append the html entity
+ }
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Convert HTML entities to special and extended unicode characters
+ * equivalents.
+ * @param str input string
+ * @return formatted string
+ * @see #htmlentities(String)
+ */
+ public static String unhtmlentities(String str) {
+
+ //initialize html translation maps table the first time is called
+ if (htmlentities_map.isEmpty()) {
+ initializeEntitiesTables();
+ }
+
+ StringBuffer buf = new StringBuffer();
+
+ for (int i = 0; i < str.length(); ++i) {
+ char ch = str.charAt(i);
+ if (ch == '&') {
+ int semi = str.indexOf(';', i + 1);
+ if ((semi == -1) || ((semi-i) > 7)){
+ buf.append(ch);
+ continue;
+ }
+ String entity = str.substring(i, semi + 1);
+ Integer iso;
+ if (entity.charAt(1) == ' ') {
+ buf.append(ch);
+ continue;
+ }
+ if (entity.charAt(1) == '#') {
+ if (entity.charAt(2) == 'x') {
+ iso = new Integer(Integer.parseInt(entity.substring(3, entity.length() - 1), 16));
+ }
+ else {
+ iso = new Integer(entity.substring(2, entity.length() - 1));
+ }
+ } else {
+ iso = (Integer) unhtmlentities_map.get(entity);
+ }
+ if (iso == null) {
+ buf.append(entity);
+ } else {
+ buf.append((char) (iso.intValue()));
+ }
+ i = semi;
+ } else {
+ buf.append(ch);
+ }
+ }
+ return buf.toString();
+ }
+
+ // methods to convert special characters
+
+ /**
+ * Replace single quotes characters with HTML entities.
+ *
+ * @param str the input string
+ * @return string with replaced single quotes
+ */
+ public static String htmlSingleQuotes(String str) {
+ str = str.replaceAll("[\']", "&rsquo;");
+ str = str.replaceAll("&#039;", "&rsquo;");
+ str = str.replaceAll("&#145;", "&rsquo;");
+ str = str.replaceAll("&#146;", "&rsquo;");
+ return str;
+ }
+
+ /**
+ * Replace single quotes HTML entities with equivalent character.
+ *
+ * @param str the input string
+ * @return string with replaced single quotes
+ */
+ public static String unhtmlSingleQuotes(String str) {
+ return str.replaceAll("&rsquo;", "\'");
+ }
+
+ /**
+ * Replace double quotes characters with HTML entities.
+ *
+ * @param str the input string
+ * @return string with replaced double quotes
+ */
+ public static String htmlDoubleQuotes(String str) {
+ str = str.replaceAll("[\"]", "&quot;");
+ str = str.replaceAll("&#147;", "&quot;");
+ str = str.replaceAll("&#148;", "&quot;");
+ return str;
+ }
+
+ /**
+ * Replace single quotes HTML entities with equivalent character.
+ *
+ * @param str the input string
+ * @return string with replaced single quotes
+ */
+ public static String unhtmlDoubleQuotes(String str) {
+ return str.replaceAll("&quot;", "\"");
+ }
+
+ /**
+ * Replace single and double quotes characters with HTML entities.
+ *
+ * @param str the input string
+ * @return string with replaced quotes
+ */
+ public static String htmlQuotes(String str) {
+ str = htmlDoubleQuotes(str); //convert double quotes
+ str = htmlSingleQuotes(str); //convert single quotes
+ return str;
+ }
+
+ /**
+ * Replace single and double quotes HTML entities with equivalent characters.
+ *
+ * @param str the input string
+ * @return string with replaced quotes
+ */
+ public static String unhtmlQuotes(String str) {
+ str = unhtmlDoubleQuotes(str); //convert double quotes
+ str = unhtmlSingleQuotes(str); //convert single quotes
+ return str;
+ }
+
+ /**
+ * Replace &lt; &gt; characters with &amp;lt; &amp;gt; entities.
+ *
+ * @param str the input string
+ * @return string with replaced characters
+ */
+ public static String htmlAngleBrackets(String str) {
+ str = str.replaceAll("<", "&lt;");
+ str = str.replaceAll(">", "&gt;");
+ return str;
+ }
+
+ /**
+ * Replace &amp;lt; &amp;gt; entities with &lt; &gt; characters.
+ *
+ * @param str the input string
+ * @return string with replaced entities
+ */
+ public static String unhtmlAngleBrackets(String str) {
+ str = str.replaceAll("&lt;", "<");
+ str = str.replaceAll("&gt;", ">");
+ return str;
+ }
+
+ /**
+ * Replace &amp; characters with &amp;amp; HTML entities.
+ *
+ * @param str the input string
+ * @return string with replaced characters
+ */
+ public static String htmlAmpersand(String str) {
+ return str.replaceAll("&", "&amp;");
+ }
+
+ /**
+ * Replace &amp;amp; HTML entities with &amp; characters.
+ *
+ * @param str the input string
+ * @return string with replaced entities
+ */
+ public static String unhtmlAmpersand(String str) {
+ return str.replaceAll("&amp;", "&");
+ }
+}
17 src/main/test/com/google/api/AllTests.java
@@ -0,0 +1,17 @@
+package com.google.api;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import com.google.api.detect.DetectTest;
+import com.google.api.translate.TranslateTest;
+
+public class AllTests {
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Test for test");
+ suite.addTestSuite(TranslateTest.class);
+ suite.addTestSuite(DetectTest.class);
+ return suite;
+ }
+}
27 src/main/test/com/google/api/detect/DetectTest.java
@@ -0,0 +1,27 @@
+package com.google.api.detect;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+import com.google.api.GoogleAPI;
+import com.google.api.detect.Detect;
+import com.google.api.detect.DetectResult;
+import com.google.api.translate.Language;
+
+/**
+ * @author Richard Midwinter
+ */
+public class DetectTest extends TestCase {
+ @Test
+ public void testDetect() throws Exception {
+ System.out.println("testDetect");
+
+ GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
+
+ DetectResult detectResult = Detect.execute("Hello world");
+
+ assertEquals(Language.ENGLISH, detectResult.getLanguage());
+ assertTrue(detectResult.getConfidence() > 0);
+ }
+}
26 src/main/test/com/google/api/translate/LoopTest.java
@@ -0,0 +1,26 @@
+/**
+ *
+ */
+package com.google.api.translate;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+/**
+ * @author Richard Midwinter
+ *
+ */
+public class LoopTest extends TestCase {
+ @Test
+ public void testTranslate() throws Exception {
+ System.out.println("testTranslate");
+
+ Translate.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
+
+ for (int i = 0; i<30; i++) {
+ System.out.println("Loop: " +i);
+ assertEquals("مرحبا العالم", Translate.execute("Hello world", Language.ENGLISH, Language.ARABIC));
+ }
+ }
+}
248 src/main/test/com/google/api/translate/TranslateTest.java
@@ -0,0 +1,248 @@
+/**
+ * TranslateTest.java
+ *
+ * Copyright (C) 2008, Richard Midwinter
+ *
+ * This file is part of google-api-translate-java.
+ *
+ * google-api-translate-java 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.
+ *
+ * google-api-translate-java 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 google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.google.api.translate;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+import com.google.api.GoogleAPI;
+
+/**
+ * @author Richard Midwinter
+ */
+public class TranslateTest extends TestCase {
+
+ @Override
+ public void setUp() {
+ GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
+ }
+
+ @Test
+ public void testHttpReferrerRequired() throws Exception {
+ System.out.println("testHttpReferrerRequired");
+
+ GoogleAPI.setHttpReferrer(null);
+
+ try {
+ Translate.execute("Hello world", Language.ENGLISH, Language.ARABIC);
+ fail("Should have thrown an error as HTTP referrer is not set.");
+ } catch (Exception e) {
+ assertEquals("[google-api-translate-java] Referrer is not set. Call setHttpReferrer().", e.getMessage());
+ }
+ }
+
+ @Test
+ public void testTranslate() throws Exception {
+ System.out.println("testTranslate");
+
+ assertEquals("مرحبا العالم", Translate.execute("Hello world", Language.ENGLISH, Language.ARABIC));
+ assertEquals("你好世界", Translate.execute("Hello world", Language.ENGLISH, Language.CHINESE));
+ assertEquals("Bonjour tout le monde", Translate.execute("Hello world", Language.ENGLISH, Language.FRENCH));
+ assertEquals("Hallo Welt", Translate.execute("Hello world", Language.ENGLISH, Language.GERMAN));
+ assertEquals("नमस्ते दुनिया", Translate.execute("Hello world", Language.ENGLISH, Language.HINDI));
+ assertEquals("Ciao a tutti", Translate.execute("Hello world", Language.ENGLISH, Language.ITALIAN));
+ assertEquals("こんにちは、世界", Translate.execute("Hello world", Language.ENGLISH, Language.JAPANESE));
+ assertEquals("안녕하세요", Translate.execute("Hello world", Language.ENGLISH, Language.KOREAN));
+ assertEquals("Olá mundo", Translate.execute("Hello world", Language.ENGLISH, Language.PORTUGUESE));
+ assertEquals("Привет мир", Translate.execute("Hello world", Language.ENGLISH, Language.RUSSIAN));
+ assertEquals("¡Hola, mundo", Translate.execute("Hello world", Language.ENGLISH, Language.SPANISH));
+ assertEquals("Hello dinja", Translate.execute("Hello world", Language.ENGLISH, Language.MALTESE));
+ assertEquals("สวัสดีชาวโลก", Translate.execute("Hello world", Language.ENGLISH, Language.THAI));
+ assertEquals("Merhaba dünya", Translate.execute("Hello world", Language.ENGLISH, Language.TURKISH));
+ assertEquals("-U-A-Π-≤ μ-C-- °-Π-Ä", Translate.execute("–ü—Ä–∏–≤–µ—Ç –º–∏—Ä", Language.RUSSIAN, Language.SPANISH));
+ assertEquals("Ciao a tutti", Translate.execute("Hallo welt", Language.GERMAN, Language.ITALIAN));
+ assertEquals("Ok", Translate.execute("Ok", Language.ENGLISH, Language.FRENCH));
+ assertEquals("Iawn", Translate.execute("Ok", Language.ENGLISH, Language.WELSH));
+
+ assertEquals("Bonjour tout le monde", Translate.execute("مرحبا العالم", Language.AUTO_DETECT, Language.FRENCH));
+ }
+
+ @Test
+ public void testUnHtmlEntities() throws Exception {
+ System.out.println("testUnHtmlEntities");
+
+ assertEquals("תעודת זהות", Translate.execute("ID", Language.ENGLISH, Language.HEBREW));
+ }
+
+ @Test
+ public void testTranslateMultipleTexts() throws Exception {
+ System.out.println("testTranslateMultipleTexts");
+
+ final String[] results = Translate.execute(new String[] {
+ "Hello world",
+ "See you soon"
+ }, Language.ENGLISH, Language.FRENCH);
+
+ assertEquals("Bonjour tout le monde", results[0]);
+ assertEquals("A bientôt", results[1]);
+ }
+
+ @Test
+ public void testTranslateMultipleLanguages() throws Exception {
+ System.out.println("testTranslateMultipleLanguages");
+
+ final String[] results = Translate.execute("Hello world", Language.ENGLISH, new Language[] {
+ Language.AFRIKAANS,
+ Language.ALBANIAN,
+ Language.ARABIC,
+ Language.BELARUSIAN,
+ Language.CATALAN,
+ Language.CHINESE,
+ Language.CHINESE_SIMPLIFIED,
+ Language.CHINESE_TRADITIONAL,
+ Language.CROATIAN,
+ Language.CZECH,
+ Language.DANISH,
+ Language.DUTCH,
+ Language.ENGLISH,
+ Language.ESTONIAN,
+ Language.FILIPINO,
+ Language.FINNISH,
+ Language.FRENCH,
+ Language.GALICIAN,
+ Language.GERMAN,
+ Language.GREEK,
+ Language.HEBREW,
+ Language.HINDI,
+ Language.HUNGARIAN,
+ Language.INDONESIAN,
+ Language.IRISH,
+ Language.ITALIAN,
+ Language.JAPANESE,
+ Language.KOREAN,
+ Language.LATVIAN,
+ Language.LITHUANIAN,
+ Language.MACEDONIAN,
+ Language.MALAY,
+ Language.MALTESE,
+ Language.NORWEGIAN,
+ Language.PERSIAN,
+ Language.POLISH,
+ Language.PORTUGUESE,
+ Language.ROMANIAN,
+ Language.RUSSIAN,
+ Language.SERBIAN,
+ Language.SLOVAK,
+ Language.SLOVENIAN,
+ Language.SPANISH,
+ Language.SWAHILI,
+ Language.SWEDISH,
+ Language.THAI,
+ Language.TURKISH,
+ Language.UKRANIAN,
+ Language.VIETNAMESE,
+ Language.WELSH,
+ Language.YIDDISH
+ });
+
+ assertEquals("Bonjour tout le monde", results[16]);
+ assertEquals("Dia duit ar domhan", results[24]);
+ assertEquals("¡Hola, mundo", results[42]);
+ }
+
+ @Test
+ public void testTranslateMultipleTextsAndLanguagesSingleEntry() throws Exception {
+ System.out.println("testTranslateMultipleTextsAndLanguagesSingleEntry");
+
+ final String[] results = Translate.execute(new String[] {
+ "Hello world"
+ }, new Language[] {
+ Language.ENGLISH
+ }, new Language[] {
+ Language.FRENCH
+ });
+
+ assertEquals("Bonjour tout le monde", results[0]);
+ }
+
+ @Test
+ public void testTranslateMultipleTextsAndLanguages() throws Exception {
+ System.out.println("testTranslateMultipleTextsAndLanguages");
+
+ final String[] results = Translate.execute(new String[] {
+ "Hello world",
+ "Hello world"
+ }, new Language[] {
+ Language.ENGLISH,
+ Language.ENGLISH
+ }, new Language[] {
+ Language.FRENCH,
+ Language.SPANISH
+ });
+
+ assertEquals("Bonjour tout le monde", results[0]);
+ }
+
+ @Test
+ public void testExample() throws Exception {
+ System.out.println("testExample");
+
+ assertEquals("Hello World", Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH));
+ }
+
+ @Test
+ public void testLarge() throws Exception {
+ System.out.println("testLarge");
+
+ Translate.execute("Figures from the Office for National Statistics (ONS) show that between December and April, "
+ + "the five-month period typically regarded as peak bonus season, those working in the financial "
+ + "intermediation sector received bonuses worth £7.6bn. The figure is more than 40pc lower than last"
+ + "year's total of £13.2bn, but the fact that it came during a period where the banking system owed its"
+ + "survival to the rescue support of taxpayers\' money will spark further outrage. Related Articles USS"
+ + "pays bonuses despite fund fall Ex-HBOS chief Hornby gives up £1m redundancyBankers blind to bonus "
+ + "'furore' Barclays and Lloyds to dish out millions in bonuses. City bonuses defy credit crunch and "
+ + "hit new record of £13bn. We are still mad with the banks but we are no closer to getting even. News"
+ + "of the huge sums being offered by Barclays to five traders at JP Morgan will also stoke the row. "
+ + "Barclays is close to poaching Todd Edgar, 37, a star commodity trader at JP Morgan, and his four "
+ + "team members to head up the foreign exchange trading desk. Mr Edgar is responsible for a $2bn book "
+ + "at JP Morgan and single-handedly made the US investment bank a $100m profit last year. At Barclays,"
+ + "the team will have an emerging markets focus, with two members based in Asia and Mr Edgar and the "
+ + "others operating out of London. They will also continue to trade commodities, but to a lesser degree"
+ + "than before. Barclays has offered the team a combined $25m in salaries and bonuses paid in cash "
+ + "guarantees and deferred stock. In addition, they will take a share of future profits that could lift"
+ + "the package to $50m. Market-leading rates on profit shares are currently 12pc, according to bankers,"
+ + "but Mr Edgar and his team are said to have been offered even more generous terms. Sources suggest Mr"
+ + "Edgar himself could receive up to half the total. It is understood the pay package does not "
+ + "contravene any of the Financial Service Authority's guidelines. At JP Morgan, Mr Edgar was largely a"
+ + "proprietary trader, gambling with the bank's own money. At Barclays, although he will take "
+ + "proprietary positions, his main role will be client business. Mr Edgar's appointment would follow "
+ + "public outrage last week over a £7m \"market leading\" deal agreed by Royal Bank of Scotland, 70pc "
+ + "owned by the taxpayer, for a Merrill Lynch banker, Antonio Polverino. Although Barclays has not "
+ + "taken any cash directly from the state, critics say it is the beneficiary of £1.2 trillion of "
+ + "taxpayer support for the financial system as a whole. Senior Treasury officials believe that the "
+ + "bank would have collapsed were it not for their assistance. In an interview this weekend, the Shadow"
+ + "Chancellor, George Osborne said it was \"totally unacceptable\" that the major banks are paying "
+ + "large bonuses on the back of taxpayer guarantees. Mr Osborne said: \"There are hundreds of billions "
+ + "of pounds of guarantees in existence: guarantees provided by the taxpayer to all banks. The reason "
+ + "those guarantees are in place is not so the bankers can pay themselves large bonuses. \"The scale of"
+ + "this year's bonus payments, as revealed by the ONS statistics, would be enough to finance an almost "
+ + "2p reduction in the basic rate of income tax. The payments came after the unprecedented bail-out of "
+ + "British banks, which cost the taxpayer some £35bn in capital infusions. Lord Oakeshott, Liberal "
+ + "Democrat Treasury spokesman, said: \"These figures suggest that the bankers are taking most of the "
+ + "profits and the taxpayer is taking most of the risk. \"The official confirmation of the scale of "
+ + "City bonuses in the past year underlines the fact that even against the backdrop of the worst "
+ + "financial crisis in British history, bankers awarded themselves bonuses which were still "
+ + "significantly larger, even in nominal terms, than those handed out five years ago in 2004, when the "
+ + "City was entering the credit boom. Barclays and JP Morgan declined to comment.",
+ Language.ENGLISH, Language.FRENCH);
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.