├── .github
└── workflows
│ └── main.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── pom.xml
└── src
├── main
└── java
│ └── com
│ └── detectlanguage
│ ├── Client.java
│ ├── DetectLanguage.java
│ ├── Result.java
│ ├── errors
│ └── APIError.java
│ └── responses
│ ├── BatchDetectResponse.java
│ ├── BatchDetectionsData.java
│ ├── DetectResponse.java
│ ├── DetectionsData.java
│ ├── ErrorData.java
│ ├── ErrorResponse.java
│ ├── Response.java
│ └── StatusResponse.java
└── test
└── java
└── com
└── detectlanguage
├── BaseTest.java
├── GenericTest.java
├── MultithreadedTest.java
├── ServerErrorTest.java
└── SslTest.java
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 | on: [push,pull_request]
3 | jobs:
4 | build-openjdk:
5 | runs-on: ubuntu-latest
6 | strategy:
7 | matrix:
8 | java-version: [ 11, 17 ]
9 | steps:
10 | - uses: actions/checkout@v3
11 | - name: Set up JDK ${{ matrix.java-version }}
12 | uses: actions/setup-java@v3
13 | with:
14 | java-version: ${{ matrix.java-version }}
15 | distribution: 'adopt'
16 | cache: 'maven'
17 | - name: Build with Maven
18 | env:
19 | DETECTLANGUAGE_API_KEY: ${{ secrets.DETECTLANGUAGE_API_KEY }}
20 | run: mvn test
21 |
22 | build-oraclejdk:
23 | runs-on: ubuntu-latest
24 | strategy:
25 | matrix:
26 | java-release: [ 17 ]
27 | steps:
28 | - uses: actions/checkout@v3
29 | - name: Set up JDK ${{ matrix.java-release }}
30 | uses: oracle-actions/setup-java@v1
31 | with:
32 | release: ${{ matrix.java-release }}
33 | - name: Build with Maven
34 | env:
35 | DETECTLANGUAGE_API_KEY: ${{ secrets.DETECTLANGUAGE_API_KEY }}
36 | run: mvn test
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # linux
2 | *~
3 |
4 | # java
5 | *.class
6 |
7 | # packages
8 | *.jar
9 | *.war
10 | *.ear
11 |
12 | # eclipse
13 | .settings
14 | .buildpath
15 | .classpath
16 | .project
17 |
18 | # logging
19 | *.log
20 |
21 | # maven
22 | target
23 |
24 |
25 | # idea
26 | .idea
27 | *.iml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2013 Laurynas Butkus
2 |
3 | MIT License
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining
6 | a copy of this software and associated documentation files (the
7 | "Software"), to deal in the Software without restriction, including
8 | without limitation the rights to use, copy, modify, merge, publish,
9 | distribute, sublicense, and/or sell copies of the Software, and to
10 | permit persons to whom the Software is furnished to do so, subject to
11 | the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be
14 | included in all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Detect Language API Java Client
2 |
3 | [](https://mvnrepository.com/artifact/com.detectlanguage/detectlanguage)
4 | [](https://github.com/detectlanguage/detectlanguage-java/actions)
5 |
6 | Detects language of the given text. Returns detected language codes and scores.
7 |
8 |
9 | ## Installation
10 |
11 | ### Maven
12 |
13 | Add this dependency to your `pom.xml`:
14 |
15 | ```xml
16 |
17 | com.detectlanguage
18 | detectlanguage
19 | 1.1.0
20 |
21 | ```
22 |
23 | ### Gradle
24 |
25 | Add this dependency to your `build.gradle`:
26 |
27 | ```gradle
28 | repositories {
29 | mavenCentral()
30 | }
31 |
32 | dependencies {
33 | compile 'com.detectlanguage:detectlanguage:1.1.0'
34 | }
35 | ```
36 |
37 | ## Usage
38 |
39 | ```java
40 | import com.detectlanguage.DetectLanguage;
41 | ```
42 |
43 | ### Configuration
44 |
45 | Before using Detect Language API client you have to setup your personal **API key**. You can get it by signing up at https://detectlanguage.com
46 |
47 | ```java
48 | DetectLanguage.apiKey = "YOURAPIKEY";
49 |
50 | // Enable secure mode (SSL) if passing sensitive information
51 | // DetectLanguage.ssl = true;
52 | ```
53 |
54 | ### Language detection
55 |
56 | ```java
57 | List results = DetectLanguage.detect("Hello world");
58 |
59 | Result result = results.get(0);
60 |
61 | System.out.println("Language: " + result.language);
62 | System.out.println("Is reliable: " + result.isReliable);
63 | System.out.println("Confidence: " + result.confidence);
64 | ```
65 |
66 | ### Simple detection
67 |
68 | ```java
69 | String language = DetectLanguage.simpleDetect("Hello world");
70 | ```
71 |
72 | ### Batch detection
73 |
74 | ```java
75 | String[] texts = {
76 | "Hello world",
77 | "Labas rytas"
78 | };
79 |
80 | List> results = DetectLanguage.detect(texts);
81 | ```
82 |
83 | ## Requirements
84 |
85 | - [gson](http://code.google.com/p/google-gson/)
86 |
87 | Which you can download to `target/dependency` using:
88 |
89 | mvn dependency:copy-dependencies
90 |
91 | ## Issues
92 |
93 | Please use appropriately tagged github [issues](https://github.com/detectlanguage/detectlanguage-java/issues) to request features or report bugs.
94 |
95 | ## Testing
96 |
97 | mvn test
98 |
99 | ## Publishing
100 |
101 | [Sonatype OSS repository](https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide).
102 |
103 | ### Snapshot
104 |
105 | mvn clean deploy
106 |
107 | ### Stage Release
108 |
109 | mvn release:clean
110 | mvn release:prepare
111 | mvn release:perform
112 |
113 | ### Release
114 |
115 | Done using the [Sonatype Nexus UI](https://oss.sonatype.org/).
116 |
117 | ## Contributing
118 |
119 | 1. Fork it
120 | 2. Create your feature branch (`git checkout -b my-new-feature`)
121 | 3. Write your code **and tests**
122 | 4. Ensure all [tests](#testing) still pass
123 | 5. Commit your changes (`git commit -am 'Add some feature'`)
124 | 6. Push to the branch (`git push origin my-new-feature`)
125 | 7. Create new pull request
126 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | maven {
7 | url "https://maven.google.com"
8 | }
9 | google()
10 | }
11 | dependencies {
12 | classpath 'com.android.tools.build:gradle:3.5.3'
13 |
14 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
15 | // NOTE: Do not place your application dependencies here; they belong
16 | // in the individual module build.gradle files
17 | }
18 | }
19 |
20 | allprojects {
21 | repositories {
22 | jcenter()
23 | maven {
24 | url "https://maven.google.com"
25 | }
26 | google()
27 | }
28 | }
29 |
30 | task clean(type: Delete) {
31 | delete rootProject.buildDir
32 | }
33 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | com.detectlanguage
4 | detectlanguage
5 | jar
6 | detectlanguage-java
7 | 1.1.1-SNAPSHOT
8 | Language Detection API Java client.
9 | http://detectlanguage.com
10 |
11 |
12 | MIT License
13 | http://www.opensource.org/licenses/mit-license.php
14 | repo
15 |
16 |
17 |
18 | git@github.com:detectlanguage/detectlanguage-java.git
19 | scm:git:git@github.com:detectlanguage/detectlanguage-java.git
20 | scm:git:git@github.com:detectlanguage/detectlanguage-java.git
21 |
22 |
23 |
24 | detectlanguage
25 | Detect Language
26 | info@detectlanguage.com
27 | DetectLanguage
28 | http://detectlanguage.com
29 | -7
30 |
31 |
32 |
33 | UTF-8
34 | UTF-8
35 |
36 |
37 | org.sonatype.oss
38 | oss-parent
39 | 7
40 |
41 |
42 |
43 | com.google.code.gson
44 | gson
45 | 2.8.9
46 | compile
47 |
48 |
49 | junit
50 | junit
51 | 4.13.1
52 | test
53 |
54 |
55 |
56 |
57 | release-sign-artifacts
58 |
59 |
60 | performRelease
61 | true
62 |
63 |
64 |
65 |
66 |
67 | org.apache.maven.plugins
68 | maven-gpg-plugin
69 | 1.4
70 |
71 |
72 | sign-artifacts
73 | verify
74 |
75 | sign
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 | ossrh
87 | https://oss.sonatype.org/content/repositories/snapshots
88 |
89 |
90 | ossrh
91 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
92 |
93 |
94 |
95 |
96 |
97 | org.apache.maven.plugins
98 | maven-compiler-plugin
99 | 2.3.2
100 |
101 | 1.7
102 | 1.7
103 |
104 |
105 |
106 | org.apache.maven.plugins
107 | maven-source-plugin
108 | 2.2.1
109 |
110 |
111 | attach-sources
112 |
113 | jar
114 |
115 |
116 |
117 |
118 |
119 | org.apache.maven.plugins
120 | maven-javadoc-plugin
121 | 2.9
122 |
123 |
124 | attach-javadocs
125 |
126 | jar
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/Client.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import com.detectlanguage.errors.APIError;
4 | import com.detectlanguage.responses.ErrorData;
5 | import com.detectlanguage.responses.ErrorResponse;
6 | import com.google.gson.Gson;
7 | import com.google.gson.GsonBuilder;
8 | import com.google.gson.JsonSyntaxException;
9 |
10 | import java.io.IOException;
11 | import java.io.InputStream;
12 | import java.io.OutputStream;
13 | import java.io.UnsupportedEncodingException;
14 | import java.net.HttpURLConnection;
15 | import java.net.MalformedURLException;
16 | import java.net.URL;
17 | import java.net.URLEncoder;
18 | import java.util.HashMap;
19 | import java.util.Map;
20 | import java.util.Scanner;
21 |
22 | public class Client {
23 |
24 | public static final String CHARSET = "UTF-8";
25 |
26 | private static final String AGENT = "detectlanguage-java";
27 |
28 | public Client() {
29 | }
30 |
31 | public T execute(String method, Map params,
32 | Class responseClass) throws APIError {
33 | URL url = buildUrl(method);
34 | String query = buildQuery(params);
35 |
36 | try {
37 | HttpURLConnection conn = createPostConnection(url, query);
38 |
39 | try {
40 | // trigger the request
41 | int rCode = conn.getResponseCode();
42 | String body;
43 |
44 | if (rCode >= 200 && rCode < 300) {
45 | body = getResponseBody(conn.getInputStream());
46 | } else {
47 | body = getResponseBody(conn.getErrorStream());
48 | }
49 |
50 | return processResponse(responseClass, body);
51 | } finally {
52 | conn.disconnect();
53 | }
54 | } catch (IOException e) {
55 | throw new RuntimeException(e);
56 | }
57 | }
58 |
59 | private T processResponse(Class responseClass, String body)
60 | throws APIError {
61 |
62 | Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
63 |
64 | if (body.contains("\"error\":")) {
65 | ErrorResponse errorResponse = gson.fromJson(body,
66 | ErrorResponse.class);
67 | ErrorData error = errorResponse.error;
68 | throw new APIError(error.message, error.code);
69 | }
70 |
71 | try {
72 | return gson.fromJson(body, responseClass);
73 | } catch (JsonSyntaxException e) {
74 | throw new APIError("Server error. Invalid response format.", 9999);
75 | }
76 | }
77 |
78 | private String getProtocol() {
79 | return DetectLanguage.ssl ? "https" : "http";
80 | }
81 |
82 | private URL buildUrl(String path, Map params) {
83 | String url = String.format(
84 | "%s://%s/%s/%s",
85 | getProtocol(),
86 | DetectLanguage.apiHost,
87 | DetectLanguage.apiVersion,
88 | path);
89 |
90 |
91 | if (params != null && params.size() > 0)
92 | url+= '?' + buildQuery(params);
93 |
94 | try {
95 | return new URL(url);
96 | } catch (MalformedURLException e) {
97 | throw new RuntimeException(e);
98 | }
99 | }
100 |
101 | private URL buildUrl(String path) {
102 | return buildUrl(path, null);
103 | }
104 |
105 | private HttpURLConnection createPostConnection(
106 | URL url, String query) throws IOException {
107 | HttpURLConnection conn = createConnection(url);
108 |
109 | conn.setDoOutput(true);
110 | conn.setRequestMethod("POST");
111 | conn.setRequestProperty("Content-Type", String.format(
112 | "application/x-www-form-urlencoded;charset=%s", CHARSET));
113 |
114 | OutputStream output = null;
115 | try {
116 | output = conn.getOutputStream();
117 | output.write(query.getBytes(CHARSET));
118 | } finally {
119 | if (output != null) {
120 | output.close();
121 | }
122 | }
123 | return conn;
124 | }
125 |
126 | private HttpURLConnection createConnection(URL url) throws IOException {
127 | HttpURLConnection conn = (HttpURLConnection) url.openConnection();
128 | conn.setConnectTimeout(DetectLanguage.timeout);
129 | conn.setReadTimeout(DetectLanguage.timeout);
130 | conn.setUseCaches(false);
131 |
132 | String version = getClass().getPackage().getImplementationVersion();
133 |
134 | conn.setRequestProperty("User-Agent", AGENT + '/' + version);
135 | conn.setRequestProperty("Accept", "application/json");
136 | conn.setRequestProperty("Accept-Charset", CHARSET);
137 | conn.setRequestProperty("Authorization", "Bearer " + DetectLanguage.apiKey);
138 |
139 | return conn;
140 | }
141 |
142 | private static String urlEncode(String str) {
143 | try {
144 | return URLEncoder.encode(str, CHARSET);
145 | } catch (UnsupportedEncodingException e) {
146 | throw new RuntimeException(e);
147 | }
148 | }
149 |
150 | private static String urlEncodePair(String k, String v) {
151 | return String.format("%s=%s", urlEncode(k), urlEncode(v));
152 | }
153 |
154 | private static String buildQuery(Map params) {
155 | Map flatParams = flattenParams(params);
156 | StringBuilder queryStringBuffer = new StringBuilder();
157 | for (Map.Entry entry : flatParams.entrySet()) {
158 | if (queryStringBuffer.length() > 0) {
159 | queryStringBuffer.append("&");
160 | }
161 | queryStringBuffer.append(urlEncodePair(entry.getKey(),
162 | entry.getValue()));
163 | }
164 | return queryStringBuffer.toString();
165 | }
166 |
167 | private static Map flattenParams(Map params) {
168 | if (params == null) {
169 | return new HashMap();
170 | }
171 | Map flatParams = new HashMap();
172 | for (Map.Entry entry : params.entrySet()) {
173 | String key = entry.getKey();
174 | Object value = entry.getValue();
175 | if (value instanceof Map, ?>) {
176 | Map flatNestedMap = new HashMap();
177 | Map, ?> nestedMap = (Map, ?>) value;
178 | for (Map.Entry, ?> nestedEntry : nestedMap.entrySet()) {
179 | flatNestedMap.put(
180 | String.format("%s[%s]", key, nestedEntry.getKey()),
181 | nestedEntry.getValue());
182 | }
183 | flatParams.putAll(flattenParams(flatNestedMap));
184 | } else if (value == null) {
185 | flatParams.put(key, "");
186 | } else if (value != null) {
187 | flatParams.put(key, value.toString());
188 | }
189 | }
190 | return flatParams;
191 | }
192 |
193 | private static String getResponseBody(InputStream responseStream)
194 | throws IOException {
195 | //\A is the beginning of
196 | // the stream boundary
197 | String rBody = new Scanner(responseStream, CHARSET)
198 | .useDelimiter("\\A")
199 | .next(); //
200 |
201 | responseStream.close();
202 | return rBody;
203 | }
204 | }
205 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/DetectLanguage.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import com.detectlanguage.errors.APIError;
4 | import com.detectlanguage.responses.BatchDetectResponse;
5 | import com.detectlanguage.responses.DetectResponse;
6 | import com.detectlanguage.responses.StatusResponse;
7 |
8 | import java.util.HashMap;
9 | import java.util.List;
10 |
11 | public abstract class DetectLanguage {
12 | public static String apiHost = "ws.detectlanguage.com";
13 | public static String apiVersion = "0.2";
14 | public static String apiKey;
15 | public static int timeout = 3 * 1000;
16 | public static boolean ssl = false;
17 |
18 | public static String simpleDetect(final String text) throws APIError {
19 | List results = detect(text);
20 |
21 | if (results.isEmpty())
22 | return null;
23 | else
24 | return results.get(0).language;
25 | }
26 |
27 | public static List detect(final String text) throws APIError {
28 | HashMap params = new HashMap();
29 | params.put("q", text);
30 |
31 | DetectResponse response = getClient().execute("detect", params,
32 | DetectResponse.class);
33 |
34 | return response.data.detections;
35 | }
36 |
37 | public static List> detect(final String[] texts)
38 | throws APIError {
39 | HashMap params = new HashMap();
40 |
41 | for (int i = 0; i < texts.length; i++) {
42 | params.put("q[" + i + "]", texts[i]);
43 | }
44 |
45 | BatchDetectResponse response = getClient().execute("detect", params,
46 | BatchDetectResponse.class);
47 |
48 | return response.data.detections;
49 | }
50 |
51 | public static StatusResponse getStatus() throws APIError {
52 | HashMap params = new HashMap();
53 |
54 | StatusResponse response = getClient().execute("user/status", params,
55 | StatusResponse.class);
56 |
57 | return response;
58 | }
59 |
60 | private static Client getClient() {
61 | return new Client();
62 | }
63 | }
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/Result.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | public class Result {
4 | public String language;
5 | public boolean isReliable;
6 | public double confidence;
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/errors/APIError.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.errors;
2 |
3 | @SuppressWarnings("serial")
4 | public class APIError extends Exception {
5 | public int code;
6 |
7 | public APIError(String message, int code) {
8 | super(message);
9 | this.code = code;
10 | }
11 | }
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/BatchDetectResponse.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | public class BatchDetectResponse extends Response {
4 | public BatchDetectionsData data;
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/BatchDetectionsData.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | import com.detectlanguage.Result;
4 |
5 | import java.util.List;
6 |
7 | public class BatchDetectionsData {
8 | public List> detections;
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/DetectResponse.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | public class DetectResponse extends Response {
4 | public DetectionsData data;
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/DetectionsData.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | import com.detectlanguage.Result;
4 |
5 | import java.util.List;
6 |
7 | public class DetectionsData {
8 | public List detections;
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/ErrorData.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | public class ErrorData {
4 | public int code;
5 | public String message;
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/ErrorResponse.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | public class ErrorResponse extends Response {
4 | public ErrorData error;
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/Response.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | abstract public class Response {
4 | }
5 |
--------------------------------------------------------------------------------
/src/main/java/com/detectlanguage/responses/StatusResponse.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage.responses;
2 |
3 | import java.util.Date;
4 |
5 | public class StatusResponse extends Response {
6 | private Date date;
7 | private Double requests;
8 | private Double bytes;
9 | private String plan;
10 | private Date plan_expires;
11 | private Double daily_requests_limit;
12 | private Double daily_bytes_limit;
13 | private String status;
14 |
15 | public Date getDate() {
16 | return date;
17 | }
18 |
19 | public Long getRequests() {
20 | return requests.longValue();
21 | }
22 |
23 | public Long getBytes() {
24 | return bytes.longValue();
25 | }
26 |
27 | public String getPlan() {
28 | return plan;
29 | }
30 |
31 | public Date getPlanExpires() {
32 | return plan_expires;
33 | }
34 |
35 | public Long getDailyRequestsLimit() {
36 | return daily_requests_limit.longValue();
37 | }
38 |
39 | public Long getDailyBytesLimit() {
40 | return daily_bytes_limit.longValue();
41 | }
42 |
43 | public String getStatus() {
44 | return status;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/test/java/com/detectlanguage/BaseTest.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import org.junit.Before;
4 |
5 | public class BaseTest {
6 | @Before
7 | public void setUp() {
8 | DetectLanguage.apiHost = System.getProperty("detectlanguage_api_host",
9 | DetectLanguage.apiHost);
10 | DetectLanguage.apiKey = System.getProperty("detectlanguage_api_key",
11 | System.getenv().get("DETECTLANGUAGE_API_KEY"));
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/test/java/com/detectlanguage/GenericTest.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import com.detectlanguage.errors.APIError;
4 | import com.detectlanguage.responses.StatusResponse;
5 | import org.junit.Test;
6 |
7 | import java.util.Date;
8 | import java.util.List;
9 |
10 | import static org.hamcrest.CoreMatchers.*;
11 | import static org.junit.Assert.*;
12 |
13 | public class GenericTest extends BaseTest {
14 |
15 | @Test
16 | public void testSimpleDetect() throws APIError {
17 | String language = DetectLanguage.simpleDetect("Hello world");
18 |
19 | assertEquals(language, "en");
20 | }
21 |
22 | @Test
23 | public void testDetect() throws APIError {
24 | List results = DetectLanguage.detect("Hello world");
25 |
26 | Result result = results.get(0);
27 |
28 | assertEquals(result.language, "en");
29 | assertTrue(result.isReliable);
30 | assertTrue(result.confidence > 0);
31 | }
32 |
33 | @Test(expected = APIError.class)
34 | public void testDetectError() throws APIError {
35 | DetectLanguage.apiKey = "INVALID";
36 | DetectLanguage.detect("Hello world");
37 | }
38 |
39 | @Test
40 | public void testBatchDetect() throws APIError {
41 | String[] texts = {"Hello world", "Kabo kabikas, žiūri žiūrikas"};
42 |
43 | List> results = DetectLanguage.detect(texts);
44 | Result result;
45 |
46 | result = results.get(0).get(0);
47 |
48 | assertEquals(result.language, "en");
49 | assertTrue(result.isReliable);
50 | assertTrue(result.confidence > 0);
51 |
52 | result = results.get(1).get(0);
53 |
54 | assertEquals(result.language, "lt");
55 | assertTrue(result.isReliable);
56 | assertTrue(result.confidence > 0);
57 | }
58 |
59 | @Test(expected = APIError.class)
60 | public void testBatchDetectError() throws APIError {
61 | DetectLanguage.apiKey = "INVALID";
62 |
63 | String[] texts = {"Hello world", "Kabo kabikas, žiūri žiūrikas"};
64 |
65 | DetectLanguage.detect(texts);
66 | }
67 |
68 | @Test
69 | public void testGetStatus() throws APIError {
70 | StatusResponse statusResponse = DetectLanguage.getStatus();
71 |
72 | assertThat(statusResponse.getDate(), is(instanceOf(Date.class)));
73 | assertTrue(statusResponse.getRequests() >= 0);
74 | assertTrue(statusResponse.getBytes() >= 0);
75 | assertThat(statusResponse.getPlan(), is(instanceOf(String.class)));
76 | assertThat(statusResponse.getPlanExpires(),
77 | anyOf(nullValue(), instanceOf(Date.class)));
78 | assertTrue(statusResponse.getDailyRequestsLimit() > 0);
79 | assertTrue(statusResponse.getDailyBytesLimit() > 0);
80 | assertEquals(statusResponse.getStatus(), "ACTIVE");
81 | }
82 |
83 | @Test(expected = APIError.class)
84 | public void testStatusError() throws APIError {
85 | DetectLanguage.apiKey = "INVALID";
86 | DetectLanguage.getStatus();
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/test/java/com/detectlanguage/MultithreadedTest.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import com.detectlanguage.errors.APIError;
4 | import org.junit.Test;
5 | import org.junit.Ignore;
6 |
7 | import java.util.Random;
8 |
9 | import static org.junit.Assert.assertEquals;
10 |
11 | /**
12 | * Copyright 2014 Getty Images
13 | * User: dbabichev
14 | * Date: 6/23/2014
15 | * Time: 12:41 PM
16 | */
17 | public class MultithreadedTest extends BaseTest {
18 | public static final String[] SAMPLES = {"Labas rytas", "Hello world", "Buenos dias"};
19 | public static final String[] SAMPLE_CODES = {"lt", "en", "es"};
20 |
21 | public static int TEST_THREADS = 10;
22 |
23 | @Ignore("fails locally because of connection timeouts")
24 | @Test
25 | public void multithreadedRequestExecution() throws InterruptedException {
26 |
27 | // create a thread for each request
28 | RequestThread[] threads = new RequestThread[TEST_THREADS];
29 | for (int i = 0; i < threads.length; i++) {
30 | threads[i] = new RequestThread();
31 | }
32 |
33 | // start the threads
34 | for (RequestThread thread : threads) {
35 | thread.start();
36 | }
37 |
38 | // join the threads
39 | for (RequestThread thread : threads) {
40 | thread.join();
41 | }
42 |
43 | for (RequestThread thread : threads) {
44 | assertEquals(thread.expectedLanguage, thread.detectedLanguage);
45 | }
46 | }
47 |
48 | static class RequestThread extends Thread {
49 |
50 | public String detectedLanguage;
51 | public String expectedLanguage;
52 |
53 | @Override
54 | public void run() {
55 | try {
56 | int n = (new Random()).nextInt(SAMPLES.length);
57 | expectedLanguage = SAMPLE_CODES[n];
58 | sleep((new Random()).nextInt(10000));
59 | detectedLanguage = DetectLanguage.simpleDetect(SAMPLES[n]);
60 | } catch (InterruptedException e) {
61 | } catch (APIError apiError) {
62 | apiError.printStackTrace();
63 | }
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/test/java/com/detectlanguage/ServerErrorTest.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import com.detectlanguage.errors.APIError;
4 | import org.junit.After;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.junit.Ignore;
8 |
9 | import static org.junit.Assert.assertEquals;
10 |
11 | public class ServerErrorTest extends BaseTest {
12 | @Before
13 | public void setInvalidHost() {
14 | DetectLanguage.apiHost = "www.detectlanguage.com";
15 | }
16 |
17 | @After
18 | public void resetHost() {
19 | DetectLanguage.apiHost = "ws.detectlanguage.com";
20 | }
21 |
22 | @Ignore
23 | @Test(expected = APIError.class)
24 | public void testSimpleDetect() throws APIError {
25 | DetectLanguage.simpleDetect("Hello world");
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/detectlanguage/SslTest.java:
--------------------------------------------------------------------------------
1 | package com.detectlanguage;
2 |
3 | import com.detectlanguage.errors.APIError;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 | import org.junit.After;
7 |
8 | import static org.junit.Assert.*;
9 |
10 | public class SslTest extends BaseTest {
11 | @Before
12 | public void enableSsl() {
13 | DetectLanguage.ssl = true;
14 | }
15 |
16 | @After
17 | public void disableSsl() {
18 | DetectLanguage.ssl = false;
19 | }
20 |
21 | @Test
22 | public void testSimpleDetect() throws APIError {
23 | String language = DetectLanguage.simpleDetect("Hello world");
24 |
25 | assertEquals(language, "en");
26 | }
27 | }
28 |
--------------------------------------------------------------------------------