Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Initial commit

  • Loading branch information...
commit 797914f44264c7e5110dd2c1ebb558f6443feb31 0 parents
authored
9 .classpath
... ... @@ -0,0 +1,9 @@
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<classpath>
  3 + <classpathentry kind="src" output="target/classes" path="src/main/java"/>
  4 + <classpathentry kind="src" path="src/main/test"/>
  5 + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
  6 + <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
  7 + <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
  8 + <classpathentry kind="output" path="target/classes"/>
  9 +</classpath>
2  .gitignore
... ... @@ -0,0 +1,2 @@
  1 +.settings/
  2 +target/
23 .project
... ... @@ -0,0 +1,23 @@
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<projectDescription>
  3 + <name>google-api-translate-java</name>
  4 + <comment></comment>
  5 + <projects>
  6 + </projects>
  7 + <buildSpec>
  8 + <buildCommand>
  9 + <name>org.eclipse.jdt.core.javabuilder</name>
  10 + <arguments>
  11 + </arguments>
  12 + </buildCommand>
  13 + <buildCommand>
  14 + <name>org.maven.ide.eclipse.maven2Builder</name>
  15 + <arguments>
  16 + </arguments>
  17 + </buildCommand>
  18 + </buildSpec>
  19 + <natures>
  20 + <nature>org.eclipse.jdt.core.javanature</nature>
  21 + <nature>org.maven.ide.eclipse.maven2Nature</nature>
  22 + </natures>
  23 +</projectDescription>
27 README
... ... @@ -0,0 +1,27 @@
  1 +Provides a simple, unofficial, Java client API for using Google Translate.
  2 +
  3 +Features:
  4 +=========
  5 +
  6 +Small library size - less than 50Kb.
  7 +
  8 +Uses English as an intermediate language to attempt translations between language pairings that are unsupported directly by Google Translate.
  9 +
  10 +The jar is runnable and has a very lightweight GUI to demonstrate translation functionality.
  11 +
  12 +Quickstart:
  13 +===========
  14 +
  15 +import com.google.api.translate.Language;
  16 +import com.google.api.translate.Translate;
  17 +
  18 +public class Main {
  19 + public static void main(String[] args) throws Exception {
  20 + // Set the HTTP referrer to your website address.
  21 + Translate.setHttpReferrer(/* Enter the URL of your site here */);
  22 +
  23 + String translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
  24 +
  25 + System.out.println(translatedText);
  26 + }
  27 +}
100 gt-checkstyle.xml
... ... @@ -0,0 +1,100 @@
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<!--
  3 + This configuration file was written by the eclipse-cs plugin configuration editor
  4 +-->
  5 +<!--
  6 +Checkstyle-Configuration: Quative Settings
  7 +Description:
  8 +
  9 +-->
  10 +<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
  11 +<module name="Checker">
  12 + <property name="severity" value="warning"/>
  13 + <module name="TreeWalker">
  14 + <module name="FileContentsHolder"/>
  15 + <module name="JavadocMethod"/>
  16 + <module name="JavadocType"/>
  17 + <module name="JavadocVariable"/>
  18 + <module name="JavadocStyle"/>
  19 + <module name="ConstantName"/>
  20 + <module name="LocalFinalVariableName"/>
  21 + <module name="LocalVariableName"/>
  22 + <module name="MemberName"/>
  23 + <module name="MethodName"/>
  24 + <module name="PackageName"/>
  25 + <module name="ParameterName"/>
  26 + <module name="StaticVariableName"/>
  27 + <module name="TypeName"/>
  28 + <module name="AvoidStarImport"/>
  29 + <module name="IllegalImport"/>
  30 + <module name="RedundantImport"/>
  31 + <module name="UnusedImports"/>
  32 + <module name="FileLength"/>
  33 + <module name="LineLength">
  34 + <property name="max" value="120"/>
  35 + </module>
  36 + <module name="MethodLength"/>
  37 + <module name="ParameterNumber"/>
  38 + <module name="EmptyForIteratorPad"/>
  39 + <module name="MethodParamPad"/>
  40 + <module name="NoWhitespaceAfter"/>
  41 + <module name="NoWhitespaceBefore"/>
  42 + <module name="OperatorWrap"/>
  43 + <module name="ParenPad"/>
  44 + <module name="TypecastParenPad"/>
  45 + <!-- <module name="TabCharacter"/> -->
  46 + <module name="WhitespaceAfter"/>
  47 + <module name="WhitespaceAround">
  48 + <metadata name="com.atlassw.tools.eclipse.checkstyle.comment" value="Removed generic types args spaces as looks untidy."/>
  49 + <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"/>
  50 + </module>
  51 + <module name="ModifierOrder"/>
  52 + <module name="RedundantModifier"/>
  53 + <module name="AvoidNestedBlocks"/>
  54 + <module name="EmptyBlock"/>
  55 + <module name="LeftCurly"/>
  56 + <module name="NeedBraces"/>
  57 + <module name="RightCurly"/>
  58 + <module name="AvoidInlineConditionals">
  59 + <property name="severity" value="ignore"/>
  60 + </module>
  61 + <module name="DoubleCheckedLocking"/>
  62 + <module name="EmptyStatement"/>
  63 + <module name="EqualsHashCode"/>
  64 + <module name="HiddenField"/>
  65 + <module name="IllegalInstantiation"/>
  66 + <module name="InnerAssignment"/>
  67 + <module name="MagicNumber"/>
  68 + <module name="MissingSwitchDefault"/>
  69 + <module name="RedundantThrows"/>
  70 + <module name="SimplifyBooleanExpression"/>
  71 + <module name="SimplifyBooleanReturn"/>
  72 + <module name="DesignForExtension">
  73 + <metadata name="com.atlassw.tools.eclipse.checkstyle.comment" value="Services must not have annotated methods which are final. This causes problems with Spring proxying."/>
  74 + <property name="severity" value="info"/>
  75 + </module>
  76 + <module name="FinalClass"/>
  77 + <module name="HideUtilityClassConstructor"/>
  78 + <module name="InterfaceIsType"/>
  79 + <module name="VisibilityModifier"/>
  80 + <module name="ArrayTypeStyle"/>
  81 + <module name="FinalParameters"/>
  82 + <module name="GenericIllegalRegexp">
  83 + <property name="severity" value="ignore"/>
  84 + <property name="format" value="\s+$"/>
  85 + <property name="message" value="Line has trailing spaces."/>
  86 + </module>
  87 + <module name="TodoComment"/>
  88 + <module name="UpperEll"/>
  89 + </module>
  90 + <module name="PackageHtml"/>
  91 + <module name="NewlineAtEndOfFile">
  92 + <property name="severity" value="ignore"/>
  93 + </module>
  94 + <module name="Translation"/>
  95 + <module name="SuppressionCommentFilter">
  96 + <property name="offCommentFormat" value="CHECKSTYLE OFF\: ([\w\|]+)"/>
  97 + <property name="onCommentFormat" value="CHECKSTYLE ON\: ([\w\|]+)"/>
  98 + <property name="checkFormat" value="$1"/>
  99 + </module>
  100 +</module>
39 pom.xml
... ... @@ -0,0 +1,39 @@
  1 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3 + <modelVersion>4.0.0</modelVersion>
  4 + <groupId>com.google.api</groupId>
  5 + <artifactId>google-api-translate-java</artifactId>
  6 + <version>0.93-SNAPSHOT</version>
  7 + <name>google-api-translate-java</name>
  8 + <description>A Java wrapper for the Google Translate service</description>
  9 + <dependencies>
  10 + <dependency>
  11 + <groupId>org.json</groupId>
  12 + <artifactId>json</artifactId>
  13 + <version>20090211</version>
  14 + </dependency>
  15 + </dependencies>
  16 + <build>
  17 + <plugins>
  18 + <plugin>
  19 + <artifactId>maven-compiler-plugin</artifactId>
  20 + <configuration>
  21 + <source>1.5</source>
  22 + <target>1.5</target>
  23 + </configuration>
  24 + </plugin>
  25 + <plugin>
  26 + <groupId>org.apache.maven.plugins</groupId>
  27 + <artifactId>maven-jar-plugin</artifactId>
  28 + <configuration>
  29 + <archive>
  30 + <manifest>
  31 + <addClasspath>true</addClasspath>
  32 + <mainClass>com.google.api.translate.TranslatorFrame</mainClass>
  33 + </manifest>
  34 + </archive>
  35 + </configuration>
  36 + </plugin>
  37 + </plugins>
  38 + </build>
  39 +</project>
66 src/main/java/com/google/api/Files.java
... ... @@ -0,0 +1,66 @@
  1 +/**
  2 + * Files.java
  3 + *
  4 + * Copyright (C) 2009, Richard Midwinter
  5 + *
  6 + * This file is part of google-api-translate-java.
  7 + *
  8 + * google-api-translate-java is free software: you can redistribute it and/or modify
  9 + * it under the terms of the GNU General Public License as published by
  10 + * the Free Software Foundation, either version 3 of the License, or
  11 + * (at your option) any later version.
  12 + *
  13 + * google-api-translate-java is distributed in the hope that it will be useful,
  14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16 + * GNU General Public License for more details.
  17 + *
  18 + * You should have received a copy of the GNU General Public License
  19 + * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
  20 + */
  21 +package com.google.api;
  22 +
  23 +import java.io.BufferedReader;
  24 +import java.io.BufferedWriter;
  25 +import java.io.File;
  26 +import java.io.FileReader;
  27 +import java.io.FileWriter;
  28 +import java.io.IOException;
  29 +
  30 +public class Files {
  31 +
  32 + private Files() {
  33 + }
  34 +
  35 + /**
  36 + * Writes a String to a given file.
  37 + *
  38 + * @param file The file to write to.
  39 + * @param content The text to write to the given file.
  40 + * @throws IOException Thrown on IO errors.
  41 + */
  42 + public static void write(final File file, final String content) throws IOException {
  43 + BufferedWriter bw = new BufferedWriter(new FileWriter(file));
  44 + bw.write(content);
  45 + bw.close();
  46 + }
  47 +
  48 + /**
  49 + * Reads a file to a String.
  50 + * @param file The file to read from.
  51 + * @return The content of the file as a String.
  52 + * @throws IOException Thrown on IO errors.
  53 + */
  54 + public static String read(final File file) throws IOException {
  55 + final StringBuilder sb = new StringBuilder();
  56 + String line;
  57 +
  58 + final BufferedReader br = new BufferedReader(new FileReader(file));
  59 + while ((line = br.readLine()) != null) {
  60 + sb.append(line);
  61 + sb.append('\n');
  62 + }
  63 +
  64 + return sb.toString();
  65 + }
  66 +}
151 src/main/java/com/google/api/GoogleAPI.java
... ... @@ -0,0 +1,151 @@
  1 +/**
  2 + * GoogleAPI.java
  3 + *
  4 + * Copyright (C) 2009, Richard Midwinter
  5 + *
  6 + * This file is part of google-api-translate-java.
  7 + *
  8 + * google-api-translate-java is free software: you can redistribute it and/or modify
  9 + * it under the terms of the GNU General Public License as published by
  10 + * the Free Software Foundation, either version 3 of the License, or
  11 + * (at your option) any later version.
  12 + *
  13 + * google-api-translate-java is distributed in the hope that it will be useful,
  14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16 + * GNU General Public License for more details.
  17 + *
  18 + * You should have received a copy of the GNU General Public License
  19 + * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
  20 + */
  21 +package com.google.api;
  22 +
  23 +import java.io.BufferedReader;
  24 +import java.io.InputStream;
  25 +import java.io.InputStreamReader;
  26 +import java.io.PrintWriter;
  27 +import java.net.HttpURLConnection;
  28 +import java.net.URL;
  29 +
  30 +import org.json.JSONObject;
  31 +
  32 +/**
  33 + * Makes generic Google API functionality available to specific API classes.
  34 + *
  35 + * @author Richard Midwinter
  36 + * @author Kramar Tomas
  37 + */
  38 +public abstract class GoogleAPI {
  39 +
  40 + protected static final String ENCODING = "UTF-8";
  41 +
  42 + /**
  43 + * The HTTP referrer attribute.
  44 + *
  45 + * This allows Google to distinguish between programs.
  46 + */
  47 + protected static String referrer;
  48 +
  49 + /**
  50 + * Sets the HTTP Referrer.
  51 + * @param pReferrer The HTTP referrer parameter.
  52 + */
  53 + public static void setHttpReferrer(final String pReferrer) {
  54 + referrer = pReferrer;
  55 + }
  56 +
  57 + public static void validateReferrer() throws Exception {
  58 + if (referrer == null || referrer.length() == 0) {
  59 + throw new Exception("[google-api-translate-java] Referrer is not set. Call setHttpReferrer().");
  60 + }
  61 + }
  62 +
  63 + /**
  64 + * Forms an HTTP request, sends it using GET method and returns the result of the request as a JSONObject.
  65 + *
  66 + * @param url The URL to query for a JSONObject.
  67 + * @return The translated String.
  68 + * @throws Exception on error.
  69 + */
  70 + protected static JSONObject retrieveJSON(final URL url) throws Exception {
  71 + try {
  72 + final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
  73 + uc.setRequestProperty("referer", referrer);
  74 + uc.setRequestMethod("GET");
  75 + uc.setDoOutput(true);
  76 +
  77 + try {
  78 + final String result = inputStreamToString(uc.getInputStream());
  79 +
  80 + return new JSONObject(result);
  81 + } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
  82 + uc.getInputStream().close();
  83 + if (uc.getErrorStream() != null) {
  84 + uc.getErrorStream().close();
  85 + }
  86 + }
  87 + } catch (Exception ex) {
  88 + throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
  89 + }
  90 + }
  91 +
  92 + /**
  93 + * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
  94 + *
  95 + * @param url The URL to query for a JSONObject.
  96 + * @param parameters Additional POST parameters
  97 + * @return The translated String.
  98 + * @throws Exception on error.
  99 + */
  100 + protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
  101 + try {
  102 + final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
  103 + uc.setRequestProperty("referer", referrer);
  104 + uc.setRequestMethod("POST");
  105 + uc.setDoOutput(true);
  106 +
  107 + final PrintWriter pw = new PrintWriter(uc.getOutputStream());
  108 + pw.write(parameters);
  109 + pw.flush();
  110 +
  111 + try {
  112 + final String result = inputStreamToString(uc.getInputStream());
  113 +
  114 + return new JSONObject(result);
  115 + } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
  116 + uc.getInputStream().close();
  117 + if (uc.getErrorStream() != null) {
  118 + uc.getErrorStream().close();
  119 + }
  120 + pw.close();
  121 + }
  122 + } catch (Exception ex) {
  123 + throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
  124 + }
  125 + }
  126 +
  127 + /**
  128 + * Reads an InputStream and returns its contents as a String.
  129 + * Also effects rate control.
  130 + * @param inputStream The InputStream to read from.
  131 + * @return The contents of the InputStream as a String.
  132 + * @throws Exception on error.
  133 + */
  134 + private static String inputStreamToString(final InputStream inputStream) throws Exception {
  135 + final StringBuilder outputBuilder = new StringBuilder();
  136 +
  137 + try {
  138 + String string;
  139 + if (inputStream != null) {
  140 + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
  141 + while (null != (string = reader.readLine())) {
  142 + outputBuilder.append(string).append('\n');
  143 + }
  144 + }
  145 + } catch (Exception ex) {
  146 + throw new Exception("[google-api-translate-java] Error reading translation stream.", ex);
  147 + }
  148 +
  149 + return outputBuilder.toString();
  150 + }
  151 +}
63 src/main/java/com/google/api/detect/Detect.java
... ... @@ -0,0 +1,63 @@
  1 +/**
  2 + * Detect.java
  3 + *
  4 + * Copyright (C) 2009, Richard Midwinter
  5 + *
  6 + * This file is part of google-api-translate-java.
  7 + *
  8 + * google-api-translate-java is free software: you can redistribute it and/or modify
  9 + * it under the terms of the GNU General Public License as published by
  10 + * the Free Software Foundation, either version 3 of the License, or
  11 + * (at your option) any later version.
  12 + *
  13 + * google-api-translate-java is distributed in the hope that it will be useful,
  14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16 + * GNU General Public License for more details.
  17 + *
  18 + * You should have received a copy of the GNU General Public License
  19 + * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
  20 + */
  21 +package com.google.api.detect;
  22 +
  23 +import java.net.URL;
  24 +import java.net.URLEncoder;
  25 +
  26 +import org.json.JSONObject;
  27 +
  28 +import com.google.api.GoogleAPI;
  29 +import com.google.api.translate.Language;
  30 +
  31 +/**
  32 + * Makes the Google Detect API available to Java applications.
  33 + *
  34 + * @author Richard Midwinter
  35 + * @author Soren AD <soren@tanesha.net>
  36 + */
  37 +public class Detect extends GoogleAPI {
  38 +
  39 + /**
  40 + * Constants.
  41 + */
  42 + private static String URL = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=";
  43 +
  44 + /**
  45 + * Detects the language of a supplied String.
  46 + *
  47 + * @param text The String to detect the language of.
  48 + * @return A DetectResult object containing the language, confidence and reliability.
  49 + * @throws Exception on error.
  50 + */
  51 + public static DetectResult execute(final String text) throws Exception {
  52 + validateReferrer();
  53 +
  54 + final URL url = new URL(URL +URLEncoder.encode(text, ENCODING));
  55 +
  56 + final JSONObject json = retrieveJSON(url);
  57 +
  58 + return new DetectResult(
  59 + Language.fromString(json.getJSONObject("responseData").getString("language")),
  60 + json.getJSONObject("responseData").getBoolean("isReliable"),
  61 + json.getJSONObject("responseData").getDouble("confidence"));
  62 + }
  63 +}
61 src/main/java/com/google/api/detect/DetectResult.java
... ... @@ -0,0 +1,61 @@
  1 +/**
  2 + * DetectResult.java
  3 + *
  4 + * Copyright (C) 2009, Richard Midwinter
  5 + *
  6 + * This file is part of google-api-translate-java.
  7 + *
  8 + * google-api-translate-java is free software: you can redistribute it and/or modify
  9 + * it under the terms of the GNU General Public License as published by
  10 + * the Free Software Foundation, either version 3 of the License, or
  11 + * (at your option) any later version.
  12 + *
  13 + * google-api-translate-java is distributed in the hope that it will be useful,
  14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16 + * GNU General Public License for more details.
  17 + *
  18 + * You should have received a copy of the GNU General Public License
  19 + * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
  20 + */
  21 +package com.google.api.detect;
  22 +
  23 +import com.google.api.translate.Language;
  24 +
  25 +/**
  26 + * Represents the result of a Detect query.
  27 + *
  28 + * @author Richard Midwinter
  29 + * @author Soren AD <soren@tanesha.net>
  30 + */
  31 +public class DetectResult {
  32 +
  33 + private Language language;
  34 + private boolean reliable;
  35 + private double confidence;
  36 +
  37 + public DetectResult(final Language language, final boolean reliable, final double confidence) {
  38 + this.language = language;
  39 + this.reliable = reliable;
  40 + this.confidence = confidence;
  41 + }
  42 +
  43 + public Language getLanguage() {
  44 + return language;
  45 + }
  46 + public void setLanguage(Language language) {
  47 + this.language = language;
  48 + }
  49 + public boolean isReliable() {
  50 + return reliable;
  51 + }
  52 + public void setReliable(boolean reliable) {
  53 + this.reliable = reliable;
  54 + }
  55 + public double getConfidence() {
  56 + return confidence;
  57 + }
  58 + public void setConfidence(double confidence) {
  59 + this.confidence = confidence;
  60 + }
  61 +}
153 src/main/java/com/google/api/translate/Language.java
... ... @@ -0,0 +1,153 @@
  1 +/**
  2 + * Language.java
  3 + *
  4 + * Copyright (C) 2007, Richard Midwinter
  5 + *
  6 + * This program is free software; you can redistribute it and/or
  7 + * modify it under the terms of the GNU General Public License
  8 + * as published by the Free Software Foundation; either version 2
  9 + * of the License, or (at your option) any later version.
  10 + *
  11 + * This program is distributed in the hope that it will be useful,
  12 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14 + * GNU General Public License for more details.
  15 + *
  16 + * You should have received a copy of the GNU General Public License
  17 + * along with this program. if not, write to the Free Software
  18 + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19 + */
  20 +package com.google.api.translate;
  21 +
  22 +/**
  23 + * Defines language information for the Google Translate API.
  24 + *
  25 + * @author Richard Midwinter
  26 + * @author alosii
  27 + * @author bjkuczynski
  28 + */
  29 +public enum Language {
  30 + AUTO_DETECT(""),
  31 + AFRIKAANS("af"),
  32 + ALBANIAN("sq"),
  33 + AMHARIC("am"),
  34 + ARABIC("ar"),
  35 + ARMENIAN("hy"),
  36 + AZERBAIJANI("az"),
  37 + BASQUE("eu"),
  38 + BELARUSIAN("be"),
  39 + BENGALI("bn"),
  40 + BIHARI("bh"),
  41 + BULGARIAN("bg"),
  42 + BURMESE("my"),
  43 + CATALAN("ca"),
  44 + CHEROKEE("chr"),
  45 + CHINESE("zh"),
  46 + CHINESE_SIMPLIFIED("zh-CN"),
  47 + CHINESE_TRADITIONAL("zh-TW"),
  48 + CROATIAN("hr"),
  49 + CZECH("cs"),
  50 + DANISH("da"),
  51 + DHIVEHI("dv"),
  52 + DUTCH("nl"),
  53 + ENGLISH("en"),
  54 + ESPERANTO("eo"),
  55 + ESTONIAN("et"),
  56 + FILIPINO("tl"),
  57 + FINNISH("fi"),
  58 + FRENCH("fr"),
  59 + GALICIAN("gl"),
  60 + GEORGIAN("ka"),
  61 + GERMAN("de"),
  62 + GREEK("el"),
  63 + GUARANI("gn"),
  64 + GUJARATI("gu"),
  65 + HEBREW("iw"),
  66 + HINDI("hi"),
  67 + HUNGARIAN("hu"),
  68 + ICELANDIC("is"),
  69 + INDONESIAN("id"),
  70 + INUKTITUT("iu"),
  71 + IRISH("ga"),
  72 + ITALIAN("it"),
  73 + JAPANESE("ja"),
  74 + KANNADA("kn"),
  75 + KAZAKH("kk"),
  76 + KHMER("km"),
  77 + KOREAN("ko"),
  78 + KURDISH("ku"),
  79 + KYRGYZ("ky"),
  80 + LAOTHIAN("lo"),
  81 + LATVIAN("lv"),
  82 + LITHUANIAN("lt"),
  83 + MACEDONIAN("mk"),
  84 + MALAY("ms"),
  85 + MALAYALAM("ml"),
  86 + MALTESE("mt"),
  87 + MARATHI("mr"),
  88 + MONGOLIAN("mn"),
  89 + NEPALI("ne"),
  90 + NORWEGIAN("no"),
  91 + ORIYA("or"),
  92 + PASHTO("ps"),
  93 + PERSIAN("fa"),
  94 + POLISH("pl"),
  95 + PORTUGUESE("pt"),
  96 + PUNJABI("pa"),
  97 + ROMANIAN("ro"),
  98 + RUSSIAN("ru"),
  99 + SANSKRIT("sa"),
  100 + SERBIAN("sr"),
  101 + SINDHI("sd"),
  102 + SINHALESE("si"),
  103 + SLOVAK("sk"),
  104 + SLOVENIAN("sl"),
  105 + SPANISH("es"),
  106 + SWAHILI("sw"),
  107 + SWEDISH("sv"),
  108 + TAJIK("tg"),
  109 + TAMIL("ta"),
  110 + TAGALOG("tl"),
  111 + TELUGU("te"),
  112 + THAI("th"),
  113 + TIBETAN("bo"),
  114 + TURKISH("tr"),
  115 + UKRANIAN("uk"),
  116 + URDU("ur"),
  117 + UZBEK("uz"),
  118 + UIGHUR("ug"),
  119 + VIETNAMESE("vi"),
  120 + WELSH("cy"),
  121 + YIDDISH("yi");
  122 +
  123 + /**
  124 + * Google's String representation of this language.
  125 + */
  126 + private final String language;
  127 +
  128 + /**
  129 + * Enum constructor.
  130 + * @param pLanguage The language identifier.
  131 + */
  132 + private Language(final String pLanguage) {
  133 + language = pLanguage;
  134 + }
  135 +
  136 + public static Language fromString(final String pLanguage) {
  137 + for (Language l : values()) {
  138 + if (pLanguage.equals(l.toString())) {
  139 + return l;
  140 + }
  141 + }
  142 + return null;
  143 + }
  144 +
  145 + /**
  146 + * Returns the String representation of this language.
  147 + * @return The String representation of this language.
  148 + */
  149 + @Override
  150 + public String toString() {
  151 + return language;
  152 + }
  153 +}
194 src/main/java/com/google/api/translate/Translate.java
... ... @@ -0,0 +1,194 @@
  1 +/**
  2 + * Translate.java
  3 + *
  4 + * Copyright (C) 2007, Richard Midwinter
  5 + *
  6 + * This file is part of google-api-translate-java.
  7 + *
  8 + * google-api-translate-java is free software: you can redistribute it and/or modify
  9 + * it under the terms of the GNU General Public License as published by
  10 + * the Free Software Foundation, either version 3 of the License, or
  11 + * (at your option) any later version.
  12 + *
  13 + * google-api-translate-java is distributed in the hope that it will be useful,
  14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16 + * GNU General Public License for more details.
  17 + *
  18 + * You should have received a copy of the GNU General Public License
  19 + * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
  20 + */
  21 +package com.google.api.translate;
  22 +
  23 +import java.net.URL;
  24 +import java.net.URLEncoder;
  25 +
  26 +import org.json.JSONArray;
  27 +import org.json.JSONObject;
  28 +
  29 +import com.google.api.GoogleAPI;
  30 +import com.tecnick.htmlutils.htmlentities.HTMLEntities;
  31 +
  32 +/**
  33 + * Makes the Google Translate API available to Java applications.
  34 + *
  35 + * @author Richard Midwinter
  36 + * @author Mike Nereson
  37 + * @author Emeric Vernat
  38 + * @author Juan B Cabral
  39 + * @author Kramar Tomas
  40 + */
  41 +public final class Translate extends GoogleAPI {
  42 +
  43 + /**
  44 + * Constants.
  45 + */
  46 + private static final String
  47 + LANG_PARAM = "&langpair=",
  48 + TEXT_PARAM = "&q=",
  49 + PIPE_PARAM = "%7C",
  50 + URL = "http://ajax.googleapis.com/ajax/services/language/translate",
  51 + PARAMETERS = "v=1.0&langpair=#FROM#%7C#TO#&q=";
  52 +
  53 + /**
  54 + * Translates text from a given Language to another given Language using Google Translate.
  55 + *
  56 + * @param text The String to translate.
  57 + * @param from The language code to translate from.
  58 + * @param to The language code to translate to.
  59 + * @return The translated String.
  60 + * @throws Exception on error.
  61 + */
  62 + public static String execute(final String text, final Language from, final Language to) throws Exception {
  63 + validateReferrer();
  64 +
  65 + final URL url = new URL(URL);
  66 + final String parameters = PARAMETERS.replaceAll("#FROM#", from.toString()).replaceAll("#TO#", to.toString())
  67 + +URLEncoder.encode(text, ENCODING);
  68 +
  69 + final JSONObject json = retrieveJSON(url, parameters);
  70 +
  71 + return getJSONResponse(json);
  72 + }
  73 +
  74 + /**
  75 + * Translates an array of text Strings from a given Language to another given Language using Google Translate.
  76 + *
  77 + * @param text The array of Strings to translate.
  78 + * @param from The language code to translate from.
  79 + * @param to The language code to translate to.
  80 + * @return The translated array of String results.
  81 + * @throws Exception on error.
  82 + */
  83 + public static String[] execute(final String[] text, final Language from, final Language to) throws Exception {
  84 + validateReferrer();
  85 +
  86 + final Language[] fromArgs = new Language[text.length];
  87 + final Language[] toArgs = new Language[text.length];
  88 +
  89 + for (int i = 0; i<text.length; i++) {
  90 + fromArgs[i] = from;
  91 + toArgs[i] = to;
  92 + }
  93 +
  94 + return execute(text, fromArgs, toArgs);
  95 + }
  96 +
  97 + /**
  98 + * Translates a String from a given Language to an Array of Languages using Google Translate.
  99 + *
  100 + * @param text The String to translate.
  101 + * @param from The language code to translate from.
  102 + * @param to The array of Languages to translate to.
  103 + * @return The translated array of String results.
  104 + * @throws Exception on error.
  105 + */
  106 + public static String[] execute(final String text, final Language from, final Language[] to) throws Exception {
  107 + validateReferrer();
  108 +
  109 + final String[] textArgs = new String[to.length];
  110 + final Language[] fromArgs = new Language[to.length];
  111 +
  112 + for (int i = 0; i<to.length; i++) {
  113 + textArgs[i] = text;
  114 + fromArgs[i] = from;
  115 + }
  116 +
  117 + return execute(textArgs, fromArgs, to);
  118 + }
  119 +
  120 + /**
  121 + * Translates text from a given Language to another given Language using Google Translate.
  122 + *
  123 + * @param text The array of Strings to translate.
  124 + * @param from The array of Language codes to translate from.
  125 + * @param to The array of Language codes to translate to.
  126 + * @return The translated array of String results.
  127 + * @throws Exception on error.
  128 + */
  129 + public static String[] execute(final String[] text, final Language from[], final Language[] to) throws Exception {
  130 + validateReferrer();
  131 +
  132 + if (text.length != from.length || from.length != to.length) {
  133 + throw new Exception(
  134 + "[google-api-translate-java] The same number of texts, from and to languages must be supplied.");
  135 + }
  136 +
  137 + if (text.length == 1) {
  138 + return new String[] { execute(text[0], from[0], to[0]) };
  139 + }
  140 +
  141 + final String[] responses = new String[text.length];
  142 +
  143 + final StringBuilder parametersBuilder = new StringBuilder();
  144 +
  145 + parametersBuilder.append(PARAMETERS.replaceAll("#FROM#", from[0].toString()).replaceAll("#TO#", to[0].toString()));
  146 + parametersBuilder.append(URLEncoder.encode(text[0], ENCODING));
  147 +
  148 + for (int i = 1; i<text.length; i++) {
  149 + parametersBuilder.append(LANG_PARAM);
  150 + parametersBuilder.append(from[i].toString());
  151 + parametersBuilder.append(PIPE_PARAM);
  152 + parametersBuilder.append(to[i].toString());
  153 + parametersBuilder.append(TEXT_PARAM);
  154 + parametersBuilder.append(URLEncoder.encode(text[i].toString(), ENCODING));
  155 + }
  156 +
  157 + final URL url = new URL(URL);
  158 +
  159 + final JSONArray json = retrieveJSON(url, parametersBuilder.toString()).getJSONArray("responseData");
  160 +
  161 + for (int i = 0; i<json.length(); i++) {
  162 + final JSONObject obj = json.getJSONObject(i);
  163 +
  164 + responses[i] = getJSONResponse(obj);
  165 + }
  166 +
  167 + return responses;
  168 + }
  169 +
  170 + /**
  171 + * Returns the JSON response data as a String. Throws an exception if the status is not a 200 OK.
  172 + *
  173 + * @param json The JSON object to retrieve the response data from.
  174 + * @return The responseData from the JSONObject.
  175 + * @throws Exception If the responseStatus is not 200 OK.
  176 + */
  177 + private static String getJSONResponse(final JSONObject json) throws Exception {
  178 + if (json.getString("responseStatus").equals("200")) {
  179 + final String translatedText = json.getJSONObject("responseData").getString("translatedText");
  180 + return HTMLEntities.unhtmlentities(translatedText);
  181 + } else {
  182 + throw new Exception("Google returned the following error: [" +json.getString("responseStatus") +"] "
  183 + +json.getString("responseDetails"));
  184 + }
  185 + }
  186 +
  187 + /**
  188 + * @deprecated Replaced by {@link execute()}.
  189 + */
  190 + @Deprecated
  191 + public static String translate(final String text, final Language from, final Language to) throws Exception {
  192 + return execute(text, from, to);
  193 + }
  194 +}
262 src/main/java/com/google/api/translate/TranslatorFrame.java
... ... @@ -0,0 +1,262 @@
  1 +/**
  2 + * TranslatorFrame.java
  3 + *
  4 + * Copyright (C) 2009, Richard Midwinter
  5 + *
  6 + * This file is part of google-api-translate-java.
  7 + *
  8 + * google-api-translate-java is free software: you can redistribute it and/or modify
  9 + * it under the terms of the GNU General Public License as published by
  10 + * the Free Software Foundation, either version 3 of the License, or
  11 + * (at your option) any later version.
  12 + *
  13 + * google-api-translate-java is distributed in the hope that it will be useful,
  14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16 + * GNU General Public License for more details.
  17 + *
  18 + * You should have received a copy of the GNU General Public License
  19 + * along with google-api-translate-java. If not, see <http://www.gnu.org/licenses/>.
  20 + */
  21 +package com.google.api.translate;
  22 +
  23 +/*
  24 + * TranslatorFrame.java
  25 + *
  26 + * Created on 03 February 2008, 19:47
  27 + */
  28 +import java.awt.event.ActionEvent;
  29 +import java.awt.event.ActionListener;
  30 +import java.awt.event.KeyEvent;
  31 +import java.io.File;
  32 +import java.io.IOException;
  33 +import java.util.logging.Level;
  34 +import java.util.logging.Logger;
  35 +
  36 +import javax.swing.JOptionPane;
  37 +import javax.swing.JRadioButtonMenuItem;
  38 +
  39 +import com.google.api.Files;
  40 +
  41 +/**
  42 + *
  43 + * @author rich.midwinter
  44 + */
  45 +public class TranslatorFrame extends javax.swing.JFrame {
  46 +
  47 + /**
  48 + * Serial version UID.
  49 + */
  50 + private static final long serialVersionUID = 7916697355146649532L;
  51 +
  52 + private static final String REFERRER_PATH = System.getProperty("user.home") +"/.gtReferrer";
  53 +
  54 + private Language languageFrom = Language.FRENCH;
  55 + private Language languageTo = Language.ENGLISH;
  56 +
  57 + /** Creates new form TranslatorFrame */
  58 + public TranslatorFrame() throws IOException {
  59 + initComponents();
  60 + setLocationRelativeTo(null);
  61 +
  62 + String referrer = null;
  63 +
  64 + final File ref = new File(REFERRER_PATH);
  65 + if (ref.exists()) {
  66 + referrer = Files.read(ref).trim();
  67 + } else {
  68 + referrer = (String) JOptionPane.showInputDialog(this,
  69 + "Please enter the address of your website.\n(This is just to help Google identify how their translation tools are used).",
  70 + "Website address", JOptionPane.OK_OPTION);
  71 + Files.write(ref, referrer);
  72 + }
  73 +
  74 + if (referrer.length() > 0) {
  75 + Translate.setHttpReferrer(referrer);
  76 + } else {
  77 + System.exit(1);
  78 + }
  79 + }
  80 +
  81 + private void translate() {
  82 + try {
  83 + toTextArea.setText(Translate.translate(fromTextArea.getText().trim(), languageFrom, languageTo));
  84 + } catch (Exception ex) {
  85 + Logger.getLogger(TranslatorFrame.class.getName()).log(Level.SEVERE, null, ex);
  86 + }
  87 + }
  88 +
  89 + /**
  90 + * This method is called from within the constructor to
  91 + * initialize the form.
  92 + */
  93 + private void initComponents() {
  94 + buttonGroup1 = new javax.swing.ButtonGroup();
  95 + buttonGroup2 = new javax.swing.ButtonGroup();
  96 + jPanel2 = new javax.swing.JPanel();
  97 + jScrollPane1 = new javax.swing.JScrollPane();
  98 + fromTextArea = new javax.swing.JTextArea();
  99 + jPanel3 = new javax.swing.JPanel();
  100 + jScrollPane2 = new javax.swing.JScrollPane();
  101 + toTextArea = new javax.swing.JTextArea();
  102 + jMenuBar1 = new javax.swing.JMenuBar();
  103 + jMenu1 = new javax.swing.JMenu();
  104 + jMenuItem1 = new javax.swing.JMenuItem();
  105 + jMenuTo = new javax.swing.JMenu();
  106 + jMenuFrom = new javax.swing.JMenu();
  107 +
  108 + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  109 + setTitle("Translator");
  110 + getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));
  111 +
  112 + fromTextArea.setColumns(20);
  113 + fromTextArea.setLineWrap(true);
  114 + fromTextArea.setRows(5);
  115 + fromTextArea.setWrapStyleWord(true);
  116 + fromTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
  117 + public void keyPressed(java.awt.event.KeyEvent evt) {
  118 + fromTextAreaKeyPressed(evt);
  119 + }
  120 + });
  121 + jScrollPane1.setViewportView(fromTextArea);
  122 +
  123 + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
  124 + jPanel2.setLayout(jPanel2Layout);
  125 + jPanel2Layout.setHorizontalGroup(
  126 + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  127 + .addGroup(jPanel2Layout.createSequentialGroup()
  128 + .addContainerGap()
  129 + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
  130 + .addContainerGap())
  131 + );
  132 + jPanel2Layout.setVerticalGroup(
  133 + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  134 + .addGroup(jPanel2Layout.createSequentialGroup()
  135 + .addContainerGap()
  136 + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
  137 + .addContainerGap())
  138 + );
  139 +
  140 + getContentPane().add(jPanel2);
  141 +
  142 + toTextArea.setColumns(20);
  143 + toTextArea.setEditable(false);
  144 + toTextArea.setLineWrap(true);
  145 + toTextArea.setRows(5);
  146 + toTextArea.setWrapStyleWord(true);
  147 + jScrollPane2.setViewportView(toTextArea);
  148 +
  149 + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
  150 + jPanel3.setLayout(jPanel3Layout);
  151 + jPanel3Layout.setHorizontalGroup(
  152 + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  153 + .addGroup(jPanel3Layout.createSequentialGroup()
  154 + .addContainerGap()
  155 + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
  156 + .addContainerGap())
  157 + );
  158 + jPanel3Layout.setVerticalGroup(
  159 + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  160 + .addGroup(jPanel3Layout.createSequentialGroup()
  161 + .addContainerGap()
  162 + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
  163 + .addContainerGap())
  164 + );
  165 +
  166 + getContentPane().add(jPanel3);
  167 +
  168 + jMenu1.setText("File");
  169 +
  170 + jMenuItem1.setText("Exit");
  171 + jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
  172 + public void actionPerformed(java.awt.event.ActionEvent evt) {
  173 + jMenuItem1ActionPerformed(evt);
  174 + }
  175 + });
  176 + jMenu1.add(jMenuItem1);
  177 +
  178 + jMenuBar1.add(jMenu1);
  179 +
  180 + jMenuFrom.setText("From");
  181 + jMenuTo.setText("To");
  182 +
  183 + for (final Language language : Language.values()) {