diff --git a/checkstyle.xml b/checkstyle.xml
deleted file mode 100644
index 383a980..0000000
--- a/checkstyle.xml
+++ /dev/null
@@ -1,119 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/pom.xml b/pom.xml
index e292e0f..1e91758 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,16 +1,21 @@
-
+
4.0.0
com.sitepark
translate-api
- jar
2.1.0-SNAPSHOT
+ jar
Translate Java API
Java API for translating texts across different providers
https://github.com/sitepark/translate-api
+
+ Sitepark
+ https://www.sitepark.com
+
+
The MIT License
@@ -18,11 +23,6 @@
-
- Sitepark
- https://www.sitepark.com
-
-
veltrup@sitepark
@@ -38,6 +38,13 @@
+
+ scm:git:git@github.com:sitepark/translate-api.git
+ scm:git:git@github.com:sitepark/translate-api.git
+ HEAD
+ https://github.com/sitepark/translate-api
+
+
5.10.2
2.16.1
@@ -47,13 +54,6 @@
true
-
- scm:git:git@github.com:sitepark/translate-api.git
- scm:git:git@github.com:sitepark/translate-api.git
- https://github.com/sitepark/translate-api
- HEAD
-
-
@@ -132,10 +132,10 @@
add-integration-test-sources
- generate-test-sources
add-test-source
+ generate-test-sources
@@ -169,10 +169,10 @@
assemble-all
- package
single
+ package
@@ -189,10 +189,10 @@
integration-test
- integration-test
test
+ integration-test
IntegrationTest
@@ -232,10 +232,10 @@
sign-artifacts
- verify
sign
+ verify
@@ -243,7 +243,7 @@
maven-release-plugin
3.0.1
- ci(release):
+ ci(release):
@{project.version}
@@ -279,46 +279,82 @@
generate-code-coverage-report
- test
report
+ test
- org.apache.maven.plugins
- maven-checkstyle-plugin
- 3.3.1
+ com.diffplug.spotless
+ spotless-maven-plugin
+ 2.43.0
- checkstyle.xml
- UTF-8
- true
- true
- false
+
+
+
+ google-java-format
+
+
+
+
+ 1.19.2
+
+ true
+ false
+
+
+
+
+
+
+ pom.xml
+
+
+
+ -1
+
+
- checkstyle
- verify
+ spotless-check
check
+ verify
+
+ org.eclipse.m2e
+ lifecycle-mapping
+ 1.0.0
+
+
+
+
+
+ com.diffplug.spotless
+ spotless-maven-plugin
+
+
+ check
+
+
+
+
+
+
+
+
+
+
com.github.spotbugs
spotbugs-maven-plugin
4.8.3.0
-
-
- verify
-
- check
-
-
-
Max
Low
@@ -335,20 +371,19 @@
${spotbugs.version}
-
-
- org.apache.maven.plugins
- maven-pmd-plugin
- 3.21.2
- pmd
- verify
check
+ verify
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ 3.21.2
pmd-ruleset.xml
@@ -357,8 +392,18 @@
true
5
true
- false
+ false
+
+
+
+ pmd
+
+ check
+
+ verify
+
+
diff --git a/src/main/java/com/sitepark/translate/Format.java b/src/main/java/com/sitepark/translate/Format.java
index 960e2c2..f524613 100644
--- a/src/main/java/com/sitepark/translate/Format.java
+++ b/src/main/java/com/sitepark/translate/Format.java
@@ -1,17 +1,16 @@
package com.sitepark.translate;
-import java.util.Locale;
-
import com.fasterxml.jackson.annotation.JsonValue;
+import java.util.Locale;
public enum Format {
- TEXT,
- HTML,
- AUTO;
+ TEXT,
+ HTML,
+ AUTO;
- @Override
- @JsonValue
- public String toString() {
- return name().toLowerCase(Locale.ENGLISH);
- }
+ @Override
+ @JsonValue
+ public String toString() {
+ return name().toLowerCase(Locale.ENGLISH);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/Glossary.java b/src/main/java/com/sitepark/translate/Glossary.java
index ead9705..d02610c 100644
--- a/src/main/java/com/sitepark/translate/Glossary.java
+++ b/src/main/java/com/sitepark/translate/Glossary.java
@@ -1,159 +1,156 @@
package com.sitepark.translate;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
-import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
@JsonDeserialize(builder = Glossary.Builder.class)
public final class Glossary {
- private final String name;
-
- private final TranslationLanguage language;
-
- private final List entryList;
-
- private Glossary(Builder builder) {
- this.name = builder.name;
- this.language = builder.language;
- this.entryList = Collections.unmodifiableList(builder.entryList);
- }
-
- public String getName() {
- return this.name;
- }
-
- public TranslationLanguage getLanguage() {
- return this.language;
- }
-
- @SuppressFBWarnings("EI_EXPOSE_REP")
- public List getEntryList() {
- return this.entryList;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- @Override
- public int hashCode() {
- int hashCode = 0;
- if (this.name != null) {
- hashCode += this.name.hashCode();
- }
- if (this.language != null) {
- hashCode += this.language.hashCode();
- }
- if (this.entryList != null) {
- hashCode += this.entryList.hashCode();
- }
-
- return hashCode;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof Glossary)) {
- return false;
- }
- Glossary glossar = (Glossary)o;
- return
- Objects.equals(glossar.getName(), this.name) &&
- Objects.equals(glossar.getLanguage(), this.language) &&
- Objects.equals(glossar.getEntryList(), this.entryList);
- }
-
- @Override
- public String toString() {
-
- StringBuilder b = new StringBuilder(50)
- .append("name:")
- .append(this.name)
- .append(", ")
- .append("language:")
- .append(this.language)
- .append('\n');
- for (GlossaryEntry entity : this.entryList) {
- b.append(entity).append('\n');
- }
-
- return b.toString();
- }
-
- @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build")
- public final static class Builder {
-
- private String name;
-
- private TranslationLanguage language;
-
- private final List entryList = new ArrayList<>();
-
- private Builder() {
- }
-
- private Builder(Glossary glossar) {
- this.name = glossar.name;
- this.language = glossar.language;
- this.entryList.addAll(glossar.entryList);
- }
-
- public Builder name(String name) {
- Objects.requireNonNull(name, "name is null");
- if (name.isBlank()) {
- throw new IllegalArgumentException("name is blank");
- }
- this.name = name;
- return this;
- }
-
- public Builder language(TranslationLanguage language) {
- Objects.requireNonNull(language, "language is null");
- this.language = language;
- return this;
- }
-
- public Builder entryList(GlossaryEntry... entryList) {
- Objects.requireNonNull(entryList, "entryList is null");
- for (GlossaryEntry entry : entryList) {
- this.entry(entry);
- }
- return this;
- }
-
- public Builder entryList(List entryList) {
- Objects.requireNonNull(entryList, "entryList is null");
- for (GlossaryEntry entry : entryList) {
- this.entry(entry);
- }
- return this;
- }
-
- public Builder entry(GlossaryEntry entry) {
- Objects.requireNonNull(entry, "entry is null");
- this.entryList.add(entry);
- return this;
- }
-
- public Glossary build() {
- if (this.name == null) {
- throw new IllegalStateException("name not set");
- }
- if (this.language == null) {
- throw new IllegalStateException("language not set");
- }
- return new Glossary(this);
- }
- }
+ private final String name;
+
+ private final TranslationLanguage language;
+
+ private final List entryList;
+
+ private Glossary(Builder builder) {
+ this.name = builder.name;
+ this.language = builder.language;
+ this.entryList = Collections.unmodifiableList(builder.entryList);
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public TranslationLanguage getLanguage() {
+ return this.language;
+ }
+
+ @SuppressFBWarnings("EI_EXPOSE_REP")
+ public List getEntryList() {
+ return this.entryList;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 0;
+ if (this.name != null) {
+ hashCode += this.name.hashCode();
+ }
+ if (this.language != null) {
+ hashCode += this.language.hashCode();
+ }
+ if (this.entryList != null) {
+ hashCode += this.entryList.hashCode();
+ }
+
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof Glossary)) {
+ return false;
+ }
+ Glossary glossar = (Glossary) o;
+ return Objects.equals(glossar.getName(), this.name)
+ && Objects.equals(glossar.getLanguage(), this.language)
+ && Objects.equals(glossar.getEntryList(), this.entryList);
+ }
+
+ @Override
+ public String toString() {
+
+ StringBuilder b =
+ new StringBuilder(50)
+ .append("name:")
+ .append(this.name)
+ .append(", ")
+ .append("language:")
+ .append(this.language)
+ .append('\n');
+ for (GlossaryEntry entity : this.entryList) {
+ b.append(entity).append('\n');
+ }
+
+ return b.toString();
+ }
+
+ @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build")
+ public static final class Builder {
+
+ private String name;
+
+ private TranslationLanguage language;
+
+ private final List entryList = new ArrayList<>();
+
+ private Builder() {}
+
+ private Builder(Glossary glossar) {
+ this.name = glossar.name;
+ this.language = glossar.language;
+ this.entryList.addAll(glossar.entryList);
+ }
+
+ public Builder name(String name) {
+ Objects.requireNonNull(name, "name is null");
+ if (name.isBlank()) {
+ throw new IllegalArgumentException("name is blank");
+ }
+ this.name = name;
+ return this;
+ }
+
+ public Builder language(TranslationLanguage language) {
+ Objects.requireNonNull(language, "language is null");
+ this.language = language;
+ return this;
+ }
+
+ public Builder entryList(GlossaryEntry... entryList) {
+ Objects.requireNonNull(entryList, "entryList is null");
+ for (GlossaryEntry entry : entryList) {
+ this.entry(entry);
+ }
+ return this;
+ }
+
+ public Builder entryList(List entryList) {
+ Objects.requireNonNull(entryList, "entryList is null");
+ for (GlossaryEntry entry : entryList) {
+ this.entry(entry);
+ }
+ return this;
+ }
+
+ public Builder entry(GlossaryEntry entry) {
+ Objects.requireNonNull(entry, "entry is null");
+ this.entryList.add(entry);
+ return this;
+ }
+
+ public Glossary build() {
+ if (this.name == null) {
+ throw new IllegalStateException("name not set");
+ }
+ if (this.language == null) {
+ throw new IllegalStateException("language not set");
+ }
+ return new Glossary(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/GlossaryChangeSet.java b/src/main/java/com/sitepark/translate/GlossaryChangeSet.java
index c4ebc02..28bc179 100644
--- a/src/main/java/com/sitepark/translate/GlossaryChangeSet.java
+++ b/src/main/java/com/sitepark/translate/GlossaryChangeSet.java
@@ -7,48 +7,46 @@
public final class GlossaryChangeSet {
- private final List added = new ArrayList<>();
-
- private final List deleted = new ArrayList<>();
-
- public void added(GlossaryEntry entry) {
- this.added.add(entry);
- }
-
- public void deleted(GlossaryEntry entry) {
- this.deleted.add(entry);
- }
-
- public List getAdded() {
- return Collections.unmodifiableList(this.added);
- }
-
- public List getDeleted() {
- return Collections.unmodifiableList(this.deleted);
- }
-
- @Override
- public int hashCode() {
- int hashCode = 0;
- if (this.added != null) {
- hashCode += this.added.hashCode();
- }
- if (this.deleted != null) {
- hashCode += this.deleted.hashCode();
- }
- return hashCode;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof GlossaryChangeSet)) {
- return false;
- }
-
- GlossaryChangeSet changeSet = (GlossaryChangeSet)o;
- return
- Objects.equals(changeSet.added, this.added) &&
- Objects.equals(changeSet.deleted, this.deleted);
- }
-
+ private final List added = new ArrayList<>();
+
+ private final List deleted = new ArrayList<>();
+
+ public void added(GlossaryEntry entry) {
+ this.added.add(entry);
+ }
+
+ public void deleted(GlossaryEntry entry) {
+ this.deleted.add(entry);
+ }
+
+ public List getAdded() {
+ return Collections.unmodifiableList(this.added);
+ }
+
+ public List getDeleted() {
+ return Collections.unmodifiableList(this.deleted);
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 0;
+ if (this.added != null) {
+ hashCode += this.added.hashCode();
+ }
+ if (this.deleted != null) {
+ hashCode += this.deleted.hashCode();
+ }
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof GlossaryChangeSet)) {
+ return false;
+ }
+
+ GlossaryChangeSet changeSet = (GlossaryChangeSet) o;
+ return Objects.equals(changeSet.added, this.added)
+ && Objects.equals(changeSet.deleted, this.deleted);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/GlossaryDiffer.java b/src/main/java/com/sitepark/translate/GlossaryDiffer.java
index 5104015..03a42d9 100644
--- a/src/main/java/com/sitepark/translate/GlossaryDiffer.java
+++ b/src/main/java/com/sitepark/translate/GlossaryDiffer.java
@@ -5,33 +5,33 @@
public final class GlossaryDiffer {
- private final Glossary a;
+ private final Glossary a;
- private final Glossary b;
+ private final Glossary b;
- public GlossaryDiffer(Glossary a, Glossary b) {
- this.a = a;
- this.b = b;
- }
+ public GlossaryDiffer(Glossary a, Glossary b) {
+ this.a = a;
+ this.b = b;
+ }
- public GlossaryChangeSet diff() {
+ public GlossaryChangeSet diff() {
- GlossaryChangeSet changeSet = new GlossaryChangeSet();
+ GlossaryChangeSet changeSet = new GlossaryChangeSet();
- Set entrySetOfB = new HashSet<>(this.b.getEntryList());
- for (GlossaryEntry entryOfA : this.a.getEntryList()) {
- if (!entrySetOfB.contains(entryOfA)) {
- changeSet.deleted(entryOfA);
- }
- }
+ Set entrySetOfB = new HashSet<>(this.b.getEntryList());
+ for (GlossaryEntry entryOfA : this.a.getEntryList()) {
+ if (!entrySetOfB.contains(entryOfA)) {
+ changeSet.deleted(entryOfA);
+ }
+ }
- Set entrySetOfA = new HashSet<>(this.a.getEntryList());
- for (GlossaryEntry entryOfB : this.b.getEntryList()) {
- if (!entrySetOfA.contains(entryOfB)) {
- changeSet.added(entryOfB);
- }
- }
+ Set entrySetOfA = new HashSet<>(this.a.getEntryList());
+ for (GlossaryEntry entryOfB : this.b.getEntryList()) {
+ if (!entrySetOfA.contains(entryOfB)) {
+ changeSet.added(entryOfB);
+ }
+ }
- return changeSet;
- }
+ return changeSet;
+ }
}
diff --git a/src/main/java/com/sitepark/translate/GlossaryEntry.java b/src/main/java/com/sitepark/translate/GlossaryEntry.java
index c860007..7314e8f 100644
--- a/src/main/java/com/sitepark/translate/GlossaryEntry.java
+++ b/src/main/java/com/sitepark/translate/GlossaryEntry.java
@@ -1,113 +1,109 @@
package com.sitepark.translate;
-import java.util.Objects;
-
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import java.util.Objects;
@JsonDeserialize(builder = GlossaryEntry.Builder.class)
public final class GlossaryEntry {
- private final String source;
-
- private final String target;
-
- private GlossaryEntry(Builder builder) {
- this.source = builder.source;
- this.target = builder.target;
- }
-
- public String getSource() {
- return this.source;
- }
-
- public String getTarget() {
- return this.target;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- @Override
- public int hashCode() {
- int hashCode = 0;
- if (this.source != null) {
- hashCode += this.source.hashCode();
- }
- if (this.target != null) {
- hashCode += this.target.hashCode();
- }
- return hashCode;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof GlossaryEntry)) {
- return false;
- }
-
- GlossaryEntry entry = (GlossaryEntry)o;
- return
- Objects.equals(entry.getSource(), this.source) &&
- Objects.equals(entry.getTarget(), this.target);
- }
-
- @Override
- public String toString() {
- return this.source + ": " + this.target;
- }
-
-
- @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build")
- public final static class Builder {
-
- private String source;
-
- private String target;
-
- private Builder() {
- }
-
- private Builder(GlossaryEntry glossarEntry) {
- this.source = glossarEntry.source;
- this.target = glossarEntry.target;
- }
-
- public Builder source(String source) {
- Objects.requireNonNull(source, "source is null");
- this.requireNotBlank(source, "source is blank");
- this.source = source;
- return this;
- }
-
- public Builder target(String target) {
- Objects.requireNonNull(target, "target is null");
- this.requireNotBlank(target, "target is blank");
- this.target = target;
- return this;
- }
-
- public GlossaryEntry build() {
-
- if (this.source == null) {
- throw new IllegalStateException("source not set");
- }
- if (this.target == null) {
- throw new IllegalStateException("target not set");
- }
-
- return new GlossaryEntry(this);
- }
-
- private void requireNotBlank(String s, String message) {
- if (s.isBlank()) {
- throw new IllegalArgumentException(message);
- }
- }
- }
+ private final String source;
+
+ private final String target;
+
+ private GlossaryEntry(Builder builder) {
+ this.source = builder.source;
+ this.target = builder.target;
+ }
+
+ public String getSource() {
+ return this.source;
+ }
+
+ public String getTarget() {
+ return this.target;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 0;
+ if (this.source != null) {
+ hashCode += this.source.hashCode();
+ }
+ if (this.target != null) {
+ hashCode += this.target.hashCode();
+ }
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof GlossaryEntry)) {
+ return false;
+ }
+
+ GlossaryEntry entry = (GlossaryEntry) o;
+ return Objects.equals(entry.getSource(), this.source)
+ && Objects.equals(entry.getTarget(), this.target);
+ }
+
+ @Override
+ public String toString() {
+ return this.source + ": " + this.target;
+ }
+
+ @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build")
+ public static final class Builder {
+
+ private String source;
+
+ private String target;
+
+ private Builder() {}
+
+ private Builder(GlossaryEntry glossarEntry) {
+ this.source = glossarEntry.source;
+ this.target = glossarEntry.target;
+ }
+
+ public Builder source(String source) {
+ Objects.requireNonNull(source, "source is null");
+ this.requireNotBlank(source, "source is blank");
+ this.source = source;
+ return this;
+ }
+
+ public Builder target(String target) {
+ Objects.requireNonNull(target, "target is null");
+ this.requireNotBlank(target, "target is blank");
+ this.target = target;
+ return this;
+ }
+
+ public GlossaryEntry build() {
+
+ if (this.source == null) {
+ throw new IllegalStateException("source not set");
+ }
+ if (this.target == null) {
+ throw new IllegalStateException("target not set");
+ }
+
+ return new GlossaryEntry(this);
+ }
+
+ private void requireNotBlank(String s, String message) {
+ if (s.isBlank()) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/GlossaryManager.java b/src/main/java/com/sitepark/translate/GlossaryManager.java
index dcad587..d34a0f1 100644
--- a/src/main/java/com/sitepark/translate/GlossaryManager.java
+++ b/src/main/java/com/sitepark/translate/GlossaryManager.java
@@ -1,32 +1,30 @@
package com.sitepark.translate;
-import java.util.Optional;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.Optional;
public class GlossaryManager {
- private final TranslationProvider translationProvider;
-
- @SuppressFBWarnings("EI_EXPOSE_REP2")
- public GlossaryManager(TranslationProvider translationProvider) {
- this.translationProvider = translationProvider;
- }
+ private final TranslationProvider translationProvider;
- public Optional getGlossary(String id) {
- return translationProvider.getGlossary(id);
- }
+ @SuppressFBWarnings("EI_EXPOSE_REP2")
+ public GlossaryManager(TranslationProvider translationProvider) {
+ this.translationProvider = translationProvider;
+ }
- public Optional getGlossaryId(String name) {
- return translationProvider.getGlossaryId(name);
- }
+ public Optional getGlossary(String id) {
+ return translationProvider.getGlossary(id);
+ }
- public String recreate(Glossary glossary) {
- return translationProvider.recreate(glossary);
- }
+ public Optional getGlossaryId(String name) {
+ return translationProvider.getGlossaryId(name);
+ }
- public void remove(String id) {
- translationProvider.removeGlossary(id);
- }
+ public String recreate(Glossary glossary) {
+ return translationProvider.recreate(glossary);
+ }
+ public void remove(String id) {
+ translationProvider.removeGlossary(id);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/Language.java b/src/main/java/com/sitepark/translate/Language.java
index 8eb008a..4edcf65 100644
--- a/src/main/java/com/sitepark/translate/Language.java
+++ b/src/main/java/com/sitepark/translate/Language.java
@@ -1,149 +1,147 @@
package com.sitepark.translate;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
@JsonDeserialize(builder = Language.Builder.class)
public final class Language {
- private final String code;
-
- private final String name;
-
- private final List targets;
-
- private Language(Builder builder) {
- this.code = builder.code;
- this.name = builder.name;
- this.targets = Collections.unmodifiableList(builder.targets);
- }
-
- public String getCode() {
- return this.code;
- }
-
- public String getName() {
- return this.name;
- }
-
- @SuppressFBWarnings("EI_EXPOSE_REP")
- public List getTargets() {
- return this.targets;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- @Override
- public int hashCode() {
- int hashCode = 0;
- if (this.code != null) {
- hashCode += this.code.hashCode();
- }
- if (this.name != null) {
- hashCode += this.name.hashCode();
- }
- if (this.targets != null) {
- hashCode += this.targets.hashCode();
- }
- return hashCode;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof Language)) {
- return false;
- }
- Language l = (Language)o;
- if (!Objects.equals(l.getCode(), this.code)) {
- return false;
- } else if (!Objects.equals(l.getName(), this.name)) {
- return false;
- }
- return Objects.equals(l.getTargets(), this.targets);
- }
-
- @Override
- public String toString() {
- return this.code + " (" + this.name + ") targets: " + this.targets;
- }
-
- @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build")
- public final static class Builder {
-
- private String code;
-
- private String name;
-
- private final List targets = new ArrayList<>();
-
- private Builder() { }
-
- private Builder(Language language) {
- this.code = language.code;
- this.name = language.name;
- this.targets.addAll(language.targets);
- }
-
- public Builder code(String code) {
- Objects.requireNonNull(code, "code is null");
- this.code = code;
- return this;
- }
-
- public Builder name(String name) {
- Objects.requireNonNull(name, "name is null");
- this.name = name;
- return this;
- }
-
- @JsonProperty
- public Builder targets(String... targets) {
- Objects.requireNonNull(targets, "targets is null");
- for (String target : targets) {
- this.target(target);
- }
- return this;
- }
-
- public Builder targets(List targets) {
- Objects.requireNonNull(targets, "targets is null");
- for (String target : targets) {
- this.target(target);
- }
- return this;
- }
-
- public Builder target(String target) {
- Objects.requireNonNull(target, "target is null");
- this.targets.add(target);
- return this;
- }
-
- public Language build() {
- if (this.code == null) {
- throw new IllegalStateException("code not set");
- }
- if (this.name == null) {
- throw new IllegalStateException("name not set");
- }
- if (targets.isEmpty()) {
- throw new IllegalStateException("no targets set");
- }
- return new Language(this);
- }
- }
-}
\ No newline at end of file
+ private final String code;
+
+ private final String name;
+
+ private final List targets;
+
+ private Language(Builder builder) {
+ this.code = builder.code;
+ this.name = builder.name;
+ this.targets = Collections.unmodifiableList(builder.targets);
+ }
+
+ public String getCode() {
+ return this.code;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ @SuppressFBWarnings("EI_EXPOSE_REP")
+ public List getTargets() {
+ return this.targets;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 0;
+ if (this.code != null) {
+ hashCode += this.code.hashCode();
+ }
+ if (this.name != null) {
+ hashCode += this.name.hashCode();
+ }
+ if (this.targets != null) {
+ hashCode += this.targets.hashCode();
+ }
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof Language)) {
+ return false;
+ }
+ Language l = (Language) o;
+ if (!Objects.equals(l.getCode(), this.code)) {
+ return false;
+ } else if (!Objects.equals(l.getName(), this.name)) {
+ return false;
+ }
+ return Objects.equals(l.getTargets(), this.targets);
+ }
+
+ @Override
+ public String toString() {
+ return this.code + " (" + this.name + ") targets: " + this.targets;
+ }
+
+ @JsonPOJOBuilder(withPrefix = "", buildMethodName = "build")
+ public static final class Builder {
+
+ private String code;
+
+ private String name;
+
+ private final List targets = new ArrayList<>();
+
+ private Builder() {}
+
+ private Builder(Language language) {
+ this.code = language.code;
+ this.name = language.name;
+ this.targets.addAll(language.targets);
+ }
+
+ public Builder code(String code) {
+ Objects.requireNonNull(code, "code is null");
+ this.code = code;
+ return this;
+ }
+
+ public Builder name(String name) {
+ Objects.requireNonNull(name, "name is null");
+ this.name = name;
+ return this;
+ }
+
+ @JsonProperty
+ public Builder targets(String... targets) {
+ Objects.requireNonNull(targets, "targets is null");
+ for (String target : targets) {
+ this.target(target);
+ }
+ return this;
+ }
+
+ public Builder targets(List targets) {
+ Objects.requireNonNull(targets, "targets is null");
+ for (String target : targets) {
+ this.target(target);
+ }
+ return this;
+ }
+
+ public Builder target(String target) {
+ Objects.requireNonNull(target, "target is null");
+ this.targets.add(target);
+ return this;
+ }
+
+ public Language build() {
+ if (this.code == null) {
+ throw new IllegalStateException("code not set");
+ }
+ if (this.name == null) {
+ throw new IllegalStateException("name not set");
+ }
+ if (targets.isEmpty()) {
+ throw new IllegalStateException("no targets set");
+ }
+ return new Language(this);
+ }
+ }
+}
diff --git a/src/main/java/com/sitepark/translate/SupportedLanguages.java b/src/main/java/com/sitepark/translate/SupportedLanguages.java
index 9d999e9..44b0692 100644
--- a/src/main/java/com/sitepark/translate/SupportedLanguages.java
+++ b/src/main/java/com/sitepark/translate/SupportedLanguages.java
@@ -1,13 +1,5 @@
package com.sitepark.translate;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.concurrent.ConcurrentHashMap;
-
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -18,93 +10,99 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.node.ArrayNode;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonDeserialize(using = SupportedLanguages.Deserializer.class)
public final class SupportedLanguages {
- private final Map languages;
+ private final Map languages;
- private SupportedLanguages(Builder builder) {
- this.languages = builder.languages;
- }
+ private SupportedLanguages(Builder builder) {
+ this.languages = builder.languages;
+ }
- public List getAll() {
- return new ArrayList<>(this.languages.values());
- }
+ public List getAll() {
+ return new ArrayList<>(this.languages.values());
+ }
- public Optional getSourceLanguage(String source) {
- return Optional.ofNullable(this.languages.get(source));
- }
+ public Optional getSourceLanguage(String source) {
+ return Optional.ofNullable(this.languages.get(source));
+ }
- public Optional getTargetLanguage(String source, String target) {
- Language sourceLanguage = this.languages.get(source);
- if (sourceLanguage == null) {
- return Optional.empty();
- }
+ public Optional getTargetLanguage(String source, String target) {
+ Language sourceLanguage = this.languages.get(source);
+ if (sourceLanguage == null) {
+ return Optional.empty();
+ }
- if (!sourceLanguage.getTargets().contains(target)) {
- return Optional.empty();
- }
+ if (!sourceLanguage.getTargets().contains(target)) {
+ return Optional.empty();
+ }
- return Optional.ofNullable(this.languages.get(target));
- }
+ return Optional.ofNullable(this.languages.get(target));
+ }
- public Builder toBuilder() {
- return new Builder(this);
- }
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
- public static Builder builder() {
- return new Builder();
- }
+ public static Builder builder() {
+ return new Builder();
+ }
- public final static class Builder {
+ public static final class Builder {
- private final Map languages = new ConcurrentHashMap<>();
+ private final Map languages = new ConcurrentHashMap<>();
- private Builder() {
- }
+ private Builder() {}
- private Builder(SupportedLanguages supportedLanguages) {
- this.languages.putAll(supportedLanguages.languages);
- }
+ private Builder(SupportedLanguages supportedLanguages) {
+ this.languages.putAll(supportedLanguages.languages);
+ }
- public Builder language(Language language) {
- Objects.requireNonNull(language, "language is null");
- this.languages.put(language.getCode(), language);
- return this;
- }
+ public Builder language(Language language) {
+ Objects.requireNonNull(language, "language is null");
+ this.languages.put(language.getCode(), language);
+ return this;
+ }
- public Builder language(Language.Builder languageBuilder) {
- Objects.requireNonNull(languageBuilder, "languageBuilder is null");
- Language language = languageBuilder.build();
- this.languages.put(language.getCode(), language);
- return this;
- }
+ public Builder language(Language.Builder languageBuilder) {
+ Objects.requireNonNull(languageBuilder, "languageBuilder is null");
+ Language language = languageBuilder.build();
+ this.languages.put(language.getCode(), language);
+ return this;
+ }
- public SupportedLanguages build() {
- return new SupportedLanguages(this);
- }
- }
+ public SupportedLanguages build() {
+ return new SupportedLanguages(this);
+ }
+ }
- public static class Deserializer extends JsonDeserializer {
+ public static class Deserializer extends JsonDeserializer {
- @Override
- public SupportedLanguages deserialize(JsonParser parser, DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
+ @Override
+ public SupportedLanguages deserialize(JsonParser parser, DeserializationContext ctxt)
+ throws IOException, JsonProcessingException {
- Builder builder = SupportedLanguages.builder();
+ Builder builder = SupportedLanguages.builder();
- ObjectCodec codec = parser.getCodec();
- TreeNode node = codec.readTree(parser);
+ ObjectCodec codec = parser.getCodec();
+ TreeNode node = codec.readTree(parser);
- if (node.isArray()) {
- for (JsonNode n : (ArrayNode) node) {
- Language language = ctxt.readTreeAsValue(n, Language.class);
- builder.language(language);
- }
- }
- return builder.build();
- }
- }
+ if (node.isArray()) {
+ for (JsonNode n : (ArrayNode) node) {
+ Language language = ctxt.readTreeAsValue(n, Language.class);
+ builder.language(language);
+ }
+ }
+ return builder.build();
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/SupportedProvider.java b/src/main/java/com/sitepark/translate/SupportedProvider.java
index b8da5a7..fe59631 100644
--- a/src/main/java/com/sitepark/translate/SupportedProvider.java
+++ b/src/main/java/com/sitepark/translate/SupportedProvider.java
@@ -3,32 +3,31 @@
import java.util.Arrays;
public enum SupportedProvider {
-
- DEEPL("deepl"),
- LIBRE_TRANSLATE("libretranslate");
-
- private final String schema;
-
- private SupportedProvider(String schema) {
- this.schema = schema;
- }
-
- public static SupportedProvider ofScheme(String name) {
- for (SupportedProvider type : SupportedProvider.values()) {
- if (type.getSchema().equals(name)) {
- return type;
- }
- }
- throw new IllegalArgumentException("scheme '" + name + "' not found");
- }
-
- public String getSchema() {
- return this.schema;
- }
-
- public static String[] scheme() {
- return Arrays.stream(SupportedProvider.values())
- .map(SupportedProvider::getSchema)
- .toArray(String[]::new);
- }
+ DEEPL("deepl"),
+ LIBRE_TRANSLATE("libretranslate");
+
+ private final String schema;
+
+ private SupportedProvider(String schema) {
+ this.schema = schema;
+ }
+
+ public static SupportedProvider ofScheme(String name) {
+ for (SupportedProvider type : SupportedProvider.values()) {
+ if (type.getSchema().equals(name)) {
+ return type;
+ }
+ }
+ throw new IllegalArgumentException("scheme '" + name + "' not found");
+ }
+
+ public String getSchema() {
+ return this.schema;
+ }
+
+ public static String[] scheme() {
+ return Arrays.stream(SupportedProvider.values())
+ .map(SupportedProvider::getSchema)
+ .toArray(String[]::new);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationCache.java b/src/main/java/com/sitepark/translate/TranslationCache.java
index 30e947f..4d31a15 100644
--- a/src/main/java/com/sitepark/translate/TranslationCache.java
+++ b/src/main/java/com/sitepark/translate/TranslationCache.java
@@ -1,10 +1,9 @@
package com.sitepark.translate;
+import com.sitepark.translate.translator.TranslatableText;
import java.util.List;
import java.util.Optional;
-import com.sitepark.translate.translator.TranslatableText;
-
/**
* With the caching implementation you can prevent that already translated
* texts are translated again. This can be useful if, for example, a list
@@ -14,14 +13,14 @@
*/
public interface TranslationCache {
- /**
- * Returns an non empty optional, if the translation is cached.
- */
- public Optional translate(String sourceText);
+ /**
+ * Returns an non empty optional, if the translation is cached.
+ */
+ public Optional translate(String sourceText);
- /**
- * Passes all translated texts of a translation process. Also those that
- * were determined via caching.
- */
- public void update(List extends TranslatableText> translated);
+ /**
+ * Passes all translated texts of a translation process. Also those that
+ * were determined via caching.
+ */
+ public void update(List extends TranslatableText> translated);
}
diff --git a/src/main/java/com/sitepark/translate/TranslationConfiguration.java b/src/main/java/com/sitepark/translate/TranslationConfiguration.java
index eaad7e9..381fee2 100644
--- a/src/main/java/com/sitepark/translate/TranslationConfiguration.java
+++ b/src/main/java/com/sitepark/translate/TranslationConfiguration.java
@@ -8,114 +8,116 @@
public final class TranslationConfiguration {
- private final TranslationCache translationCache;
-
- private final TranslationProviderFactory translationProviderFactory;
-
- private final Map, TranslationProviderConfiguration>
- translationProviderConfigurations;
-
- private final boolean encodePlaceholder;
-
- private TranslationConfiguration(Builder builder) {
- this.translationCache = builder.translationCache;
- this.translationProviderConfigurations = Collections.unmodifiableMap(
- builder.translationProviderConfigurations);
- this.encodePlaceholder = builder.encodePlaceholder;
- if (builder.translationProviderFactory == null) {
- this.translationProviderFactory = new TranslationProviderFactory(this);
- } else {
- this.translationProviderFactory = builder.translationProviderFactory;
- }
- }
-
- public Optional getTranslationCache() {
- return Optional.ofNullable(this.translationCache);
- }
-
- public TranslationProviderFactory getTranslationProviderFactory() {
- return this.translationProviderFactory;
- }
-
- public SupportedProvider[] getConfiguredProvider() {
- return this.translationProviderConfigurations.values().stream()
- .map(TranslationProviderConfiguration::getType)
- .toArray(SupportedProvider[]::new);
- }
-
- @SuppressWarnings("unchecked")
- public T getTranslationProviderConfiguration(Class type) {
- T provider = (T)this.translationProviderConfigurations.get(type);
- if (provider == null) {
- throw new IllegalArgumentException("Provider configuration " + type.getName() + " not found");
- }
- return provider;
- }
-
- public boolean isEncodePlaceholder() {
- return this.encodePlaceholder;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- @SuppressWarnings("PMD.TooManyMethods")
- public final static class Builder {
-
- private TranslationCache translationCache;
-
- private TranslationProviderFactory translationProviderFactory;
-
- private final Map, TranslationProviderConfiguration>
- translationProviderConfigurations = new ConcurrentHashMap<>();
-
- private boolean encodePlaceholder;
-
- private Builder() { }
-
- private Builder(TranslationConfiguration translatorConfiguration) {
- this.translationCache = translatorConfiguration.translationCache;
- this.translationProviderFactory = translatorConfiguration.translationProviderFactory;
- this.translationProviderConfigurations.putAll(
- translatorConfiguration.translationProviderConfigurations);
- this.encodePlaceholder = translatorConfiguration.encodePlaceholder;
- }
-
- public Builder translationCache(TranslationCache translationCache) {
- Objects.requireNonNull(translationCache, "translationCache is null");
- this.translationCache = translationCache;
- return this;
- }
-
- public Builder translationProviderFactory(TranslationProviderFactory translatorProviderFactory) {
- Objects.requireNonNull(translatorProviderFactory, "translatorProviderFactory is null");
- this.translationProviderFactory = translatorProviderFactory;
- return this;
- }
-
- public Builder translationProviderConfiguration(
- TranslationProviderConfiguration translationProviderConfiguration) {
- Objects.requireNonNull(
- translationProviderConfiguration,
- "translationProviderConfiguration is null");
- this.translationProviderConfigurations.put(
- translationProviderConfiguration.getClass(),
- translationProviderConfiguration);
- return this;
- }
-
- public Builder encodePlaceholder(boolean encodePlaceholder) {
- this.encodePlaceholder = encodePlaceholder;
- return this;
- }
-
- public TranslationConfiguration build() {
- return new TranslationConfiguration(this);
- }
- }
+ private final TranslationCache translationCache;
+
+ private final TranslationProviderFactory translationProviderFactory;
+
+ private final Map<
+ Class extends TranslationProviderConfiguration>, TranslationProviderConfiguration>
+ translationProviderConfigurations;
+
+ private final boolean encodePlaceholder;
+
+ private TranslationConfiguration(Builder builder) {
+ this.translationCache = builder.translationCache;
+ this.translationProviderConfigurations =
+ Collections.unmodifiableMap(builder.translationProviderConfigurations);
+ this.encodePlaceholder = builder.encodePlaceholder;
+ if (builder.translationProviderFactory == null) {
+ this.translationProviderFactory = new TranslationProviderFactory(this);
+ } else {
+ this.translationProviderFactory = builder.translationProviderFactory;
+ }
+ }
+
+ public Optional getTranslationCache() {
+ return Optional.ofNullable(this.translationCache);
+ }
+
+ public TranslationProviderFactory getTranslationProviderFactory() {
+ return this.translationProviderFactory;
+ }
+
+ public SupportedProvider[] getConfiguredProvider() {
+ return this.translationProviderConfigurations.values().stream()
+ .map(TranslationProviderConfiguration::getType)
+ .toArray(SupportedProvider[]::new);
+ }
+
+ @SuppressWarnings("unchecked")
+ public T getTranslationProviderConfiguration(
+ Class type) {
+ T provider = (T) this.translationProviderConfigurations.get(type);
+ if (provider == null) {
+ throw new IllegalArgumentException("Provider configuration " + type.getName() + " not found");
+ }
+ return provider;
+ }
+
+ public boolean isEncodePlaceholder() {
+ return this.encodePlaceholder;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ @SuppressWarnings("PMD.TooManyMethods")
+ public static final class Builder {
+
+ private TranslationCache translationCache;
+
+ private TranslationProviderFactory translationProviderFactory;
+
+ private final Map<
+ Class extends TranslationProviderConfiguration>, TranslationProviderConfiguration>
+ translationProviderConfigurations = new ConcurrentHashMap<>();
+
+ private boolean encodePlaceholder;
+
+ private Builder() {}
+
+ private Builder(TranslationConfiguration translatorConfiguration) {
+ this.translationCache = translatorConfiguration.translationCache;
+ this.translationProviderFactory = translatorConfiguration.translationProviderFactory;
+ this.translationProviderConfigurations.putAll(
+ translatorConfiguration.translationProviderConfigurations);
+ this.encodePlaceholder = translatorConfiguration.encodePlaceholder;
+ }
+
+ public Builder translationCache(TranslationCache translationCache) {
+ Objects.requireNonNull(translationCache, "translationCache is null");
+ this.translationCache = translationCache;
+ return this;
+ }
+
+ public Builder translationProviderFactory(
+ TranslationProviderFactory translatorProviderFactory) {
+ Objects.requireNonNull(translatorProviderFactory, "translatorProviderFactory is null");
+ this.translationProviderFactory = translatorProviderFactory;
+ return this;
+ }
+
+ public Builder translationProviderConfiguration(
+ TranslationProviderConfiguration translationProviderConfiguration) {
+ Objects.requireNonNull(
+ translationProviderConfiguration, "translationProviderConfiguration is null");
+ this.translationProviderConfigurations.put(
+ translationProviderConfiguration.getClass(), translationProviderConfiguration);
+ return this;
+ }
+
+ public Builder encodePlaceholder(boolean encodePlaceholder) {
+ this.encodePlaceholder = encodePlaceholder;
+ return this;
+ }
+
+ public TranslationConfiguration build() {
+ return new TranslationConfiguration(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationEvent.java b/src/main/java/com/sitepark/translate/TranslationEvent.java
index 6743b1d..61aeb0e 100644
--- a/src/main/java/com/sitepark/translate/TranslationEvent.java
+++ b/src/main/java/com/sitepark/translate/TranslationEvent.java
@@ -4,108 +4,108 @@
public final class TranslationEvent {
- private final TranslationLanguage translationLanguage;
-
- private final long translationTime;
-
- private final int chunks;
-
- private final int sourceBytes;
-
- private final int targetBytes;
-
- private TranslationEvent(Builder builder) {
- this.translationLanguage = builder.translationLanguage;
- this.translationTime = builder.translationTime;
- this.chunks = builder.chunks;
- this.sourceBytes = builder.sourceBytes;
- this.targetBytes = builder.targetBytes;
- }
-
- /**
- * Source and target language of the translation.
- */
- public TranslationLanguage getTranslationLanguage() {
- return this.translationLanguage;
- }
-
- /**
- * Time in milliseconds that the translation took.
- */
- public long getTranslationTime() {
- return this.translationTime;
- }
-
- /**
- * Number of texts passed to libretranslate in an array.
- */
- public int getChunks() {
- return this.chunks;
- }
-
- /**
- * Number of bytes that were translated
- */
- public int getSourceBytes() {
- return this.sourceBytes;
- }
-
- /**
- * Number of bytes of the translated text.
- */
- public int getTargetBytes() {
- return this.targetBytes;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public final static class Builder {
-
- private TranslationLanguage translationLanguage;
-
- private long translationTime;
-
- private int chunks;
-
- private int sourceBytes;
-
- private int targetBytes;
-
- private Builder() {}
-
- public Builder translationLanguage(TranslationLanguage translationLanguage) {
- Objects.requireNonNull(translationLanguage, "translationLanguage is null");
- this.translationLanguage = translationLanguage;
- return this;
- }
-
- public Builder translationTime(long translationTime) {
- this.translationTime = translationTime;
- return this;
- }
-
- public Builder chunks(int chunks) {
- this.chunks = chunks;
- return this;
- }
-
- public Builder sourceBytes(int sourceBytes) {
- this.sourceBytes = sourceBytes;
- return this;
- }
-
- public Builder targetBytes(int targetBytes) {
- this.targetBytes = targetBytes;
- return this;
- }
-
- public TranslationEvent build() {
- if (this.translationLanguage == null) {
- throw new IllegalStateException("translationLanguage is not set");
- }
- return new TranslationEvent(this);
- }
- }
+ private final TranslationLanguage translationLanguage;
+
+ private final long translationTime;
+
+ private final int chunks;
+
+ private final int sourceBytes;
+
+ private final int targetBytes;
+
+ private TranslationEvent(Builder builder) {
+ this.translationLanguage = builder.translationLanguage;
+ this.translationTime = builder.translationTime;
+ this.chunks = builder.chunks;
+ this.sourceBytes = builder.sourceBytes;
+ this.targetBytes = builder.targetBytes;
+ }
+
+ /**
+ * Source and target language of the translation.
+ */
+ public TranslationLanguage getTranslationLanguage() {
+ return this.translationLanguage;
+ }
+
+ /**
+ * Time in milliseconds that the translation took.
+ */
+ public long getTranslationTime() {
+ return this.translationTime;
+ }
+
+ /**
+ * Number of texts passed to libretranslate in an array.
+ */
+ public int getChunks() {
+ return this.chunks;
+ }
+
+ /**
+ * Number of bytes that were translated
+ */
+ public int getSourceBytes() {
+ return this.sourceBytes;
+ }
+
+ /**
+ * Number of bytes of the translated text.
+ */
+ public int getTargetBytes() {
+ return this.targetBytes;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+
+ private TranslationLanguage translationLanguage;
+
+ private long translationTime;
+
+ private int chunks;
+
+ private int sourceBytes;
+
+ private int targetBytes;
+
+ private Builder() {}
+
+ public Builder translationLanguage(TranslationLanguage translationLanguage) {
+ Objects.requireNonNull(translationLanguage, "translationLanguage is null");
+ this.translationLanguage = translationLanguage;
+ return this;
+ }
+
+ public Builder translationTime(long translationTime) {
+ this.translationTime = translationTime;
+ return this;
+ }
+
+ public Builder chunks(int chunks) {
+ this.chunks = chunks;
+ return this;
+ }
+
+ public Builder sourceBytes(int sourceBytes) {
+ this.sourceBytes = sourceBytes;
+ return this;
+ }
+
+ public Builder targetBytes(int targetBytes) {
+ this.targetBytes = targetBytes;
+ return this;
+ }
+
+ public TranslationEvent build() {
+ if (this.translationLanguage == null) {
+ throw new IllegalStateException("translationLanguage is not set");
+ }
+ return new TranslationEvent(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationLanguage.java b/src/main/java/com/sitepark/translate/TranslationLanguage.java
index 9445347..6537bc7 100644
--- a/src/main/java/com/sitepark/translate/TranslationLanguage.java
+++ b/src/main/java/com/sitepark/translate/TranslationLanguage.java
@@ -4,93 +4,92 @@
public final class TranslationLanguage {
- private final String source;
-
- private final String target;
-
- private TranslationLanguage(Builder builder) {
- this.source = builder.source;
- this.target = builder.target;
- }
-
- public String getSource() {
- return this.source;
- }
-
- public String getTarget() {
- return this.target;
- }
-
- @Override
- public int hashCode() {
- int hashCode = 0;
- if (this.source != null) {
- hashCode += this.source.hashCode();
- }
- if (this.target != null) {
- hashCode += this.target.hashCode();
- }
- return hashCode;
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof TranslationLanguage)) {
- return false;
- }
-
- TranslationLanguage lang = (TranslationLanguage)o;
- return
- Objects.equals(lang.getSource(), this.source) &&
- Objects.equals(lang.getTarget(), this.target);
- }
-
- @Override
- public String toString() {
- return this.source + " - " + this.target;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- public final static class Builder {
-
- private String source;
-
- private String target;
-
- private Builder() { }
-
- private Builder(TranslationLanguage translationLanguage) {
- this.source = translationLanguage.source;
- this.target = translationLanguage.target;
- }
-
- public Builder source(String source) {
- Objects.requireNonNull(source, "source is null");
- this.source = source;
- return this;
- }
-
- public Builder target(String target) {
- Objects.requireNonNull(target, "target is null");
- this.target = target;
- return this;
- }
-
- public TranslationLanguage build() {
- if (this.source == null) {
- throw new IllegalStateException("source is not set");
- }
- if (this.target == null) {
- throw new IllegalStateException("target is not set");
- }
- return new TranslationLanguage(this);
- }
- }
+ private final String source;
+
+ private final String target;
+
+ private TranslationLanguage(Builder builder) {
+ this.source = builder.source;
+ this.target = builder.target;
+ }
+
+ public String getSource() {
+ return this.source;
+ }
+
+ public String getTarget() {
+ return this.target;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 0;
+ if (this.source != null) {
+ hashCode += this.source.hashCode();
+ }
+ if (this.target != null) {
+ hashCode += this.target.hashCode();
+ }
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof TranslationLanguage)) {
+ return false;
+ }
+
+ TranslationLanguage lang = (TranslationLanguage) o;
+ return Objects.equals(lang.getSource(), this.source)
+ && Objects.equals(lang.getTarget(), this.target);
+ }
+
+ @Override
+ public String toString() {
+ return this.source + " - " + this.target;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ public static final class Builder {
+
+ private String source;
+
+ private String target;
+
+ private Builder() {}
+
+ private Builder(TranslationLanguage translationLanguage) {
+ this.source = translationLanguage.source;
+ this.target = translationLanguage.target;
+ }
+
+ public Builder source(String source) {
+ Objects.requireNonNull(source, "source is null");
+ this.source = source;
+ return this;
+ }
+
+ public Builder target(String target) {
+ Objects.requireNonNull(target, "target is null");
+ this.target = target;
+ return this;
+ }
+
+ public TranslationLanguage build() {
+ if (this.source == null) {
+ throw new IllegalStateException("source is not set");
+ }
+ if (this.target == null) {
+ throw new IllegalStateException("target is not set");
+ }
+ return new TranslationLanguage(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationParameter.java b/src/main/java/com/sitepark/translate/TranslationParameter.java
index 23cc815..9b8aa70 100644
--- a/src/main/java/com/sitepark/translate/TranslationParameter.java
+++ b/src/main/java/com/sitepark/translate/TranslationParameter.java
@@ -5,99 +5,98 @@
public final class TranslationParameter {
- private final Format format;
+ private final Format format;
- private final SupportedProvider providerType;
+ private final SupportedProvider providerType;
- private final TranslationLanguage language;
+ private final TranslationLanguage language;
- private final String glossaryId;
+ private final String glossaryId;
- private TranslationParameter(Builder builder) {
- this.format = builder.format;
- this.providerType = builder.providerType;
- this.language = builder.language;
- this.glossaryId = builder.glossaryId;
- }
+ private TranslationParameter(Builder builder) {
+ this.format = builder.format;
+ this.providerType = builder.providerType;
+ this.language = builder.language;
+ this.glossaryId = builder.glossaryId;
+ }
- public Optional getFormat() {
- return Optional.ofNullable(this.format);
- }
+ public Optional getFormat() {
+ return Optional.ofNullable(this.format);
+ }
- public SupportedProvider getProviderType() {
- return this.providerType;
- }
+ public SupportedProvider getProviderType() {
+ return this.providerType;
+ }
- public TranslationLanguage getLanguage() {
- return this.language;
- }
+ public TranslationLanguage getLanguage() {
+ return this.language;
+ }
- public Optional getGlossaryId() {
- return Optional.ofNullable(this.glossaryId);
- }
+ public Optional getGlossaryId() {
+ return Optional.ofNullable(this.glossaryId);
+ }
- public static Builder builder() {
- return new Builder();
- }
+ public static Builder builder() {
+ return new Builder();
+ }
- public Builder toBuilder() {
- return new Builder(this);
- }
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
- public final static class Builder {
+ public static final class Builder {
- private Format format;
+ private Format format;
- private SupportedProvider providerType;
+ private SupportedProvider providerType;
- private TranslationLanguage language;
+ private TranslationLanguage language;
- private String glossaryId;
+ private String glossaryId;
- private Builder() {
- }
+ private Builder() {}
- private Builder(TranslationParameter translationParameter) {
- this.format = translationParameter.format;
- this.providerType = translationParameter.providerType;
- this.language = translationParameter.language.toBuilder().build();
- this.glossaryId = translationParameter.glossaryId;
- }
+ private Builder(TranslationParameter translationParameter) {
+ this.format = translationParameter.format;
+ this.providerType = translationParameter.providerType;
+ this.language = translationParameter.language.toBuilder().build();
+ this.glossaryId = translationParameter.glossaryId;
+ }
- public Builder providerType(SupportedProvider providerType) {
- Objects.requireNonNull(providerType, "providerType is null");
- this.providerType = providerType;
- return this;
- }
+ public Builder providerType(SupportedProvider providerType) {
+ Objects.requireNonNull(providerType, "providerType is null");
+ this.providerType = providerType;
+ return this;
+ }
- public Builder format(Format format) {
- Objects.requireNonNull(format, "format is null");
- this.format = format;
- return this;
- }
+ public Builder format(Format format) {
+ Objects.requireNonNull(format, "format is null");
+ this.format = format;
+ return this;
+ }
- public Builder language(TranslationLanguage language) {
- Objects.requireNonNull(language, "language is null");
- this.language = language;
- return this;
- }
+ public Builder language(TranslationLanguage language) {
+ Objects.requireNonNull(language, "language is null");
+ this.language = language;
+ return this;
+ }
- public Builder glossaryId(String glossaryId) {
- Objects.requireNonNull(glossaryId, "glossaryId is null");
- this.glossaryId = glossaryId;
- return this;
- }
+ public Builder glossaryId(String glossaryId) {
+ Objects.requireNonNull(glossaryId, "glossaryId is null");
+ this.glossaryId = glossaryId;
+ return this;
+ }
- public TranslationParameter build() {
+ public TranslationParameter build() {
- if (this.providerType == null) {
- throw new IllegalStateException("providerType is not set");
- }
- if (this.language == null) {
- throw new IllegalStateException("language is not set");
- }
+ if (this.providerType == null) {
+ throw new IllegalStateException("providerType is not set");
+ }
+ if (this.language == null) {
+ throw new IllegalStateException("language is not set");
+ }
- return new TranslationParameter(this);
- }
- }
+ return new TranslationParameter(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationProvider.java b/src/main/java/com/sitepark/translate/TranslationProvider.java
index 93fb66d..fb6746d 100644
--- a/src/main/java/com/sitepark/translate/TranslationProvider.java
+++ b/src/main/java/com/sitepark/translate/TranslationProvider.java
@@ -3,10 +3,15 @@
import java.util.Optional;
public interface TranslationProvider {
- SupportedLanguages getSupportedLanguages();
- TranslationResult translate(TranslationRequest req);
- Optional getGlossary(String id);
- Optional getGlossaryId(String name);
- String recreate(Glossary glossar);
- void removeGlossary(String id);
+ SupportedLanguages getSupportedLanguages();
+
+ TranslationResult translate(TranslationRequest req);
+
+ Optional getGlossary(String id);
+
+ Optional getGlossaryId(String name);
+
+ String recreate(Glossary glossar);
+
+ void removeGlossary(String id);
}
diff --git a/src/main/java/com/sitepark/translate/TranslationProviderConfiguration.java b/src/main/java/com/sitepark/translate/TranslationProviderConfiguration.java
index 6ff5bb3..11568db 100644
--- a/src/main/java/com/sitepark/translate/TranslationProviderConfiguration.java
+++ b/src/main/java/com/sitepark/translate/TranslationProviderConfiguration.java
@@ -1,5 +1,5 @@
package com.sitepark.translate;
public interface TranslationProviderConfiguration {
- public SupportedProvider getType();
+ public SupportedProvider getType();
}
diff --git a/src/main/java/com/sitepark/translate/TranslationProviderException.java b/src/main/java/com/sitepark/translate/TranslationProviderException.java
index 9e2ca01..4332329 100644
--- a/src/main/java/com/sitepark/translate/TranslationProviderException.java
+++ b/src/main/java/com/sitepark/translate/TranslationProviderException.java
@@ -2,14 +2,13 @@
public class TranslationProviderException extends RuntimeException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public TranslationProviderException(String msg) {
- super(msg);
- }
-
- public TranslationProviderException(String msg, Throwable t) {
- super(msg, t);
- }
+ public TranslationProviderException(String msg) {
+ super(msg);
+ }
+ public TranslationProviderException(String msg, Throwable t) {
+ super(msg, t);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationProviderFactory.java b/src/main/java/com/sitepark/translate/TranslationProviderFactory.java
index 6505fe7..0f5aa43 100644
--- a/src/main/java/com/sitepark/translate/TranslationProviderFactory.java
+++ b/src/main/java/com/sitepark/translate/TranslationProviderFactory.java
@@ -5,28 +5,27 @@
public class TranslationProviderFactory {
- private final TranslationConfiguration translatorConfiguration;
-
- public TranslationProviderFactory(TranslationConfiguration translatorConfiguration) {
- this.translatorConfiguration = translatorConfiguration;
- }
-
- public TranslationProvider create(SupportedProvider type) {
- if (type == SupportedProvider.LIBRE_TRANSLATE) {
- return this.createLibreTranslateTranslationProvider();
- } else if (type == SupportedProvider.DEEPL) {
- return this.createDeeplTranslationProvider();
- } else {
- throw new IllegalArgumentException("Unsupported provider " + type);
- }
- }
-
- private LibreTranslateTranslationProvider createLibreTranslateTranslationProvider() {
- return new LibreTranslateTranslationProvider(this.translatorConfiguration);
- }
-
- private DeeplTranslationProvider createDeeplTranslationProvider() {
- return new DeeplTranslationProvider(this.translatorConfiguration);
- }
-
+ private final TranslationConfiguration translatorConfiguration;
+
+ public TranslationProviderFactory(TranslationConfiguration translatorConfiguration) {
+ this.translatorConfiguration = translatorConfiguration;
+ }
+
+ public TranslationProvider create(SupportedProvider type) {
+ if (type == SupportedProvider.LIBRE_TRANSLATE) {
+ return this.createLibreTranslateTranslationProvider();
+ } else if (type == SupportedProvider.DEEPL) {
+ return this.createDeeplTranslationProvider();
+ } else {
+ throw new IllegalArgumentException("Unsupported provider " + type);
+ }
+ }
+
+ private LibreTranslateTranslationProvider createLibreTranslateTranslationProvider() {
+ return new LibreTranslateTranslationProvider(this.translatorConfiguration);
+ }
+
+ private DeeplTranslationProvider createDeeplTranslationProvider() {
+ return new DeeplTranslationProvider(this.translatorConfiguration);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationRequest.java b/src/main/java/com/sitepark/translate/TranslationRequest.java
index 988bd04..140bea2 100644
--- a/src/main/java/com/sitepark/translate/TranslationRequest.java
+++ b/src/main/java/com/sitepark/translate/TranslationRequest.java
@@ -5,70 +5,69 @@
public final class TranslationRequest {
- private final TranslationParameter parameter;
+ private final TranslationParameter parameter;
- private final String[] sourceText;
+ private final String[] sourceText;
- private TranslationRequest(Builder builder) {
- this.parameter = builder.parameter;
- this.sourceText = builder.sourceText;
- }
+ private TranslationRequest(Builder builder) {
+ this.parameter = builder.parameter;
+ this.sourceText = builder.sourceText;
+ }
- public String[] getSourceText() {
- return Arrays.copyOf(this.sourceText, this.sourceText.length);
- }
+ public String[] getSourceText() {
+ return Arrays.copyOf(this.sourceText, this.sourceText.length);
+ }
- public TranslationParameter getParameter() {
- return this.parameter;
- }
+ public TranslationParameter getParameter() {
+ return this.parameter;
+ }
- public static Builder builder() {
- return new Builder();
- }
+ public static Builder builder() {
+ return new Builder();
+ }
- public Builder toBuilder() {
- return new Builder(this);
- }
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
- public final static class Builder {
+ public static final class Builder {
- private TranslationParameter parameter;
+ private TranslationParameter parameter;
- private String[] sourceText;
+ private String[] sourceText;
- private Builder() {
- }
+ private Builder() {}
- private Builder(TranslationRequest translationRequest) {
- this.parameter = translationRequest.parameter;
- this.sourceText = translationRequest.sourceText;
- }
+ private Builder(TranslationRequest translationRequest) {
+ this.parameter = translationRequest.parameter;
+ this.sourceText = translationRequest.sourceText;
+ }
- public Builder sourceText(String... sourceText) {
- Objects.requireNonNull(sourceText, "sourceText is null");
- for (String text : sourceText) {
- Objects.requireNonNull(text, "sourceText contains null value");
- }
- this.sourceText = Arrays.copyOf(sourceText, sourceText.length);
- return this;
- }
+ public Builder sourceText(String... sourceText) {
+ Objects.requireNonNull(sourceText, "sourceText is null");
+ for (String text : sourceText) {
+ Objects.requireNonNull(text, "sourceText contains null value");
+ }
+ this.sourceText = Arrays.copyOf(sourceText, sourceText.length);
+ return this;
+ }
- public Builder parameter(TranslationParameter parameter) {
- Objects.requireNonNull(parameter, "parameter is null");
- this.parameter = parameter;
- return this;
- }
+ public Builder parameter(TranslationParameter parameter) {
+ Objects.requireNonNull(parameter, "parameter is null");
+ this.parameter = parameter;
+ return this;
+ }
- public TranslationRequest build() {
+ public TranslationRequest build() {
- if (this.parameter == null) {
- throw new IllegalStateException("parameter is not set");
- }
- if (this.sourceText == null) {
- throw new IllegalStateException("sourceText is not set");
- }
+ if (this.parameter == null) {
+ throw new IllegalStateException("parameter is not set");
+ }
+ if (this.sourceText == null) {
+ throw new IllegalStateException("sourceText is not set");
+ }
- return new TranslationRequest(this);
- }
- }
+ return new TranslationRequest(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationResult.java b/src/main/java/com/sitepark/translate/TranslationResult.java
index c9fb38c..64bdce8 100644
--- a/src/main/java/com/sitepark/translate/TranslationResult.java
+++ b/src/main/java/com/sitepark/translate/TranslationResult.java
@@ -5,89 +5,88 @@
public final class TranslationResult {
- private final TranslationRequest request;
-
- private final String[] text;
-
- private final TranslationResultStatistic statistic;
-
- private TranslationResult(Builder builder) {
- this.request = builder.request;
- this.text = builder.text;
- this.statistic = builder.statistic;
- }
-
- public TranslationRequest getRequest() {
- return this.request;
- }
-
- public String[] getText() {
- return Arrays.copyOf(this.text, this.text.length);
- }
-
- public TranslationResultStatistic getStatistic() {
- return this.statistic;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- public final static class Builder {
-
- private TranslationRequest request;
-
- private String[] text;
-
- private TranslationResultStatistic statistic;
-
- private Builder() {
- }
-
- private Builder(TranslationResult result) {
- this.request = result.request;
- this.text = result.text;
- this.statistic = result.statistic;
- }
-
- public Builder request(TranslationRequest request) {
- Objects.requireNonNull(request, "request is null");
- this.request = request;
- return this;
- }
-
- public Builder text(String... text) {
- Objects.requireNonNull(text, "text is null");
- for (String s : text) {
- Objects.requireNonNull(s, "value in text is null");
- }
- this.text = Arrays.copyOf(text, text.length);
- return this;
- }
-
- public Builder statistic(TranslationResultStatistic statistic) {
- Objects.requireNonNull(statistic, "statistic is null");
- this.statistic = statistic;
- return this;
- }
-
- public TranslationResult build() {
-
- if (this.request == null) {
- throw new IllegalStateException("request is not set");
- }
- if (this.text == null) {
- throw new IllegalStateException("text is not set");
- }
- if (this.statistic == null) {
- throw new IllegalStateException("statistic is not set");
- }
-
- return new TranslationResult(this);
- }
- }
+ private final TranslationRequest request;
+
+ private final String[] text;
+
+ private final TranslationResultStatistic statistic;
+
+ private TranslationResult(Builder builder) {
+ this.request = builder.request;
+ this.text = builder.text;
+ this.statistic = builder.statistic;
+ }
+
+ public TranslationRequest getRequest() {
+ return this.request;
+ }
+
+ public String[] getText() {
+ return Arrays.copyOf(this.text, this.text.length);
+ }
+
+ public TranslationResultStatistic getStatistic() {
+ return this.statistic;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ public static final class Builder {
+
+ private TranslationRequest request;
+
+ private String[] text;
+
+ private TranslationResultStatistic statistic;
+
+ private Builder() {}
+
+ private Builder(TranslationResult result) {
+ this.request = result.request;
+ this.text = result.text;
+ this.statistic = result.statistic;
+ }
+
+ public Builder request(TranslationRequest request) {
+ Objects.requireNonNull(request, "request is null");
+ this.request = request;
+ return this;
+ }
+
+ public Builder text(String... text) {
+ Objects.requireNonNull(text, "text is null");
+ for (String s : text) {
+ Objects.requireNonNull(s, "value in text is null");
+ }
+ this.text = Arrays.copyOf(text, text.length);
+ return this;
+ }
+
+ public Builder statistic(TranslationResultStatistic statistic) {
+ Objects.requireNonNull(statistic, "statistic is null");
+ this.statistic = statistic;
+ return this;
+ }
+
+ public TranslationResult build() {
+
+ if (this.request == null) {
+ throw new IllegalStateException("request is not set");
+ }
+ if (this.text == null) {
+ throw new IllegalStateException("text is not set");
+ }
+ if (this.statistic == null) {
+ throw new IllegalStateException("statistic is not set");
+ }
+
+ return new TranslationResult(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/TranslationResultStatistic.java b/src/main/java/com/sitepark/translate/TranslationResultStatistic.java
index 693e9b0..3692aed 100644
--- a/src/main/java/com/sitepark/translate/TranslationResultStatistic.java
+++ b/src/main/java/com/sitepark/translate/TranslationResultStatistic.java
@@ -2,119 +2,115 @@
public final class TranslationResultStatistic {
- private final long translationTime;
-
- private final int chunks;
-
- private final long sourceBytes;
-
- private final long targetBytes;
-
- public static final TranslationResultStatistic EMPTY = TranslationResultStatistic.builder()
- .translationTime(0)
- .chunks(0)
- .sourceBytes(0)
- .targetBytes(0)
- .build();
-
- private TranslationResultStatistic(Builder builder) {
- this.translationTime = builder.translationTime;
- this.chunks = builder.chunks;
- this.sourceBytes = builder.sourceBytes;
- this.targetBytes = builder.targetBytes;
- }
-
- public long getTranslationTime() {
- return this.translationTime;
- }
-
- public int getChunks() {
- return this.chunks;
- }
-
- public long getSourceBytes() {
- return this.sourceBytes;
- }
-
- public long getTargetBytes() {
- return this.targetBytes;
- }
-
- public TranslationResultStatistic add(TranslationResultStatistic statistic) {
- return TranslationResultStatistic.builder()
- .translationTime(this.translationTime + statistic.getTranslationTime())
- .chunks(this.chunks + statistic.getChunks())
- .sourceBytes(this.sourceBytes + statistic.getSourceBytes())
- .targetBytes(this.targetBytes + statistic.getTargetBytes())
- .build();
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- public final static class Builder {
-
- private long translationTime;
-
- private int chunks;
-
- private long sourceBytes;
-
- private long targetBytes;
-
- private Builder() {
- }
-
- private Builder(TranslationResultStatistic result) {
- this.translationTime = result.translationTime;
- this.chunks = result.chunks;
- this.sourceBytes = result.sourceBytes;
- this.targetBytes = result.targetBytes;
- }
-
- public Builder translationTime(long translationTime) {
- if (translationTime < 0) {
- throw new IllegalArgumentException(
- "translationTime should be greate equals then 0");
- }
- this.translationTime = translationTime;
- return this;
- }
-
- public Builder chunks(int chunks) {
- if (chunks < 0) {
- throw new IllegalArgumentException(
- "chunks should be greate equals then 0");
- }
- this.chunks = chunks;
- return this;
- }
-
- public Builder sourceBytes(long sourceBytes) {
- if (sourceBytes < 0) {
- throw new IllegalArgumentException(
- "sourceBytes should be greate equals then 0");
- }
- this.sourceBytes = sourceBytes;
- return this;
- }
-
- public Builder targetBytes(long targetBytes) {
- if (targetBytes < 0) {
- throw new IllegalArgumentException(
- "targetBytes should be greate equals then 0");
- }
- this.targetBytes = targetBytes;
- return this;
- }
-
- public TranslationResultStatistic build() {
- return new TranslationResultStatistic(this);
- }
- }
+ private final long translationTime;
+
+ private final int chunks;
+
+ private final long sourceBytes;
+
+ private final long targetBytes;
+
+ public static final TranslationResultStatistic EMPTY =
+ TranslationResultStatistic.builder()
+ .translationTime(0)
+ .chunks(0)
+ .sourceBytes(0)
+ .targetBytes(0)
+ .build();
+
+ private TranslationResultStatistic(Builder builder) {
+ this.translationTime = builder.translationTime;
+ this.chunks = builder.chunks;
+ this.sourceBytes = builder.sourceBytes;
+ this.targetBytes = builder.targetBytes;
+ }
+
+ public long getTranslationTime() {
+ return this.translationTime;
+ }
+
+ public int getChunks() {
+ return this.chunks;
+ }
+
+ public long getSourceBytes() {
+ return this.sourceBytes;
+ }
+
+ public long getTargetBytes() {
+ return this.targetBytes;
+ }
+
+ public TranslationResultStatistic add(TranslationResultStatistic statistic) {
+ return TranslationResultStatistic.builder()
+ .translationTime(this.translationTime + statistic.getTranslationTime())
+ .chunks(this.chunks + statistic.getChunks())
+ .sourceBytes(this.sourceBytes + statistic.getSourceBytes())
+ .targetBytes(this.targetBytes + statistic.getTargetBytes())
+ .build();
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ public static final class Builder {
+
+ private long translationTime;
+
+ private int chunks;
+
+ private long sourceBytes;
+
+ private long targetBytes;
+
+ private Builder() {}
+
+ private Builder(TranslationResultStatistic result) {
+ this.translationTime = result.translationTime;
+ this.chunks = result.chunks;
+ this.sourceBytes = result.sourceBytes;
+ this.targetBytes = result.targetBytes;
+ }
+
+ public Builder translationTime(long translationTime) {
+ if (translationTime < 0) {
+ throw new IllegalArgumentException("translationTime should be greate equals then 0");
+ }
+ this.translationTime = translationTime;
+ return this;
+ }
+
+ public Builder chunks(int chunks) {
+ if (chunks < 0) {
+ throw new IllegalArgumentException("chunks should be greate equals then 0");
+ }
+ this.chunks = chunks;
+ return this;
+ }
+
+ public Builder sourceBytes(long sourceBytes) {
+ if (sourceBytes < 0) {
+ throw new IllegalArgumentException("sourceBytes should be greate equals then 0");
+ }
+ this.sourceBytes = sourceBytes;
+ return this;
+ }
+
+ public Builder targetBytes(long targetBytes) {
+ if (targetBytes < 0) {
+ throw new IllegalArgumentException("targetBytes should be greate equals then 0");
+ }
+ this.targetBytes = targetBytes;
+ return this;
+ }
+
+ public TranslationResultStatistic build() {
+ return new TranslationResultStatistic(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/cli/Main.java b/src/main/java/com/sitepark/translate/cli/Main.java
index 2c8edb8..1ed4b3a 100644
--- a/src/main/java/com/sitepark/translate/cli/Main.java
+++ b/src/main/java/com/sitepark/translate/cli/Main.java
@@ -3,23 +3,23 @@
@SuppressWarnings("PMD.SystemPrintln")
public final class Main {
- private Main() {}
+ private Main() {}
- public static void main(String... argv) {
+ public static void main(String... argv) {
- if (argv.length == 0) {
- System.out.println("missing command");
- return;
- }
+ if (argv.length == 0) {
+ System.out.println("missing command");
+ return;
+ }
- String command = argv[0];
- String[] arguments = new String[argv.length - 1];
- System.arraycopy(argv, 1, arguments, 0, argv.length - 1);
+ String command = argv[0];
+ String[] arguments = new String[argv.length - 1];
+ System.arraycopy(argv, 1, arguments, 0, argv.length - 1);
- if (TranslateJson.COMMAND_NAME.equals(command)) {
- TranslateJson.execute(arguments);
- } else {
- System.err.println("unknown command: " + command);
- }
- }
+ if (TranslateJson.COMMAND_NAME.equals(command)) {
+ TranslateJson.execute(arguments);
+ } else {
+ System.err.println("unknown command: " + command);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/cli/TranslateJson.java b/src/main/java/com/sitepark/translate/cli/TranslateJson.java
index 59b0240..884d242 100644
--- a/src/main/java/com/sitepark/translate/cli/TranslateJson.java
+++ b/src/main/java/com/sitepark/translate/cli/TranslateJson.java
@@ -1,5 +1,11 @@
package com.sitepark.translate.cli;
+import com.sitepark.translate.SupportedProvider;
+import com.sitepark.translate.TranslationConfiguration;
+import com.sitepark.translate.TranslationProviderConfiguration;
+import com.sitepark.translate.provider.deepl.DeeplTranslationProviderConfiguration;
+import com.sitepark.translate.provider.libretranslate.LibreTranslateTranslationProviderConfiguration;
+import com.sitepark.translate.translator.JsonFileListTranslator;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
@@ -14,173 +20,168 @@
import java.util.List;
import java.util.Map;
-import com.sitepark.translate.SupportedProvider;
-import com.sitepark.translate.TranslationConfiguration;
-import com.sitepark.translate.TranslationProviderConfiguration;
-import com.sitepark.translate.provider.deepl.DeeplTranslationProviderConfiguration;
-import com.sitepark.translate.provider.libretranslate.LibreTranslateTranslationProviderConfiguration;
-import com.sitepark.translate.translator.JsonFileListTranslator;
-
@SuppressWarnings("PMD")
public class TranslateJson {
- private JsonFileListTranslator jsonFileListTranslator;
-
- private SupportedProvider providerType;
-
- private List targetLanguages;
-
- public static final String COMMAND_NAME = "translate-json";
-
- public static void execute(String... arguments) {
-
- TranslateJson command = new TranslateJson();
-
- try {
- command.parseArguments(arguments);
- command.run();
- } catch (Exception e) {
- System.err.println("ERROR: " + e.getMessage());
- e.printStackTrace();
- command.usage();
- }
- }
-
- protected JsonFileListTranslator getTranslator() {
- return this.jsonFileListTranslator;
- }
-
- protected void parseArguments(String... arguments) {
-
- if (arguments.length < 4) {
- throw new IllegalArgumentException(", , [target-language]... expected");
- }
-
- String url = arguments[0];
- Path dir = Paths.get(arguments[1]).toAbsolutePath();
- String sourceLang = arguments[2];
- Path output = Paths.get(arguments[3]).toAbsolutePath();
- Path sourceDir = dir.resolve(sourceLang);
- if (!Files.exists(sourceDir)) {
- throw new IllegalArgumentException("source-dir " + sourceDir + " not exitst");
- }
-
- if (arguments.length > 4) {
- this.targetLanguages = new ArrayList<>();
- for (int i = 4; i < arguments.length; i++) {
- this.targetLanguages.add(arguments[i]);
- }
- }
-
- TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder()
- .encodePlaceholder(true)
- .translationProviderConfiguration(this.createTranslationProviderConfigurationByUrl(url))
- .build();
-
- this.jsonFileListTranslator = JsonFileListTranslator.builder()
- .dir(dir)
- .output(output)
- .sourceLang(sourceLang)
- .translatorConfiguration(translatorConfiguration)
- .logger(new ConsoleLogger(true))
- .build();
- }
-
- protected TranslationProviderConfiguration createTranslationProviderConfigurationByUrl(String s) {
- try {
- URI url = new URI(s);
-
- this.providerType = SupportedProvider.ofScheme(url.getScheme());
-
- Map params = this.splitQuery(new URI(url.getSchemeSpecificPart()));
-
- String providerUrl = url.getSchemeSpecificPart();
- int paramStart = providerUrl.indexOf('?');
- if (paramStart != -1) {
- providerUrl = providerUrl.substring(0, paramStart);
- }
-
- if (this.providerType == SupportedProvider.LIBRE_TRANSLATE) {
- LibreTranslateTranslationProviderConfiguration.Builder builder =
- LibreTranslateTranslationProviderConfiguration.builder()
- .url(providerUrl);
- if (params.containsKey("apiKey")) {
- builder.apiKey(params.get("apiKey"));
- }
- return builder.build();
- } else if (this.providerType == SupportedProvider.DEEPL) {
- return DeeplTranslationProviderConfiguration.builder()
- .url(providerUrl)
- .authKey(params.get("authKey"))
- .build();
- } else {
- throw new IllegalArgumentException("Unsupported provider " + this.providerType);
- }
-
- } catch (URISyntaxException | UnsupportedEncodingException e) {
- throw new IllegalArgumentException("url " + s +
- " invalid: " + e.getMessage(), e);
- }
- }
-
- private Map splitQuery(URI url) throws UnsupportedEncodingException {
- String query = url.getQuery();
- if (query == null) {
- return Collections.emptyMap();
- }
- Map queryPairs = new LinkedHashMap<>();
- String[] pairs = query.split("&");
- for (String pair : pairs) {
- int idx = pair.indexOf("=");
- queryPairs.put(
- URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
- URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
- }
- return queryPairs;
- }
-
-
- protected void run() throws IOException {
- assert this.jsonFileListTranslator != null : "jsonFileListTranslator is null";
- this.jsonFileListTranslator.translate(this.providerType, this.targetLanguages);
- }
-
- private void usage() {
- System.out.println("translate translate-json ");
- System.out.println("");
- System.out.println(" URL to translation server: " +
- ":http[s]://host/[?params]");
- System.out.println(" directory in which language specific subfolders");
- System.out.println(" \"de\", \"en\", ... are contained.");
- System.out.println(" Language to be translated. This must also be ");
- System.out.println(" as a directory in .");
- System.out.println(" directory in which the translations are written");
- System.out.println("");
- System.out.println("Supported provider-scheme:");
- for (String provider : SupportedProvider.scheme()) {
- System.out.println(" " + provider);
- }
- }
-
- private static class ConsoleLogger implements JsonFileListTranslator.Logger {
-
- private final boolean printStackTrace;
-
- private ConsoleLogger(boolean printStackTrace) {
- this.printStackTrace = printStackTrace;
- }
-
- @Override
- public void info(String msg) {
- System.out.println(msg);
- }
-
- @Override
- public void error(String msg, Throwable t) {
- System.err.println(msg);
- if (this.printStackTrace) {
- t.printStackTrace();
- }
- }
- }
+ private JsonFileListTranslator jsonFileListTranslator;
+
+ private SupportedProvider providerType;
+
+ private List targetLanguages;
+
+ public static final String COMMAND_NAME = "translate-json";
+
+ public static void execute(String... arguments) {
+
+ TranslateJson command = new TranslateJson();
+
+ try {
+ command.parseArguments(arguments);
+ command.run();
+ } catch (Exception e) {
+ System.err.println("ERROR: " + e.getMessage());
+ e.printStackTrace();
+ command.usage();
+ }
+ }
+
+ protected JsonFileListTranslator getTranslator() {
+ return this.jsonFileListTranslator;
+ }
+
+ protected void parseArguments(String... arguments) {
+
+ if (arguments.length < 4) {
+ throw new IllegalArgumentException(
+ ", , [target-language]... expected");
+ }
+
+ String url = arguments[0];
+ Path dir = Paths.get(arguments[1]).toAbsolutePath();
+ String sourceLang = arguments[2];
+ Path output = Paths.get(arguments[3]).toAbsolutePath();
+ Path sourceDir = dir.resolve(sourceLang);
+ if (!Files.exists(sourceDir)) {
+ throw new IllegalArgumentException("source-dir " + sourceDir + " not exitst");
+ }
+
+ if (arguments.length > 4) {
+ this.targetLanguages = new ArrayList<>();
+ for (int i = 4; i < arguments.length; i++) {
+ this.targetLanguages.add(arguments[i]);
+ }
+ }
+
+ TranslationConfiguration translatorConfiguration =
+ TranslationConfiguration.builder()
+ .encodePlaceholder(true)
+ .translationProviderConfiguration(this.createTranslationProviderConfigurationByUrl(url))
+ .build();
+
+ this.jsonFileListTranslator =
+ JsonFileListTranslator.builder()
+ .dir(dir)
+ .output(output)
+ .sourceLang(sourceLang)
+ .translatorConfiguration(translatorConfiguration)
+ .logger(new ConsoleLogger(true))
+ .build();
+ }
+
+ protected TranslationProviderConfiguration createTranslationProviderConfigurationByUrl(String s) {
+ try {
+ URI url = new URI(s);
+
+ this.providerType = SupportedProvider.ofScheme(url.getScheme());
+
+ Map params = this.splitQuery(new URI(url.getSchemeSpecificPart()));
+
+ String providerUrl = url.getSchemeSpecificPart();
+ int paramStart = providerUrl.indexOf('?');
+ if (paramStart != -1) {
+ providerUrl = providerUrl.substring(0, paramStart);
+ }
+
+ if (this.providerType == SupportedProvider.LIBRE_TRANSLATE) {
+ LibreTranslateTranslationProviderConfiguration.Builder builder =
+ LibreTranslateTranslationProviderConfiguration.builder().url(providerUrl);
+ if (params.containsKey("apiKey")) {
+ builder.apiKey(params.get("apiKey"));
+ }
+ return builder.build();
+ } else if (this.providerType == SupportedProvider.DEEPL) {
+ return DeeplTranslationProviderConfiguration.builder()
+ .url(providerUrl)
+ .authKey(params.get("authKey"))
+ .build();
+ } else {
+ throw new IllegalArgumentException("Unsupported provider " + this.providerType);
+ }
+
+ } catch (URISyntaxException | UnsupportedEncodingException e) {
+ throw new IllegalArgumentException("url " + s + " invalid: " + e.getMessage(), e);
+ }
+ }
+
+ private Map splitQuery(URI url) throws UnsupportedEncodingException {
+ String query = url.getQuery();
+ if (query == null) {
+ return Collections.emptyMap();
+ }
+ Map queryPairs = new LinkedHashMap<>();
+ String[] pairs = query.split("&");
+ for (String pair : pairs) {
+ int idx = pair.indexOf("=");
+ queryPairs.put(
+ URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
+ URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
+ }
+ return queryPairs;
+ }
+
+ protected void run() throws IOException {
+ assert this.jsonFileListTranslator != null : "jsonFileListTranslator is null";
+ this.jsonFileListTranslator.translate(this.providerType, this.targetLanguages);
+ }
+
+ private void usage() {
+ System.out.println(
+ "translate translate-json ");
+ System.out.println("");
+ System.out.println(
+ " URL to translation server: "
+ + ":http[s]://host/[?params]");
+ System.out.println(" directory in which language specific subfolders");
+ System.out.println(" \"de\", \"en\", ... are contained.");
+ System.out.println(" Language to be translated. This must also be ");
+ System.out.println(" as a directory in .");
+ System.out.println(" directory in which the translations are written");
+ System.out.println("");
+ System.out.println("Supported provider-scheme:");
+ for (String provider : SupportedProvider.scheme()) {
+ System.out.println(" " + provider);
+ }
+ }
+
+ private static class ConsoleLogger implements JsonFileListTranslator.Logger {
+
+ private final boolean printStackTrace;
+
+ private ConsoleLogger(boolean printStackTrace) {
+ this.printStackTrace = printStackTrace;
+ }
+
+ @Override
+ public void info(String msg) {
+ System.out.println(msg);
+ }
+
+ @Override
+ public void error(String msg, Throwable t) {
+ System.err.println(msg);
+ if (this.printStackTrace) {
+ t.printStackTrace();
+ }
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/CreateGlossaryRequest.java b/src/main/java/com/sitepark/translate/provider/deepl/CreateGlossaryRequest.java
index 47375e2..27dba82 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/CreateGlossaryRequest.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/CreateGlossaryRequest.java
@@ -4,73 +4,68 @@
import com.sitepark.translate.Glossary;
import com.sitepark.translate.GlossaryEntry;
import com.sitepark.translate.TranslationProviderException;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
public final class CreateGlossaryRequest {
- public final String name;
- @JsonProperty("source_lang")
- public final String sourceLang;
- @JsonProperty("target_lang")
- public final String targetLang;
- public final String entries;
- @JsonProperty("entries_format")
- public final String entriesFormat;
+ public final String name;
+
+ @JsonProperty("source_lang")
+ public final String sourceLang;
+
+ @JsonProperty("target_lang")
+ public final String targetLang;
+
+ public final String entries;
+
+ @JsonProperty("entries_format")
+ public final String entriesFormat;
- private CreateGlossaryRequest(
- String name,
- String sourceLang,
- String targetLang,
- String entries,
- String entriesFormat) {
- this.name = name;
- this.sourceLang = sourceLang;
- this.targetLang = targetLang;
- this.entries = entries;
- this.entriesFormat = entriesFormat;
- }
+ private CreateGlossaryRequest(
+ String name, String sourceLang, String targetLang, String entries, String entriesFormat) {
+ this.name = name;
+ this.sourceLang = sourceLang;
+ this.targetLang = targetLang;
+ this.entries = entries;
+ this.entriesFormat = entriesFormat;
+ }
- @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
- public static CreateGlossaryRequest build(Glossary glossary) {
+ @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
+ public static CreateGlossaryRequest build(Glossary glossary) {
- StringBuilder entries = new StringBuilder();
- for (GlossaryEntry entry : glossary.getEntryList()) {
+ StringBuilder entries = new StringBuilder();
+ for (GlossaryEntry entry : glossary.getEntryList()) {
- CreateGlossaryRequest.validateEntry(entry);
+ CreateGlossaryRequest.validateEntry(entry);
- entries
- .append(entry.getSource())
- .append('\t')
- .append(entry.getTarget())
- .append('\n');
- }
+ entries.append(entry.getSource()).append('\t').append(entry.getTarget()).append('\n');
+ }
- return new CreateGlossaryRequest(
- glossary.getName(),
- glossary.getLanguage().getSource(),
- glossary.getLanguage().getTarget(),
- entries.toString(),
- "tsv");
- }
+ return new CreateGlossaryRequest(
+ glossary.getName(),
+ glossary.getLanguage().getSource(),
+ glossary.getLanguage().getTarget(),
+ entries.toString(),
+ "tsv");
+ }
- private static void validateEntry(GlossaryEntry entry) {
+ private static void validateEntry(GlossaryEntry entry) {
- if (entry.getSource().indexOf('\t') != -1) {
- throw new TranslationProviderException(
- "The source text must not contain a tab: " + entry.getSource());
- }
- if (entry.getSource().indexOf('\n') != -1) {
- throw new TranslationProviderException(
- "The source text must not contain a newline: " + entry.getSource());
- }
- if (entry.getTarget().indexOf('\t') != -1) {
- throw new TranslationProviderException(
- "The target text must not contain a tab: " + entry.getSource());
- }
- if (entry.getTarget().indexOf('\n') != -1) {
- throw new TranslationProviderException(
- "The target text must not contain a newline: " + entry.getSource());
- }
- }
+ if (entry.getSource().indexOf('\t') != -1) {
+ throw new TranslationProviderException(
+ "The source text must not contain a tab: " + entry.getSource());
+ }
+ if (entry.getSource().indexOf('\n') != -1) {
+ throw new TranslationProviderException(
+ "The source text must not contain a newline: " + entry.getSource());
+ }
+ if (entry.getTarget().indexOf('\t') != -1) {
+ throw new TranslationProviderException(
+ "The target text must not contain a tab: " + entry.getSource());
+ }
+ if (entry.getTarget().indexOf('\n') != -1) {
+ throw new TranslationProviderException(
+ "The target text must not contain a newline: " + entry.getSource());
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProvider.java b/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProvider.java
index b1185a9..2e34157 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProvider.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProvider.java
@@ -1,17 +1,5 @@
package com.sitepark.translate.provider.deepl;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URLEncoder;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sitepark.translate.Format;
@@ -29,430 +17,453 @@
import com.sitepark.translate.translator.UnifiedSourceText;
import com.sitepark.translate.translator.entity.Decoder;
import com.sitepark.translate.translator.entity.Encoder;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
@SuppressFBWarnings
@SuppressWarnings("PMD")
public class DeeplTranslationProvider implements TranslationProvider {
- private final TranslationConfiguration translatorConfiguration;
-
- public DeeplTranslationProvider(TranslationConfiguration translatorConfiguration) {
- this.translatorConfiguration = translatorConfiguration;
- }
-
- public TranslationResult translate(TranslationRequest req) {
-
- String[] sourceTextToTranslate = req.getSourceText();
- if (req.getParameter().getFormat().isPresent() &&
- req.getParameter().getFormat().get() == Format.HTML) {
- sourceTextToTranslate = this.encodePlacerholder(req.getSourceText());
- }
-
- UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceTextToTranslate);
-
- TranslationRequest modifiedReq = req.toBuilder()
- .sourceText(unifiedSourceText.getSourceText())
- .build();
- try {
-
- long start = System.currentTimeMillis();
-
- String[] translated = translationRequest(modifiedReq);
-
- String[] decodedTranslation = this.decodePlacerholder(translated);
-
- return TranslationResult.builder()
- .request(req)
- .text(unifiedSourceText.expandTranslation(decodedTranslation))
- .statistic(TranslationResultStatistic.builder()
- .chunks(req.getSourceText().length)
- .translationTime(System.currentTimeMillis() - start)
- .sourceBytes(this.byteCount(unifiedSourceText.getSourceText()))
- .targetBytes(this.byteCount(translated))
- .build()
- )
- .build();
-
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
-
- protected String[] translationRequest(TranslationRequest req)
- throws IOException, InterruptedException {
-
- URI uri = this.buildUri("/translate");
-
- TranslationLanguage language = req.getParameter().getLanguage();
-
- List params = new ArrayList<>();
- params.add(new String[] {"source_lang", language.getSource()});
- params.add(new String[] {"target_lang", language.getTarget()});
- if (req.getParameter().getFormat().isPresent() &&
- req.getParameter().getFormat().get() == Format.HTML) {
- params.add(new String[] {"tag_handling", Format.HTML.toString().toLowerCase()});
- }
- for (String text : req.getSourceText()) {
- params.add(new String[] {"text", text});
- }
- req.getParameter().getGlossaryId().ifPresent(glossarId -> {
- params.add(new String[] {"glossary_id", glossarId});
- });
-
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "application/json")
- .header("Content-Type", "application/x-www-form-urlencoded")
- .POST(this.buildBody(params))
- .build();
-
- HttpClient client = this.createHttpClient();
-
- var response = client
- .send(request, new JsonBodyHandler<>(TransportResponse.class, ErrorResponse.class))
- .body();
-
- var result = response.get();
-
- if (result.isSuccess()) {
- return result.getSuccessValue().getTranslations();
- } else {
- throw result.getErrorValue().toException();
- }
- }
-
- private DeeplTranslationProviderConfiguration getProviderConfiguration() {
- return this.translatorConfiguration.getTranslationProviderConfiguration(
- DeeplTranslationProviderConfiguration.class);
- }
-
-
- private HttpRequest.BodyPublisher buildBody(List params) {
- var builder = new StringBuilder();
- for (String[] param : params) {
- String name = param[0];
- String value = param[1];
- if (builder.length() > 0) {
- builder.append("&");
- }
- builder.append(URLEncoder.encode(name, StandardCharsets.UTF_8));
- builder.append("=");
- builder.append(URLEncoder.encode(value, StandardCharsets.UTF_8));
- }
- return HttpRequest.BodyPublishers.ofString(builder.toString());
- }
-
- private String[] encodePlacerholder(String... q) {
- if (!this.translatorConfiguration.isEncodePlaceholder()) {
- return q;
- }
-
- return Encoder.encode(q);
- }
-
- private String[] decodePlacerholder(String... q) {
-
- if (!this.translatorConfiguration.isEncodePlaceholder()) {
- return q;
- }
-
- return Decoder.decode(q);
- }
-
- private int byteCount(String... array) {
- int count = 0;
- for (String s : array) {
- count += s.getBytes(StandardCharsets.UTF_8).length;
- }
- return count;
- }
-
- public SupportedLanguages getSupportedLanguages() {
-
- SupportedLanguages.Builder builder = SupportedLanguages.builder();
-
- List sourceLanguageList = this.getSourceLanguages();
- List targetLanguageList = this.getTargetLanguages();
-
- for (TransportLanguage sourceLanguage : sourceLanguageList) {
- Language language = Language.builder()
- .code(sourceLanguage.getLanguage().toLowerCase())
- .name(sourceLanguage.getName())
- .targets(targetLanguageList.stream()
- .map(l -> l.getLanguage().toLowerCase())
- .collect(Collectors.toList())
- )
- .build();
- builder.language(language);
- }
-
- return builder.build();
- }
-
- private List getSourceLanguages() {
- return this.getLanguages(LanguageType.SOURCE);
- }
-
- private List getTargetLanguages() {
- return this.getLanguages(LanguageType.TARGET);
- }
-
- protected List getLanguages(LanguageType type) {
-
- URI uri = this.buildUri("/languages?type=" + type);
-
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "application/json")
- .build();
-
- HttpClient client = this.createHttpClient();
-
- try {
- return client.send(request, new JsonBodyLanguagesHandler()).body().get();
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
-
- private URI buildUri(String path) {
- try {
- return new URI(this.getProviderConfiguration().getUri() + path);
- } catch (URISyntaxException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
-
- private HttpClient createHttpClient() {
- HttpClient.Builder builder = HttpClient.newBuilder();
- if (this.getProviderConfiguration().getProxy().isPresent()) {
- builder.proxy(this.getProviderConfiguration().getProxy().get());
- }
- return builder.build();
- }
-
- @Override
- public Optional getGlossary(String id) {
-
- Optional response = this.getGlossaryResponse(id);
- if (response.isEmpty()) {
- return Optional.empty();
- }
-
- return Optional.of(Glossary.builder()
- .name(response.get().name)
- .language(TranslationLanguage.builder()
- .source(response.get().sourceLang)
- .target(response.get().targetLang)
- .build()
- )
- .entryList(this.getGlossaryEntries(id))
- .build());
- }
-
- @Override
- public Optional getGlossaryId(String name) {
- List glossaries = this.getGlossaries(name);
- return glossaries.stream().map(res -> res.glossaryId).findFirst();
- }
-
- private List getGlossaries(String name) {
-
- List glossaries = new ArrayList<>();
-
- for (GlossaryResponse glossary : this.getGlossaries()) {
- if (!glossary.name.equals(name)) {
- continue;
- }
- glossaries.add(glossary);
- }
- return glossaries;
- }
-
- private List getGlossaries() {
-
- URI uri = this.buildUri("/glossaries");
-
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "application/json")
- .build();
-
- HttpClient client = this.createHttpClient();
-
- try {
- var response = client
- .send(request, new JsonBodyHandler<>(GlossaryListResponse.class, ErrorResponse.class))
- .body();
-
- var result = response.get();
-
- if (!result.isSuccess()) {
- throw result.getErrorValue().toException();
- }
-
- return result.getSuccessValue().glossaries;
-
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
-
- private List getGlossaryEntries(String id) {
-
- URI uri = this.buildUri("/glossaries/" + id + "/entries");
-
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "text/tab-separated-values")
- .build();
- HttpClient client = this.createHttpClient();
-
- try {
- var response = client
- .send(request, new JsonBodyHandler<>(String.class, ErrorResponse.class))
- .body();
+ private final TranslationConfiguration translatorConfiguration;
+
+ public DeeplTranslationProvider(TranslationConfiguration translatorConfiguration) {
+ this.translatorConfiguration = translatorConfiguration;
+ }
+
+ public TranslationResult translate(TranslationRequest req) {
+
+ String[] sourceTextToTranslate = req.getSourceText();
+ if (req.getParameter().getFormat().isPresent()
+ && req.getParameter().getFormat().get() == Format.HTML) {
+ sourceTextToTranslate = this.encodePlacerholder(req.getSourceText());
+ }
+
+ UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceTextToTranslate);
+
+ TranslationRequest modifiedReq =
+ req.toBuilder().sourceText(unifiedSourceText.getSourceText()).build();
+ try {
+
+ long start = System.currentTimeMillis();
+
+ String[] translated = translationRequest(modifiedReq);
+
+ String[] decodedTranslation = this.decodePlacerholder(translated);
+
+ return TranslationResult.builder()
+ .request(req)
+ .text(unifiedSourceText.expandTranslation(decodedTranslation))
+ .statistic(
+ TranslationResultStatistic.builder()
+ .chunks(req.getSourceText().length)
+ .translationTime(System.currentTimeMillis() - start)
+ .sourceBytes(this.byteCount(unifiedSourceText.getSourceText()))
+ .targetBytes(this.byteCount(translated))
+ .build())
+ .build();
+
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
+
+ protected String[] translationRequest(TranslationRequest req)
+ throws IOException, InterruptedException {
+
+ URI uri = this.buildUri("/translate");
+
+ TranslationLanguage language = req.getParameter().getLanguage();
+
+ List params = new ArrayList<>();
+ params.add(new String[] {"source_lang", language.getSource()});
+ params.add(new String[] {"target_lang", language.getTarget()});
+ if (req.getParameter().getFormat().isPresent()
+ && req.getParameter().getFormat().get() == Format.HTML) {
+ params.add(new String[] {"tag_handling", Format.HTML.toString().toLowerCase()});
+ }
+ for (String text : req.getSourceText()) {
+ params.add(new String[] {"text", text});
+ }
+ req.getParameter()
+ .getGlossaryId()
+ .ifPresent(
+ glossarId -> {
+ params.add(new String[] {"glossary_id", glossarId});
+ });
+
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "application/json")
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .POST(this.buildBody(params))
+ .build();
+
+ HttpClient client = this.createHttpClient();
+
+ var response =
+ client
+ .send(request, new JsonBodyHandler<>(TransportResponse.class, ErrorResponse.class))
+ .body();
+
+ var result = response.get();
+
+ if (result.isSuccess()) {
+ return result.getSuccessValue().getTranslations();
+ } else {
+ throw result.getErrorValue().toException();
+ }
+ }
+
+ private DeeplTranslationProviderConfiguration getProviderConfiguration() {
+ return this.translatorConfiguration.getTranslationProviderConfiguration(
+ DeeplTranslationProviderConfiguration.class);
+ }
+
+ private HttpRequest.BodyPublisher buildBody(List params) {
+ var builder = new StringBuilder();
+ for (String[] param : params) {
+ String name = param[0];
+ String value = param[1];
+ if (builder.length() > 0) {
+ builder.append("&");
+ }
+ builder.append(URLEncoder.encode(name, StandardCharsets.UTF_8));
+ builder.append("=");
+ builder.append(URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ return HttpRequest.BodyPublishers.ofString(builder.toString());
+ }
+
+ private String[] encodePlacerholder(String... q) {
+ if (!this.translatorConfiguration.isEncodePlaceholder()) {
+ return q;
+ }
+
+ return Encoder.encode(q);
+ }
+
+ private String[] decodePlacerholder(String... q) {
+
+ if (!this.translatorConfiguration.isEncodePlaceholder()) {
+ return q;
+ }
+
+ return Decoder.decode(q);
+ }
+
+ private int byteCount(String... array) {
+ int count = 0;
+ for (String s : array) {
+ count += s.getBytes(StandardCharsets.UTF_8).length;
+ }
+ return count;
+ }
+
+ public SupportedLanguages getSupportedLanguages() {
+
+ SupportedLanguages.Builder builder = SupportedLanguages.builder();
+
+ List sourceLanguageList = this.getSourceLanguages();
+ List targetLanguageList = this.getTargetLanguages();
+
+ for (TransportLanguage sourceLanguage : sourceLanguageList) {
+ Language language =
+ Language.builder()
+ .code(sourceLanguage.getLanguage().toLowerCase())
+ .name(sourceLanguage.getName())
+ .targets(
+ targetLanguageList.stream()
+ .map(l -> l.getLanguage().toLowerCase())
+ .collect(Collectors.toList()))
+ .build();
+ builder.language(language);
+ }
+
+ return builder.build();
+ }
+
+ private List getSourceLanguages() {
+ return this.getLanguages(LanguageType.SOURCE);
+ }
+
+ private List getTargetLanguages() {
+ return this.getLanguages(LanguageType.TARGET);
+ }
+
+ protected List getLanguages(LanguageType type) {
+
+ URI uri = this.buildUri("/languages?type=" + type);
+
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "application/json")
+ .build();
+
+ HttpClient client = this.createHttpClient();
+
+ try {
+ return client.send(request, new JsonBodyLanguagesHandler()).body().get();
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
+
+ private URI buildUri(String path) {
+ try {
+ return new URI(this.getProviderConfiguration().getUri() + path);
+ } catch (URISyntaxException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
+
+ private HttpClient createHttpClient() {
+ HttpClient.Builder builder = HttpClient.newBuilder();
+ if (this.getProviderConfiguration().getProxy().isPresent()) {
+ builder.proxy(this.getProviderConfiguration().getProxy().get());
+ }
+ return builder.build();
+ }
+
+ @Override
+ public Optional getGlossary(String id) {
+
+ Optional response = this.getGlossaryResponse(id);
+ if (response.isEmpty()) {
+ return Optional.empty();
+ }
+
+ return Optional.of(
+ Glossary.builder()
+ .name(response.get().name)
+ .language(
+ TranslationLanguage.builder()
+ .source(response.get().sourceLang)
+ .target(response.get().targetLang)
+ .build())
+ .entryList(this.getGlossaryEntries(id))
+ .build());
+ }
+
+ @Override
+ public Optional getGlossaryId(String name) {
+ List glossaries = this.getGlossaries(name);
+ return glossaries.stream().map(res -> res.glossaryId).findFirst();
+ }
+
+ private List getGlossaries(String name) {
+
+ List glossaries = new ArrayList<>();
+
+ for (GlossaryResponse glossary : this.getGlossaries()) {
+ if (!glossary.name.equals(name)) {
+ continue;
+ }
+ glossaries.add(glossary);
+ }
+ return glossaries;
+ }
+
+ private List getGlossaries() {
+
+ URI uri = this.buildUri("/glossaries");
+
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "application/json")
+ .build();
+
+ HttpClient client = this.createHttpClient();
+
+ try {
+ var response =
+ client
+ .send(request, new JsonBodyHandler<>(GlossaryListResponse.class, ErrorResponse.class))
+ .body();
+
+ var result = response.get();
+
+ if (!result.isSuccess()) {
+ throw result.getErrorValue().toException();
+ }
+
+ return result.getSuccessValue().glossaries;
+
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
+
+ private List getGlossaryEntries(String id) {
+
+ URI uri = this.buildUri("/glossaries/" + id + "/entries");
+
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "text/tab-separated-values")
+ .build();
+ HttpClient client = this.createHttpClient();
+
+ try {
+ var response =
+ client.send(request, new JsonBodyHandler<>(String.class, ErrorResponse.class)).body();
- var result = response.get();
+ var result = response.get();
- if (!result.isSuccess()) {
- throw result.getErrorValue().toException();
- }
+ if (!result.isSuccess()) {
+ throw result.getErrorValue().toException();
+ }
- List entries = new ArrayList<>();
+ List entries = new ArrayList<>();
- for (String line : result.getSuccessValue().split("\n")) {
- String[] values = line.split("\t");
- String source = values[0];
- String target = values[1];
+ for (String line : result.getSuccessValue().split("\n")) {
+ String[] values = line.split("\t");
+ String source = values[0];
+ String target = values[1];
- entries.add(GlossaryEntry.builder()
- .source(source)
- .target(target)
- .build()
- );
- }
+ entries.add(GlossaryEntry.builder().source(source).target(target).build());
+ }
- return entries;
+ return entries;
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
- private Optional getGlossaryResponse(String id) {
+ private Optional getGlossaryResponse(String id) {
- URI uri = this.buildUri("/glossaries/" + id);
+ URI uri = this.buildUri("/glossaries/" + id);
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "application/json")
- .build();
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "application/json")
+ .build();
- HttpClient client = this.createHttpClient();
+ HttpClient client = this.createHttpClient();
- try {
- var response = client
- .send(request, new JsonBodyHandler<>(GlossaryResponse.class, ErrorResponse.class))
- .body();
+ try {
+ var response =
+ client
+ .send(request, new JsonBodyHandler<>(GlossaryResponse.class, ErrorResponse.class))
+ .body();
- var result = response.get();
+ var result = response.get();
- if (result.isSuccess()) {
- return Optional.of(result.getSuccessValue());
- }
+ if (result.isSuccess()) {
+ return Optional.of(result.getSuccessValue());
+ }
- if (result.getStatusCode() == 404) {
- return Optional.empty();
- }
+ if (result.getStatusCode() == 404) {
+ return Optional.empty();
+ }
- throw result.getErrorValue().toException();
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
+ throw result.getErrorValue().toException();
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
- @Override
- public void removeGlossary(String id) {
+ @Override
+ public void removeGlossary(String id) {
- URI uri = this.buildUri("/glossaries/" + id);
+ URI uri = this.buildUri("/glossaries/" + id);
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "application/json")
- .DELETE()
- .build();
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "application/json")
+ .DELETE()
+ .build();
- HttpClient client = this.createHttpClient();
+ HttpClient client = this.createHttpClient();
- try {
- var response = client
- .send(request, new JsonBodyHandler<>(String.class, ErrorResponse.class))
- .body();
+ try {
+ var response =
+ client.send(request, new JsonBodyHandler<>(String.class, ErrorResponse.class)).body();
- var result = response.get();
+ var result = response.get();
- if (!result.isSuccess()) {
- throw result.getErrorValue().toException();
- }
+ if (!result.isSuccess()) {
+ throw result.getErrorValue().toException();
+ }
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
- @Override
- public String recreate(Glossary glossary) {
+ @Override
+ public String recreate(Glossary glossary) {
- List glossaries = this.getGlossaries(glossary.getName());
+ List glossaries = this.getGlossaries(glossary.getName());
- for (GlossaryResponse res : glossaries) {
- this.removeGlossary(res.glossaryId);
- }
+ for (GlossaryResponse res : glossaries) {
+ this.removeGlossary(res.glossaryId);
+ }
- CreateGlossaryRequest req = CreateGlossaryRequest.build(glossary);
+ CreateGlossaryRequest req = CreateGlossaryRequest.build(glossary);
- URI uri = this.buildUri("/glossaries");
+ URI uri = this.buildUri("/glossaries");
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
- .header("Accept", "application/json")
- .header("Content-Type", "application/json")
- .POST(this.buildBody(req))
- .build();
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header(
+ "Authorization", "DeepL-Auth-Key " + this.getProviderConfiguration().getAuthKey())
+ .header("Accept", "application/json")
+ .header("Content-Type", "application/json")
+ .POST(this.buildBody(req))
+ .build();
- HttpClient client = this.createHttpClient();
+ HttpClient client = this.createHttpClient();
- try {
- var response = client
- .send(request, new JsonBodyHandler<>(GlossaryResponse.class, ErrorResponse.class))
- .body();
+ try {
+ var response =
+ client
+ .send(request, new JsonBodyHandler<>(GlossaryResponse.class, ErrorResponse.class))
+ .body();
- var result = response.get();
+ var result = response.get();
- if (!result.isSuccess()) {
- throw result.getErrorValue().toException();
- }
+ if (!result.isSuccess()) {
+ throw result.getErrorValue().toException();
+ }
- return result.getSuccessValue().glossaryId;
+ return result.getSuccessValue().glossaryId;
- } catch (InterruptedException | IOException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
+ } catch (InterruptedException | IOException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
- private HttpRequest.BodyPublisher buildBody(Object o) {
+ private HttpRequest.BodyPublisher buildBody(Object o) {
- try {
- ObjectMapper objectMapper = new ObjectMapper();
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
- return HttpRequest.BodyPublishers.ofString(
- objectMapper.writeValueAsString(o)
- );
- } catch (JsonProcessingException e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- }
+ return HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(o));
+ } catch (JsonProcessingException e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfiguration.java b/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfiguration.java
index b4c8d98..76785ef 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfiguration.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfiguration.java
@@ -1,5 +1,7 @@
package com.sitepark.translate.provider.deepl;
+import com.sitepark.translate.SupportedProvider;
+import com.sitepark.translate.TranslationProviderConfiguration;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
@@ -7,106 +9,104 @@
import java.util.Objects;
import java.util.Optional;
-import com.sitepark.translate.SupportedProvider;
-import com.sitepark.translate.TranslationProviderConfiguration;
-
-public final class DeeplTranslationProviderConfiguration implements TranslationProviderConfiguration {
-
- private final URI uri;
-
- private final ProxySelector proxy;
-
- private final String authKey;
-
- private DeeplTranslationProviderConfiguration(Builder builder) {
- this.uri = builder.uri;
- this.proxy = builder.proxy;
- this.authKey = builder.authKey;
- }
-
- @Override
- public SupportedProvider getType() {
- return SupportedProvider.DEEPL;
- }
-
- public URI getUri() {
- return this.uri;
- }
-
- public String getAuthKey() {
- return this.authKey;
- }
-
- public Optional getProxy() {
- return Optional.ofNullable(this.proxy);
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- @SuppressWarnings("PMD.TooManyMethods")
- public final static class Builder {
-
- private URI uri;
-
- private ProxySelector proxy;
-
- private String authKey;
-
- private Builder() { }
-
- private Builder(DeeplTranslationProviderConfiguration translatorConfiguration) {
- this.uri = translatorConfiguration.uri;
- this.proxy = translatorConfiguration.proxy;
- this.authKey = translatorConfiguration.authKey;
- }
-
- public Builder url(String url) throws URISyntaxException {
- Objects.requireNonNull(url, "url is null");
- this.uri = new URI(url);
- return this;
- }
-
- public Builder authKey(String authKey) {
- Objects.requireNonNull(authKey, "authKey is null");
- this.authKey = authKey;
- return this;
- }
-
- public Builder proxy(ProxySelector proxy) {
- Objects.requireNonNull(proxy, "proxy is null");
- this.proxy = proxy;
- return this;
- }
-
- public Builder proxy(InetSocketAddress proxy) {
- Objects.requireNonNull(proxy, "proxy is null");
- this.proxy = ProxySelector.of(proxy);
- return this;
- }
-
- public Builder proxy(String host, int port) {
- Objects.requireNonNull(host, "host is null");
- if (port <= 0) {
- throw new IllegalArgumentException("port should be greater than 0");
- }
- this.proxy = ProxySelector.of(new InetSocketAddress(host, port));
- return this;
- }
-
- public DeeplTranslationProviderConfiguration build() {
- if (this.uri == null) {
- throw new IllegalStateException("uri not set");
- }
- if (this.authKey == null) {
- throw new IllegalStateException("authKey not set");
- }
- return new DeeplTranslationProviderConfiguration(this);
- }
- }
+public final class DeeplTranslationProviderConfiguration
+ implements TranslationProviderConfiguration {
+
+ private final URI uri;
+
+ private final ProxySelector proxy;
+
+ private final String authKey;
+
+ private DeeplTranslationProviderConfiguration(Builder builder) {
+ this.uri = builder.uri;
+ this.proxy = builder.proxy;
+ this.authKey = builder.authKey;
+ }
+
+ @Override
+ public SupportedProvider getType() {
+ return SupportedProvider.DEEPL;
+ }
+
+ public URI getUri() {
+ return this.uri;
+ }
+
+ public String getAuthKey() {
+ return this.authKey;
+ }
+
+ public Optional getProxy() {
+ return Optional.ofNullable(this.proxy);
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ @SuppressWarnings("PMD.TooManyMethods")
+ public static final class Builder {
+
+ private URI uri;
+
+ private ProxySelector proxy;
+
+ private String authKey;
+
+ private Builder() {}
+
+ private Builder(DeeplTranslationProviderConfiguration translatorConfiguration) {
+ this.uri = translatorConfiguration.uri;
+ this.proxy = translatorConfiguration.proxy;
+ this.authKey = translatorConfiguration.authKey;
+ }
+
+ public Builder url(String url) throws URISyntaxException {
+ Objects.requireNonNull(url, "url is null");
+ this.uri = new URI(url);
+ return this;
+ }
+
+ public Builder authKey(String authKey) {
+ Objects.requireNonNull(authKey, "authKey is null");
+ this.authKey = authKey;
+ return this;
+ }
+
+ public Builder proxy(ProxySelector proxy) {
+ Objects.requireNonNull(proxy, "proxy is null");
+ this.proxy = proxy;
+ return this;
+ }
+
+ public Builder proxy(InetSocketAddress proxy) {
+ Objects.requireNonNull(proxy, "proxy is null");
+ this.proxy = ProxySelector.of(proxy);
+ return this;
+ }
+
+ public Builder proxy(String host, int port) {
+ Objects.requireNonNull(host, "host is null");
+ if (port <= 0) {
+ throw new IllegalArgumentException("port should be greater than 0");
+ }
+ this.proxy = ProxySelector.of(new InetSocketAddress(host, port));
+ return this;
+ }
+
+ public DeeplTranslationProviderConfiguration build() {
+ if (this.uri == null) {
+ throw new IllegalStateException("uri not set");
+ }
+ if (this.authKey == null) {
+ throw new IllegalStateException("authKey not set");
+ }
+ return new DeeplTranslationProviderConfiguration(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/ErrorResponse.java b/src/main/java/com/sitepark/translate/provider/deepl/ErrorResponse.java
index 2469ead..decd462 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/ErrorResponse.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/ErrorResponse.java
@@ -5,14 +5,10 @@
public class ErrorResponse {
- @JsonProperty
- public String message;
- @JsonProperty
- public String detail;
+ @JsonProperty public String message;
+ @JsonProperty public String detail;
- public TranslationProviderException toException() {
- return new TranslationProviderException(
- this.message + "\n" +
- this.detail);
- }
+ public TranslationProviderException toException() {
+ return new TranslationProviderException(this.message + "\n" + this.detail);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/GlossaryListResponse.java b/src/main/java/com/sitepark/translate/provider/deepl/GlossaryListResponse.java
index ece584b..3b3b64e 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/GlossaryListResponse.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/GlossaryListResponse.java
@@ -1,10 +1,8 @@
package com.sitepark.translate.provider.deepl;
-import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
public class GlossaryListResponse {
- @JsonProperty
- public List glossaries;
+ @JsonProperty public List glossaries;
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/GlossaryResponse.java b/src/main/java/com/sitepark/translate/provider/deepl/GlossaryResponse.java
index 663829d..4ee9402 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/GlossaryResponse.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/GlossaryResponse.java
@@ -1,25 +1,29 @@
package com.sitepark.translate.provider.deepl;
-import java.time.OffsetDateTime;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+import java.time.OffsetDateTime;
public class GlossaryResponse {
- @JsonProperty("glossary_id")
- public String glossaryId;
- @JsonProperty("name")
- public String name;
- @JsonProperty("ready")
- public boolean ready;
- @JsonProperty("source_lang")
- public String sourceLang;
- @JsonProperty("target_lang")
- public String targetLang;
- @JsonProperty("creation_time")
- public OffsetDateTime creationTime;
- @JsonProperty("entry_count")
- public int entryCount;
-
- public GlossaryResponse() {
- }
-}
\ No newline at end of file
+ @JsonProperty("glossary_id")
+ public String glossaryId;
+
+ @JsonProperty("name")
+ public String name;
+
+ @JsonProperty("ready")
+ public boolean ready;
+
+ @JsonProperty("source_lang")
+ public String sourceLang;
+
+ @JsonProperty("target_lang")
+ public String targetLang;
+
+ @JsonProperty("creation_time")
+ public OffsetDateTime creationTime;
+
+ @JsonProperty("entry_count")
+ public int entryCount;
+
+ public GlossaryResponse() {}
+}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyHandler.java b/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyHandler.java
index 3331de7..8b0193c 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyHandler.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyHandler.java
@@ -1,5 +1,8 @@
package com.sitepark.translate.provider.deepl;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import com.sitepark.translate.TranslationProviderException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
@@ -12,82 +15,78 @@
import java.util.function.Function;
import java.util.function.Supplier;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
-import com.sitepark.translate.TranslationProviderException;
-
public class JsonBodyHandler implements BodyHandler>> {
- private final Class successType;
+ private final Class successType;
- private final Class errorType;
+ private final Class errorType;
- public JsonBodyHandler(Class successType, Class errorType) {
- this.successType = successType;
- this.errorType = errorType;
- }
+ public JsonBodyHandler(Class successType, Class errorType) {
+ this.successType = successType;
+ this.errorType = errorType;
+ }
- @Override
- public BodySubscriber>> apply(ResponseInfo responseInfo) {
+ @Override
+ public BodySubscriber>> apply(ResponseInfo responseInfo) {
- Function>> mapper;
+ Function>> mapper;
- if (responseInfo.statusCode() == HttpURLConnection.HTTP_OK ||
- responseInfo.statusCode() == HttpURLConnection.HTTP_CREATED) {
- mapper = this.parseSuccessResult(responseInfo.statusCode());
- } else if (responseInfo.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
- mapper = this.successNoContent(responseInfo.statusCode());
- } else {
- mapper = this.parseErrorResult(responseInfo.statusCode());
- }
- return BodySubscribers.mapping(BodySubscribers.ofInputStream(), mapper);
- }
+ if (responseInfo.statusCode() == HttpURLConnection.HTTP_OK
+ || responseInfo.statusCode() == HttpURLConnection.HTTP_CREATED) {
+ mapper = this.parseSuccessResult(responseInfo.statusCode());
+ } else if (responseInfo.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
+ mapper = this.successNoContent(responseInfo.statusCode());
+ } else {
+ mapper = this.parseErrorResult(responseInfo.statusCode());
+ }
+ return BodySubscribers.mapping(BodySubscribers.ofInputStream(), mapper);
+ }
- private Function>> parseSuccessResult(int statusCode) {
- return (input) -> {
- return () -> {
- return JsonResult.success(statusCode, parseResult(input, successType));
- };
- };
- }
+ private Function>> parseSuccessResult(int statusCode) {
+ return (input) -> {
+ return () -> {
+ return JsonResult.success(statusCode, parseResult(input, successType));
+ };
+ };
+ }
- private Function>> parseErrorResult(int statusCode) {
- return (input) -> {
- return () -> {
- return JsonResult.error(statusCode, parseResult(input, errorType));
- };
- };
- }
+ private Function>> parseErrorResult(int statusCode) {
+ return (input) -> {
+ return () -> {
+ return JsonResult.error(statusCode, parseResult(input, errorType));
+ };
+ };
+ }
- private Function>> successNoContent(int statusCode) {
- return (input) -> {
- return () -> {
- try {
- return JsonResult.success(statusCode, this.successType.getConstructor().newInstance());
- } catch (Exception e) {
- throw new TranslationProviderException(e.getMessage(), e);
- }
- };
- };
- }
+ private Function>> successNoContent(int statusCode) {
+ return (input) -> {
+ return () -> {
+ try {
+ return JsonResult.success(statusCode, this.successType.getConstructor().newInstance());
+ } catch (Exception e) {
+ throw new TranslationProviderException(e.getMessage(), e);
+ }
+ };
+ };
+ }
- private R parseResult(InputStream input, Class type) {
- ObjectMapper mapper = new ObjectMapper();
- mapper.registerModule(new JavaTimeModule());
+ private R parseResult(InputStream input, Class type) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(new JavaTimeModule());
- if (type == String.class) {
- try {
- String text = new String(input.readAllBytes(), StandardCharsets.UTF_8);
- return type.cast(text);
- } catch (IOException e) {
- throw new UncheckedIOException(e.getMessage(), e);
- }
- }
+ if (type == String.class) {
+ try {
+ String text = new String(input.readAllBytes(), StandardCharsets.UTF_8);
+ return type.cast(text);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e.getMessage(), e);
+ }
+ }
- try {
- return mapper.readValue(input, type);
- } catch (IOException ex) {
- throw new UncheckedIOException(ex);
- }
- }
+ try {
+ return mapper.readValue(input, type);
+ } catch (IOException ex) {
+ throw new UncheckedIOException(ex);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandler.java b/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandler.java
index c192815..cf19dac 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandler.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandler.java
@@ -1,5 +1,8 @@
package com.sitepark.translate.provider.deepl;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sitepark.translate.TranslationProviderException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
@@ -8,39 +11,35 @@
import java.util.List;
import java.util.function.Supplier;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.sitepark.translate.TranslationProviderException;
-
-public class JsonBodyLanguagesHandler implements HttpResponse.BodyHandler>> {
-
- @Override
- public HttpResponse.BodySubscriber>> apply(
- HttpResponse.ResponseInfo responseInfo) {
- if (responseInfo.statusCode() != HttpURLConnection.HTTP_OK) {
- throw new TranslationProviderException("HTTP-Status: " + responseInfo.statusCode());
- }
- return asJSON();
- }
-
- public static HttpResponse.BodySubscriber>> asJSON() {
-
-
- HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofInputStream();
-
- return HttpResponse.BodySubscribers.mapping(upstream, inputStream -> toSupplierOfType(inputStream));
- }
-
- public static Supplier> toSupplierOfType(InputStream inputStream) {
- return () -> {
- try (InputStream stream = inputStream) {
- ObjectMapper objectMapper = new ObjectMapper();
- return objectMapper.readValue(
- stream,
- new TypeReference>() { });
- } catch (IOException e) {
- throw new UncheckedIOException(e);
- }
- };
- }
+public class JsonBodyLanguagesHandler
+ implements HttpResponse.BodyHandler>> {
+
+ @Override
+ public HttpResponse.BodySubscriber>> apply(
+ HttpResponse.ResponseInfo responseInfo) {
+ if (responseInfo.statusCode() != HttpURLConnection.HTTP_OK) {
+ throw new TranslationProviderException("HTTP-Status: " + responseInfo.statusCode());
+ }
+ return asJSON();
+ }
+
+ public static HttpResponse.BodySubscriber>> asJSON() {
+
+ HttpResponse.BodySubscriber upstream =
+ HttpResponse.BodySubscribers.ofInputStream();
+
+ return HttpResponse.BodySubscribers.mapping(
+ upstream, inputStream -> toSupplierOfType(inputStream));
+ }
+
+ public static Supplier> toSupplierOfType(InputStream inputStream) {
+ return () -> {
+ try (InputStream stream = inputStream) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ return objectMapper.readValue(stream, new TypeReference>() {});
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ };
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/JsonResult.java b/src/main/java/com/sitepark/translate/provider/deepl/JsonResult.java
index c3344db..632cec2 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/JsonResult.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/JsonResult.java
@@ -4,45 +4,46 @@
public final class JsonResult {
- public static JsonResult success(int statusCode, T successValue) {
- Objects.requireNonNull(successValue, "successValue is null");
- return new JsonResult<>(statusCode, successValue, null);
- }
-
- public static JsonResult error(int statusCode, U errorValue) {
- Objects.requireNonNull(errorValue, "errorValue is null");
- return new JsonResult<>(statusCode, null, errorValue);
- }
-
- private final int statusCode;
- private final T successValue;
- private final U errorValue;
-
- private JsonResult(int statusCode, T successValue, U errorValue) {
- this.statusCode = statusCode;
- this.successValue = successValue;
- this.errorValue = errorValue;
- }
-
- public boolean isSuccess() {
- return errorValue == null;
- }
-
- public int getStatusCode() {
- return this.statusCode;
- }
-
- public T getSuccessValue() {
- if (!isSuccess()) {
- throw new IllegalStateException("No success value: JsonResult represents a non-successful result");
- }
- return successValue;
- }
-
- public U getErrorValue() {
- if (isSuccess()) {
- throw new IllegalStateException("No error value: JsonResult represents a successful result");
- }
- return errorValue;
- }
+ public static JsonResult success(int statusCode, T successValue) {
+ Objects.requireNonNull(successValue, "successValue is null");
+ return new JsonResult<>(statusCode, successValue, null);
+ }
+
+ public static JsonResult error(int statusCode, U errorValue) {
+ Objects.requireNonNull(errorValue, "errorValue is null");
+ return new JsonResult<>(statusCode, null, errorValue);
+ }
+
+ private final int statusCode;
+ private final T successValue;
+ private final U errorValue;
+
+ private JsonResult(int statusCode, T successValue, U errorValue) {
+ this.statusCode = statusCode;
+ this.successValue = successValue;
+ this.errorValue = errorValue;
+ }
+
+ public boolean isSuccess() {
+ return errorValue == null;
+ }
+
+ public int getStatusCode() {
+ return this.statusCode;
+ }
+
+ public T getSuccessValue() {
+ if (!isSuccess()) {
+ throw new IllegalStateException(
+ "No success value: JsonResult represents a non-successful result");
+ }
+ return successValue;
+ }
+
+ public U getErrorValue() {
+ if (isSuccess()) {
+ throw new IllegalStateException("No error value: JsonResult represents a successful result");
+ }
+ return errorValue;
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/LanguageType.java b/src/main/java/com/sitepark/translate/provider/deepl/LanguageType.java
index e2257ad..eccb576 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/LanguageType.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/LanguageType.java
@@ -1,16 +1,15 @@
package com.sitepark.translate.provider.deepl;
-import java.util.Locale;
-
import com.fasterxml.jackson.annotation.JsonValue;
+import java.util.Locale;
public enum LanguageType {
- SOURCE,
- TARGET;
-
- @Override
- @JsonValue
- public String toString() {
- return name().toLowerCase(Locale.ENGLISH);
- }
+ SOURCE,
+ TARGET;
+
+ @Override
+ @JsonValue
+ public String toString() {
+ return name().toLowerCase(Locale.ENGLISH);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/TransportLanguage.java b/src/main/java/com/sitepark/translate/provider/deepl/TransportLanguage.java
index 605d789..a285412 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/TransportLanguage.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/TransportLanguage.java
@@ -1,28 +1,27 @@
package com.sitepark.translate.provider.deepl;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UWF_UNWRITTEN_FIELD")
public class TransportLanguage {
- private String language;
+ private String language;
- private String name;
+ private String name;
- private boolean supportsFormality;
+ private boolean supportsFormality;
- public String getLanguage() {
- return this.language;
- }
+ public String getLanguage() {
+ return this.language;
+ }
- public String getName() {
- return this.name;
- }
+ public String getName() {
+ return this.name;
+ }
- @JsonProperty("supports_formality")
- public boolean isSupportsFormality() {
- return this.supportsFormality;
- }
+ @JsonProperty("supports_formality")
+ public boolean isSupportsFormality() {
+ return this.supportsFormality;
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/TransportResponse.java b/src/main/java/com/sitepark/translate/provider/deepl/TransportResponse.java
index 90b2120..0be24a4 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/TransportResponse.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/TransportResponse.java
@@ -1,17 +1,15 @@
package com.sitepark.translate.provider.deepl;
-import java.util.Arrays;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.Arrays;
public class TransportResponse {
- @JsonProperty
- private TransportTranslation[] translations;
+ @JsonProperty private TransportTranslation[] translations;
- public String[] getTranslations() {
- return Arrays.stream(this.translations)
- .map(translation -> translation.getText())
- .toArray(String[]::new);
- }
+ public String[] getTranslations() {
+ return Arrays.stream(this.translations)
+ .map(translation -> translation.getText())
+ .toArray(String[]::new);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/deepl/TransportTranslation.java b/src/main/java/com/sitepark/translate/provider/deepl/TransportTranslation.java
index d0a6a03..ac27d42 100644
--- a/src/main/java/com/sitepark/translate/provider/deepl/TransportTranslation.java
+++ b/src/main/java/com/sitepark/translate/provider/deepl/TransportTranslation.java
@@ -1,22 +1,21 @@
package com.sitepark.translate.provider.deepl;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UWF_UNWRITTEN_FIELD")
public class TransportTranslation {
- private String detectedSourceLanguage;
+ private String detectedSourceLanguage;
- private String text;
+ private String text;
- @JsonProperty("detected_source_language")
- public String getDetectedSourceLanguage() {
- return this.detectedSourceLanguage;
- }
+ @JsonProperty("detected_source_language")
+ public String getDetectedSourceLanguage() {
+ return this.detectedSourceLanguage;
+ }
- public String getText() {
- return this.text;
- }
+ public String getText() {
+ return this.text;
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandler.java b/src/main/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandler.java
index 646a13b..569aaff 100644
--- a/src/main/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandler.java
+++ b/src/main/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandler.java
@@ -1,5 +1,7 @@
package com.sitepark.translate.provider.libretranslate;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sitepark.translate.TranslationProviderException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
@@ -8,41 +10,40 @@
import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.sitepark.translate.TranslationProviderException;
-
public class JsonBodyHandler implements HttpResponse.BodyHandler> {
- private final Class wClass;
-
- public JsonBodyHandler(Class wClass) {
- this.wClass = wClass;
- }
-
- @Override
- public HttpResponse.BodySubscriber> apply(HttpResponse.ResponseInfo responseInfo) {
- if (responseInfo.statusCode() != HttpURLConnection.HTTP_OK) {
- throw new TranslationProviderException("HTTP-Status: " + responseInfo.statusCode());
- }
- return asJSON(this.wClass);
- }
-
- public static HttpResponse.BodySubscriber> asJSON(Class targetType) {
- HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofInputStream();
-
- return HttpResponse.BodySubscribers.mapping(upstream, inputStream -> toSupplierOfType(inputStream, targetType));
- }
-
- public static Supplier toSupplierOfType(InputStream inputStream, Class targetType) {
- return () -> {
- String text = null;
- try (InputStream stream = inputStream) {
- text = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
- ObjectMapper objectMapper = new ObjectMapper();
- return objectMapper.readValue(text, targetType);
- } catch (IOException e) {
- throw new UncheckedIOException(text, e);
- }
- };
- }
+ private final Class wClass;
+
+ public JsonBodyHandler(Class wClass) {
+ this.wClass = wClass;
+ }
+
+ @Override
+ public HttpResponse.BodySubscriber> apply(HttpResponse.ResponseInfo responseInfo) {
+ if (responseInfo.statusCode() != HttpURLConnection.HTTP_OK) {
+ throw new TranslationProviderException("HTTP-Status: " + responseInfo.statusCode());
+ }
+ return asJSON(this.wClass);
+ }
+
+ public static HttpResponse.BodySubscriber> asJSON(Class targetType) {
+ HttpResponse.BodySubscriber upstream =
+ HttpResponse.BodySubscribers.ofInputStream();
+
+ return HttpResponse.BodySubscribers.mapping(
+ upstream, inputStream -> toSupplierOfType(inputStream, targetType));
+ }
+
+ public static Supplier toSupplierOfType(InputStream inputStream, Class targetType) {
+ return () -> {
+ String text = null;
+ try (InputStream stream = inputStream) {
+ text = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
+ ObjectMapper objectMapper = new ObjectMapper();
+ return objectMapper.readValue(text, targetType);
+ } catch (IOException e) {
+ throw new UncheckedIOException(text, e);
+ }
+ };
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProvider.java b/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProvider.java
index 7f752e0..80b9484 100644
--- a/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProvider.java
+++ b/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProvider.java
@@ -1,15 +1,5 @@
package com.sitepark.translate.provider.libretranslate;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpRequest.BodyPublisher;
-import java.nio.charset.StandardCharsets;
-import java.security.ProviderException;
-import java.util.Optional;
-
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sitepark.translate.Glossary;
import com.sitepark.translate.SupportedLanguages;
@@ -23,171 +13,174 @@
import com.sitepark.translate.translator.UnifiedSourceText;
import com.sitepark.translate.translator.entity.Decoder;
import com.sitepark.translate.translator.entity.Encoder;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpRequest.BodyPublisher;
+import java.nio.charset.StandardCharsets;
+import java.security.ProviderException;
+import java.util.Optional;
@SuppressFBWarnings
@SuppressWarnings("PMD")
public class LibreTranslateTranslationProvider implements TranslationProvider {
- private final TranslationConfiguration translatorConfiguration;
+ private final TranslationConfiguration translatorConfiguration;
+
+ public LibreTranslateTranslationProvider(TranslationConfiguration translatorConfiguration) {
+ this.translatorConfiguration = translatorConfiguration;
+ }
- public LibreTranslateTranslationProvider(TranslationConfiguration translatorConfiguration) {
- this.translatorConfiguration = translatorConfiguration;
- }
+ public TranslationResult translate(TranslationRequest req) {
- public TranslationResult translate(TranslationRequest req) {
+ String[] encodedSourceText = this.encodePlacerholder(req.getSourceText());
- String[] encodedSourceText = this.encodePlacerholder(req.getSourceText());
+ UnifiedSourceText unifiedSourceText = new UnifiedSourceText(encodedSourceText);
- UnifiedSourceText unifiedSourceText = new UnifiedSourceText(encodedSourceText);
+ try {
- try {
+ long start = System.currentTimeMillis();
- long start = System.currentTimeMillis();
+ String[] translated =
+ this.translationRequest(req.getParameter(), unifiedSourceText.getSourceText());
- String[] translated = this.translationRequest(
- req.getParameter(),
- unifiedSourceText.getSourceText());
+ String[] decodedTranslation = this.decodePlacerholder(translated);
- String[] decodedTranslation = this.decodePlacerholder(translated);
+ return TranslationResult.builder()
+ .request(req)
+ .text(unifiedSourceText.expandTranslation(decodedTranslation))
+ .statistic(
+ TranslationResultStatistic.builder()
+ .chunks(req.getSourceText().length)
+ .translationTime(System.currentTimeMillis() - start)
+ .sourceBytes(this.byteCount(unifiedSourceText.getSourceText()))
+ .targetBytes(this.byteCount(translated))
+ .build())
+ .build();
- return TranslationResult.builder()
- .request(req)
- .text(unifiedSourceText.expandTranslation(decodedTranslation))
- .statistic(TranslationResultStatistic.builder()
- .chunks(req.getSourceText().length)
- .translationTime(System.currentTimeMillis() - start)
- .sourceBytes(this.byteCount(unifiedSourceText.getSourceText()))
- .targetBytes(this.byteCount(translated))
- .build()
- )
- .build();
+ } catch (InterruptedException | IOException e) {
+ throw new ProviderException(e.getMessage(), e);
+ }
+ }
- } catch (InterruptedException | IOException e) {
- throw new ProviderException(e.getMessage(), e);
- }
- }
-
- protected String[] translationRequest(
- TranslationParameter parameter,
- String... source)
- throws IOException, InterruptedException {
-
- URI uri = this.buildUri("/translate");
-
- TransportRequest req = TransportRequest.builder()
- .source(parameter.getLanguage().getSource())
- .target(parameter.getLanguage().getTarget())
- .format(parameter.getFormat().get())
- .q(source)
- .build();
-
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Content-Type", "application/json")
- .header("Accept", "application/json")
- .header("Origin", this.getProviderConfiguration().getUri().toString())
- .POST(this.toPostBody(req))
- .build();
-
- HttpClient client = this.createHttpClient();
-
- TransportResponse response = client
- .send(request, new JsonBodyHandler<>(TransportResponse.class))
- .body()
- .get();
-
- return response.getTranslations();
- }
-
- private String[] encodePlacerholder(String... q) {
- if (!this.translatorConfiguration.isEncodePlaceholder()) {
- return q;
- }
-
- return Encoder.encode(q);
- }
-
- private String[] decodePlacerholder(String... q) {
-
- if (!this.translatorConfiguration.isEncodePlaceholder()) {
- return q;
- }
-
- return Decoder.decode(q);
- }
-
- private int byteCount(String... array) {
- int count = 0;
- for (String s : array) {
- count += s.getBytes(StandardCharsets.UTF_8).length;
- }
- return count;
- }
-
- private BodyPublisher toPostBody(TransportRequest req) {
- try {
- ObjectMapper mapper = new ObjectMapper();
- String reqJson = mapper.writeValueAsString(req);
- return HttpRequest.BodyPublishers.ofString(reqJson);
- } catch (Exception e) {
- throw new ProviderException(e.getMessage(), e);
- }
- }
-
- public SupportedLanguages getSupportedLanguages() {
-
- URI uri = this.buildUri("/languages");
-
- HttpRequest request = HttpRequest.newBuilder(uri)
- .header("Accept", "application/json").build();
-
- HttpClient client = this.createHttpClient();
-
- try {
- return client.send(request, new JsonBodyHandler<>(SupportedLanguages.class)).body().get();
- } catch (InterruptedException | IOException e) {
- throw new ProviderException(e.getMessage(), e);
- }
- }
-
- private LibreTranslateTranslationProviderConfiguration getProviderConfiguration() {
- return this.translatorConfiguration.getTranslationProviderConfiguration(
- LibreTranslateTranslationProviderConfiguration.class);
- }
-
- private URI buildUri(String path) {
- try {
- return new URI(this.getProviderConfiguration().getUri() + path);
- } catch (URISyntaxException e) {
- throw new ProviderException(e.getMessage(), e);
- }
- }
-
- private HttpClient createHttpClient() {
- HttpClient.Builder builder = HttpClient.newBuilder();
- if (this.getProviderConfiguration().getProxy().isPresent()) {
- builder.proxy(this.getProviderConfiguration().getProxy().get());
- }
- return builder.build();
- }
-
- @Override
- public Optional getGlossary(String id) {
- return Optional.empty();
- }
-
- @Override
- public Optional getGlossaryId(String name) {
- return Optional.empty();
- }
-
- @Override
- public String recreate(Glossary glossar) {
- throw new UnsupportedOperationException("LibreTranslate not yet support a glossary.");
- }
-
- @Override
- public void removeGlossary(String id) {
- }
+ protected String[] translationRequest(TranslationParameter parameter, String... source)
+ throws IOException, InterruptedException {
+
+ URI uri = this.buildUri("/translate");
+
+ TransportRequest req =
+ TransportRequest.builder()
+ .source(parameter.getLanguage().getSource())
+ .target(parameter.getLanguage().getTarget())
+ .format(parameter.getFormat().get())
+ .q(source)
+ .build();
+
+ HttpRequest request =
+ HttpRequest.newBuilder(uri)
+ .header("Content-Type", "application/json")
+ .header("Accept", "application/json")
+ .header("Origin", this.getProviderConfiguration().getUri().toString())
+ .POST(this.toPostBody(req))
+ .build();
+
+ HttpClient client = this.createHttpClient();
+
+ TransportResponse response =
+ client.send(request, new JsonBodyHandler<>(TransportResponse.class)).body().get();
+
+ return response.getTranslations();
+ }
+
+ private String[] encodePlacerholder(String... q) {
+ if (!this.translatorConfiguration.isEncodePlaceholder()) {
+ return q;
+ }
+
+ return Encoder.encode(q);
+ }
+
+ private String[] decodePlacerholder(String... q) {
+
+ if (!this.translatorConfiguration.isEncodePlaceholder()) {
+ return q;
+ }
+
+ return Decoder.decode(q);
+ }
+
+ private int byteCount(String... array) {
+ int count = 0;
+ for (String s : array) {
+ count += s.getBytes(StandardCharsets.UTF_8).length;
+ }
+ return count;
+ }
+
+ private BodyPublisher toPostBody(TransportRequest req) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ String reqJson = mapper.writeValueAsString(req);
+ return HttpRequest.BodyPublishers.ofString(reqJson);
+ } catch (Exception e) {
+ throw new ProviderException(e.getMessage(), e);
+ }
+ }
+
+ public SupportedLanguages getSupportedLanguages() {
+
+ URI uri = this.buildUri("/languages");
+
+ HttpRequest request = HttpRequest.newBuilder(uri).header("Accept", "application/json").build();
+
+ HttpClient client = this.createHttpClient();
+
+ try {
+ return client.send(request, new JsonBodyHandler<>(SupportedLanguages.class)).body().get();
+ } catch (InterruptedException | IOException e) {
+ throw new ProviderException(e.getMessage(), e);
+ }
+ }
+
+ private LibreTranslateTranslationProviderConfiguration getProviderConfiguration() {
+ return this.translatorConfiguration.getTranslationProviderConfiguration(
+ LibreTranslateTranslationProviderConfiguration.class);
+ }
+
+ private URI buildUri(String path) {
+ try {
+ return new URI(this.getProviderConfiguration().getUri() + path);
+ } catch (URISyntaxException e) {
+ throw new ProviderException(e.getMessage(), e);
+ }
+ }
+
+ private HttpClient createHttpClient() {
+ HttpClient.Builder builder = HttpClient.newBuilder();
+ if (this.getProviderConfiguration().getProxy().isPresent()) {
+ builder.proxy(this.getProviderConfiguration().getProxy().get());
+ }
+ return builder.build();
+ }
+
+ @Override
+ public Optional getGlossary(String id) {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional getGlossaryId(String name) {
+ return Optional.empty();
+ }
+
+ @Override
+ public String recreate(Glossary glossar) {
+ throw new UnsupportedOperationException("LibreTranslate not yet support a glossary.");
+ }
+
+ @Override
+ public void removeGlossary(String id) {}
}
diff --git a/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfiguration.java b/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfiguration.java
index 0d9bc3e..035f39d 100644
--- a/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfiguration.java
+++ b/src/main/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfiguration.java
@@ -1,5 +1,7 @@
package com.sitepark.translate.provider.libretranslate;
+import com.sitepark.translate.SupportedProvider;
+import com.sitepark.translate.TranslationProviderConfiguration;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
@@ -7,103 +9,101 @@
import java.util.Objects;
import java.util.Optional;
-import com.sitepark.translate.SupportedProvider;
-import com.sitepark.translate.TranslationProviderConfiguration;
-
-public final class LibreTranslateTranslationProviderConfiguration implements TranslationProviderConfiguration {
-
- private final URI uri;
-
- private final ProxySelector proxy;
-
- private final String apiKey;
-
- private LibreTranslateTranslationProviderConfiguration(Builder builder) {
- this.uri = builder.uri;
- this.proxy = builder.proxy;
- this.apiKey = builder.apiKey;
- }
-
- @Override
- public SupportedProvider getType() {
- return SupportedProvider.LIBRE_TRANSLATE;
- }
-
- public URI getUri() {
- return this.uri;
- }
-
- public Optional getApiKey() {
- return Optional.ofNullable(this.apiKey);
- }
-
- public Optional getProxy() {
- return Optional.ofNullable(this.proxy);
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- @SuppressWarnings("PMD.TooManyMethods")
- public final static class Builder {
-
- private URI uri;
-
- private ProxySelector proxy;
-
- private String apiKey;
-
- private Builder() { }
-
- private Builder(LibreTranslateTranslationProviderConfiguration translatorConfiguration) {
- this.uri = translatorConfiguration.uri;
- this.proxy = translatorConfiguration.proxy;
- this.apiKey = translatorConfiguration.apiKey;
- }
-
- public Builder url(String url) throws URISyntaxException {
- Objects.requireNonNull(url, "url is null");
- this.uri = new URI(url);
- return this;
- }
-
- public Builder apiKey(String apiKey) {
- Objects.requireNonNull(apiKey, "apiKey is null");
- this.apiKey = apiKey;
- return this;
- }
-
- public Builder proxy(ProxySelector proxy) {
- Objects.requireNonNull(proxy, "proxy is null");
- this.proxy = proxy;
- return this;
- }
-
- public Builder proxy(InetSocketAddress proxy) {
- Objects.requireNonNull(proxy, "proxy is null");
- this.proxy = ProxySelector.of(proxy);
- return this;
- }
-
- public Builder proxy(String host, int port) {
- Objects.requireNonNull(host, "host is null");
- if (port <= 0) {
- throw new IllegalArgumentException("port should be greater than 0");
- }
- this.proxy = ProxySelector.of(new InetSocketAddress(host, port));
- return this;
- }
-
- public LibreTranslateTranslationProviderConfiguration build() {
- if (this.uri == null) {
- throw new IllegalStateException("uri not set");
- }
- return new LibreTranslateTranslationProviderConfiguration(this);
- }
- }
+public final class LibreTranslateTranslationProviderConfiguration
+ implements TranslationProviderConfiguration {
+
+ private final URI uri;
+
+ private final ProxySelector proxy;
+
+ private final String apiKey;
+
+ private LibreTranslateTranslationProviderConfiguration(Builder builder) {
+ this.uri = builder.uri;
+ this.proxy = builder.proxy;
+ this.apiKey = builder.apiKey;
+ }
+
+ @Override
+ public SupportedProvider getType() {
+ return SupportedProvider.LIBRE_TRANSLATE;
+ }
+
+ public URI getUri() {
+ return this.uri;
+ }
+
+ public Optional getApiKey() {
+ return Optional.ofNullable(this.apiKey);
+ }
+
+ public Optional getProxy() {
+ return Optional.ofNullable(this.proxy);
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ @SuppressWarnings("PMD.TooManyMethods")
+ public static final class Builder {
+
+ private URI uri;
+
+ private ProxySelector proxy;
+
+ private String apiKey;
+
+ private Builder() {}
+
+ private Builder(LibreTranslateTranslationProviderConfiguration translatorConfiguration) {
+ this.uri = translatorConfiguration.uri;
+ this.proxy = translatorConfiguration.proxy;
+ this.apiKey = translatorConfiguration.apiKey;
+ }
+
+ public Builder url(String url) throws URISyntaxException {
+ Objects.requireNonNull(url, "url is null");
+ this.uri = new URI(url);
+ return this;
+ }
+
+ public Builder apiKey(String apiKey) {
+ Objects.requireNonNull(apiKey, "apiKey is null");
+ this.apiKey = apiKey;
+ return this;
+ }
+
+ public Builder proxy(ProxySelector proxy) {
+ Objects.requireNonNull(proxy, "proxy is null");
+ this.proxy = proxy;
+ return this;
+ }
+
+ public Builder proxy(InetSocketAddress proxy) {
+ Objects.requireNonNull(proxy, "proxy is null");
+ this.proxy = ProxySelector.of(proxy);
+ return this;
+ }
+
+ public Builder proxy(String host, int port) {
+ Objects.requireNonNull(host, "host is null");
+ if (port <= 0) {
+ throw new IllegalArgumentException("port should be greater than 0");
+ }
+ this.proxy = ProxySelector.of(new InetSocketAddress(host, port));
+ return this;
+ }
+
+ public LibreTranslateTranslationProviderConfiguration build() {
+ if (this.uri == null) {
+ throw new IllegalStateException("uri not set");
+ }
+ return new LibreTranslateTranslationProviderConfiguration(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/libretranslate/TransportRequest.java b/src/main/java/com/sitepark/translate/provider/libretranslate/TransportRequest.java
index ddb451a..ca98ba7 100644
--- a/src/main/java/com/sitepark/translate/provider/libretranslate/TransportRequest.java
+++ b/src/main/java/com/sitepark/translate/provider/libretranslate/TransportRequest.java
@@ -1,129 +1,128 @@
package com.sitepark.translate.provider.libretranslate;
-import java.util.Arrays;
-import java.util.Objects;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sitepark.translate.Format;
+import java.util.Arrays;
+import java.util.Objects;
public final class TransportRequest {
- private final String[] q;
+ private final String[] q;
- private final String source;
+ private final String source;
- private final String target;
+ private final String target;
- private final Format format;
+ private final Format format;
- private final String apiKey;
+ private final String apiKey;
- private TransportRequest(Builder builder) {
- this.q = builder.q;
- this.source = builder.source;
- this.target = builder.target;
- this.format = builder.format;
- this.apiKey = builder.apiKey;
- }
-
- public String[] getQ() {
- return Arrays.copyOf(this.q, this.q.length);
- }
-
- public String getSource() {
- return this.source;
- }
-
- public String getTarget() {
- return this.target;
- }
-
- public Format getFormat() {
- return this.format;
- }
-
- @JsonProperty("api_key")
- public String getApiKey() {
- return this.apiKey;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public Builder toBuilder() {
- return new Builder(this);
- }
-
- public final static class Builder {
-
- private String[] q;
-
- private String source;
-
- private String target;
-
- private Format format = Format.TEXT;
-
- private String apiKey = "";
-
- private Builder() { }
-
- private Builder(TransportRequest request) {
- this.q = request.q;
- this.source = request.source;
- this.target = request.target;
- this.format = request.format;
- this.apiKey = request.apiKey;
- }
-
- public Builder q(String... q) {
- Objects.requireNonNull(q, "q is null");
- if (q.length == 0) {
- throw new IllegalArgumentException("q is empty");
- }
- this.q = Arrays.copyOf(q, q.length);
- for (String item : q) {
- Objects.requireNonNull(item, "q item is null");
- }
- return this;
- }
-
- public Builder source(String source) {
- Objects.requireNonNull(source, "source is null");
- this.source = source;
- return this;
- }
-
- public Builder target(String target) {
- Objects.requireNonNull(target, "target is null");
- this.target = target;
- return this;
- }
-
- public Builder format(Format format) {
- Objects.requireNonNull(format, "format is null");
- this.format = format;
- return this;
- }
-
- public Builder apiKey(String apiKey) {
- Objects.requireNonNull(apiKey, "apiKey is null");
- this.apiKey = apiKey;
- return this;
- }
-
- public TransportRequest build() {
- if (this.q == null) {
- throw new IllegalStateException("q is not set");
- }
- if (this.source == null) {
- throw new IllegalStateException("source is not set");
- }
- if (this.target == null) {
- throw new IllegalStateException("target is not set");
- }
- return new TransportRequest(this);
- }
- }
+ private TransportRequest(Builder builder) {
+ this.q = builder.q;
+ this.source = builder.source;
+ this.target = builder.target;
+ this.format = builder.format;
+ this.apiKey = builder.apiKey;
+ }
+
+ public String[] getQ() {
+ return Arrays.copyOf(this.q, this.q.length);
+ }
+
+ public String getSource() {
+ return this.source;
+ }
+
+ public String getTarget() {
+ return this.target;
+ }
+
+ public Format getFormat() {
+ return this.format;
+ }
+
+ @JsonProperty("api_key")
+ public String getApiKey() {
+ return this.apiKey;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public Builder toBuilder() {
+ return new Builder(this);
+ }
+
+ public static final class Builder {
+
+ private String[] q;
+
+ private String source;
+
+ private String target;
+
+ private Format format = Format.TEXT;
+
+ private String apiKey = "";
+
+ private Builder() {}
+
+ private Builder(TransportRequest request) {
+ this.q = request.q;
+ this.source = request.source;
+ this.target = request.target;
+ this.format = request.format;
+ this.apiKey = request.apiKey;
+ }
+
+ public Builder q(String... q) {
+ Objects.requireNonNull(q, "q is null");
+ if (q.length == 0) {
+ throw new IllegalArgumentException("q is empty");
+ }
+ this.q = Arrays.copyOf(q, q.length);
+ for (String item : q) {
+ Objects.requireNonNull(item, "q item is null");
+ }
+ return this;
+ }
+
+ public Builder source(String source) {
+ Objects.requireNonNull(source, "source is null");
+ this.source = source;
+ return this;
+ }
+
+ public Builder target(String target) {
+ Objects.requireNonNull(target, "target is null");
+ this.target = target;
+ return this;
+ }
+
+ public Builder format(Format format) {
+ Objects.requireNonNull(format, "format is null");
+ this.format = format;
+ return this;
+ }
+
+ public Builder apiKey(String apiKey) {
+ Objects.requireNonNull(apiKey, "apiKey is null");
+ this.apiKey = apiKey;
+ return this;
+ }
+
+ public TransportRequest build() {
+ if (this.q == null) {
+ throw new IllegalStateException("q is not set");
+ }
+ if (this.source == null) {
+ throw new IllegalStateException("source is not set");
+ }
+ if (this.target == null) {
+ throw new IllegalStateException("target is not set");
+ }
+ return new TransportRequest(this);
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/provider/libretranslate/TransportResponse.java b/src/main/java/com/sitepark/translate/provider/libretranslate/TransportResponse.java
index 2061939..8333008 100644
--- a/src/main/java/com/sitepark/translate/provider/libretranslate/TransportResponse.java
+++ b/src/main/java/com/sitepark/translate/provider/libretranslate/TransportResponse.java
@@ -1,18 +1,14 @@
package com.sitepark.translate.provider.libretranslate;
-import java.util.Arrays;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.Arrays;
-@SuppressFBWarnings({
- "UWF_UNWRITTEN_FIELD",
- "NP_UNWRITTEN_FIELD"
-})
+@SuppressFBWarnings({"UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD"})
public class TransportResponse {
- private String[] translatedText;
+ private String[] translatedText;
- public String[] getTranslatedText() {
- return Arrays.copyOf(this.translatedText, this.translatedText.length);
- }
+ public String[] getTranslatedText() {
+ return Arrays.copyOf(this.translatedText, this.translatedText.length);
+ }
}
diff --git a/src/main/java/com/sitepark/translate/translator/FormatDetector.java b/src/main/java/com/sitepark/translate/translator/FormatDetector.java
index 9577003..37a1b0f 100644
--- a/src/main/java/com/sitepark/translate/translator/FormatDetector.java
+++ b/src/main/java/com/sitepark/translate/translator/FormatDetector.java
@@ -1,38 +1,35 @@
package com.sitepark.translate.translator;
+import com.sitepark.translate.Format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import com.sitepark.translate.Format;
-
public final class FormatDetector {
- private static final Pattern HTML_DETECTOR_PATTERN = Pattern.compile("<[^\\s>]*>|&[a-zA-Z]+;");
-
- private FormatDetector() {
- }
-
- public static boolean containsHtml(String text) {
- Matcher matcher = HTML_DETECTOR_PATTERN.matcher(text);
- return matcher.find();
- }
-
- public static boolean containsPlaceholder(String text) {
- return text.indexOf("${") != -1;
- }
-
- public static Format detect(String text) {
- if (FormatDetector.containsHtml(text)) {
- return Format.HTML;
- /*
- * HTML must also be used for placeholders since they
- * are masked with .
- */
- } else if (FormatDetector.containsPlaceholder(text)) {
- return Format.HTML;
- } else {
- return Format.TEXT;
- }
- }
-
+ private static final Pattern HTML_DETECTOR_PATTERN = Pattern.compile("<[^\\s>]*>|&[a-zA-Z]+;");
+
+ private FormatDetector() {}
+
+ public static boolean containsHtml(String text) {
+ Matcher matcher = HTML_DETECTOR_PATTERN.matcher(text);
+ return matcher.find();
+ }
+
+ public static boolean containsPlaceholder(String text) {
+ return text.indexOf("${") != -1;
+ }
+
+ public static Format detect(String text) {
+ if (FormatDetector.containsHtml(text)) {
+ return Format.HTML;
+ /*
+ * HTML must also be used for placeholders since they
+ * are masked with .
+ */
+ } else if (FormatDetector.containsPlaceholder(text)) {
+ return Format.HTML;
+ } else {
+ return Format.TEXT;
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/translator/JsonFileListTranslator.java b/src/main/java/com/sitepark/translate/translator/JsonFileListTranslator.java
index dd6c305..eed7f74 100644
--- a/src/main/java/com/sitepark/translate/translator/JsonFileListTranslator.java
+++ b/src/main/java/com/sitepark/translate/translator/JsonFileListTranslator.java
@@ -1,5 +1,14 @@
package com.sitepark.translate.translator; // NOPMD by veltrup on 24.05.23, 15:37
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sitepark.translate.Language;
+import com.sitepark.translate.SupportedLanguages;
+import com.sitepark.translate.SupportedProvider;
+import com.sitepark.translate.TranslationLanguage;
+import com.sitepark.translate.TranslationParameter;
+import com.sitepark.translate.TranslationProvider;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -12,303 +21,286 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.sitepark.translate.Language;
-import com.sitepark.translate.SupportedLanguages;
-import com.sitepark.translate.SupportedProvider;
-import com.sitepark.translate.TranslationLanguage;
-import com.sitepark.translate.TranslationParameter;
-import com.sitepark.translate.TranslationProvider;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
-@SuppressWarnings({
- "PMD.GuardLogStatement",
- "PMD.TooManyMethods"
-})
+@SuppressWarnings({"PMD.GuardLogStatement", "PMD.TooManyMethods"})
public final class JsonFileListTranslator extends Translator {
- private final Path dir;
-
- private final Path output;
-
- private final String sourceLang;
-
- private final Set targetLangList;
-
- private final Logger logger;
-
- private Path sourceDir;
-
- private List jsonFiles;
-
- private List jsonNodes;
-
- private List translatableTextNodeList;
-
- private JsonFileListTranslator(Builder builder) {
- super(builder);
- this.dir = builder.dir;
- this.output = builder.output;
- this.sourceLang = builder.sourceLang;
- this.targetLangList = builder.targetLangList;
- this.logger = builder.logger;
- }
-
- public static Builder builder() {
- return new Builder();
- }
-
- public void translate(SupportedProvider provider) throws IOException {
- this.translate(provider, (List)null);
- }
-
- public void translate(SupportedProvider provider, List targets) throws IOException {
-
- this.sourceDir = this.dir.resolve(this.sourceLang);
-
- Language sourceLanguage = this.getSourceLanguage(provider);
- this.loadJsonFiles();
- this.collectJsonNodes();
- this.collectTranslatableText();
-
- long tt = System.currentTimeMillis();
-
- List targetLanguageList;
- if (targets != null) {
- targetLanguageList = targets;
- } else {
- targetLanguageList = sourceLanguage.getTargets();
- }
-
- for (String targetLanguage : targetLanguageList) {
- if (this.sourceLang.equals(targetLanguage)) {
- continue;
- }
- if (!this.targetLangList.isEmpty() && !this.targetLangList.contains(targetLanguage)) {
- continue;
- }
- long t = System.currentTimeMillis();
-
- this.logger.info(
- "translate " + this.sourceLang + " -> " + targetLanguage);
- this.translate(provider, targetLanguage);
- long duration = (System.currentTimeMillis() - t) / 1000;
- this.logger.info(
- "translated " + this.sourceLang + " -> " + targetLanguage +
- " in " + duration + " seconds.");
- this.write(targetLanguage);
- }
- long totalDuration = (System.currentTimeMillis() - tt) / 1000;
- this.logger.info("translated in " + totalDuration + " seconds.");
- }
-
- private void write(String lang) throws IOException {
-
- ObjectMapper mapper = new ObjectMapper();
-
- for (JsonFile jsonFile : this.jsonFiles) {
- Path translatedFile = this.getOutputDir(lang).resolve(jsonFile.sourceFile);
- Path parent = translatedFile.getParent();
- if (parent != null && !Files.exists(parent)) {
- Files.createDirectories(parent);
- }
- mapper.writerWithDefaultPrettyPrinter()
- .writeValue(translatedFile.toFile(), jsonFile.node);
- }
- }
-
- private void collectJsonNodes() {
- this.jsonNodes = this.jsonFiles.stream()
- .map(json -> json.node)
- .collect(Collectors.toList());
- }
-
- private void collectTranslatableText() {
- TranslatableTextNodeCollector collector = new TranslatableTextNodeCollector();
- this.translatableTextNodeList = collector.collect(this.jsonNodes);
- }
-
- @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE")
- private void loadJsonFiles() throws IOException {
- try (Stream stream = Files.walk(this.sourceDir)) {
- this.jsonFiles = stream
- .filter(Files::isRegularFile)
- .filter(p -> p.toString().endsWith(".json"))
- .map(this::createJsonFile)
- .collect(Collectors.toList());
- }
- }
-
- private Language getSourceLanguage(SupportedProvider provider) {
- TranslationProvider translator = this.createTransporter(provider);
- SupportedLanguages supportedLanguages = translator.getSupportedLanguages();
- Optional sourceLanguage = supportedLanguages.getSourceLanguage(this.sourceLang);
- return sourceLanguage.orElseThrow(() -> new IllegalArgumentException(
- "Unsupported source language '" + this.sourceLang + "'"));
- }
-
- private void translate(SupportedProvider provider, String targetLang) {
-
- TranslationFileCache cache = this.createTranslationCache(targetLang);
-
- TranslatableTextListTranslator translator = TranslatableTextListTranslator.builder()
- .translatorConfiguration(this.getTranslatorConfiguration().toBuilder()
- .translationCache(cache)
- )
- .build();
-
- TranslationLanguage language = TranslationLanguage.builder()
- .source(this.sourceLang)
- .target(targetLang)
- .build();
-
- TranslationParameter parameter = TranslationParameter.builder()
- .providerType(provider)
- .language(language)
- .build();
-
- translator.translate(parameter, this.translatableTextNodeList);
-
- try {
- cache.store();
- } catch (Exception e) {
- this.logger.error(
- "Unable to store cache " + cache.getFile() + ": " + e.getMessage(),
- e);
- }
- }
-
- private JsonFile createJsonFile(Path file) {
-
- if (this.sourceDir == null) {
- throw new IllegalStateException("sourceDir is not set");
- }
-
- Path path = file.subpath(this.sourceDir.getNameCount(), file.getNameCount());
- JsonNode node = this.parseJson(file);
- return new JsonFile(path, node);
- }
-
- private JsonNode parseJson(Path file) {
- try {
- ObjectMapper mapper = new ObjectMapper();
- return mapper.readTree(file.toFile());
- } catch (Exception e) {
- throw new TranslatorException(e.getMessage(), e);
- }
- }
-
- private TranslationFileCache createTranslationCache(String targetLang) {
-
- Path cacheFile = this.getOutputDir(targetLang).resolve(".translation-cache-file");
-
- TranslationFileCache cache = new TranslationFileCache(cacheFile);
- try {
- cache.load();
- } catch (Exception e) {
- this.logger.error(
- "Unalbe to load cache " + cacheFile + ": " + e.getMessage(),
- e);
- }
- return cache;
- }
-
- private Path getOutputDir(String lang) {
- return this.output.resolve(lang);
- }
-
- public static interface Logger {
- void info(String msg);
- void error(String msg, Throwable t);
- }
-
- private final static class JsonFile {
- private final Path sourceFile;
- private final JsonNode node;
- private JsonFile(Path sourceFile, JsonNode node) {
- this.sourceFile = sourceFile;
- this.node = node;
- }
- }
-
- public final static class Builder extends Translator.Builder {
-
- private Path dir;
-
- private Path output;
-
- private String sourceLang;
-
- private final Set targetLangList = new HashSet<>();
-
- private Logger logger;
-
- private Builder() { }
-
- public Builder dir(Path dir) {
- Objects.requireNonNull(dir, "dir is null");
- this.dir = dir.toAbsolutePath();
- return this;
- }
-
- public Builder output(Path output) {
- Objects.requireNonNull(output, "output is null");
- this.output = output.toAbsolutePath();
- return this;
- }
-
- public Builder sourceLang(String sourceLang) {
- Objects.requireNonNull(sourceLang, "sourceLang is null");
- this.sourceLang = sourceLang;
- return this;
- }
-
- public Builder targetLangList(String... targetLangList) {
- Objects.requireNonNull(targetLangList, "targetLangList is null");
- this.targetLangList.addAll(Arrays.asList(targetLangList));
- return this;
- }
-
- public Builder targetLangList(Set targetLangList) {
- Objects.requireNonNull(targetLangList, "targetLangList is null");
- this.targetLangList.addAll(targetLangList);
- return this;
- }
-
- public Builder logger(Logger logger) {
- Objects.requireNonNull(logger, "logger is null");
- this.logger = logger;
- return this;
- }
-
- @Override
- protected Builder self() {
- return this;
- }
-
- @Override
- public JsonFileListTranslator build() {
- assert dir != null : "dir is null";
- assert output != null : "output is null";
- assert sourceLang != null : "sourceLang is null";
- if (this.logger == null) {
- this.logger = new NullLogger();
- }
- return new JsonFileListTranslator(this);
- }
- }
-
- private final static class NullLogger implements Logger {
- @Override
- public void info(String msg) {
- // null logger
- }
- @Override
- public void error(String msg, Throwable t) {
- // null logger
- }
- }
+ private final Path dir;
+ private final Path output;
+
+ private final String sourceLang;
+
+ private final Set targetLangList;
+
+ private final Logger logger;
+
+ private Path sourceDir;
+
+ private List jsonFiles;
+
+ private List jsonNodes;
+
+ private List translatableTextNodeList;
+
+ private JsonFileListTranslator(Builder builder) {
+ super(builder);
+ this.dir = builder.dir;
+ this.output = builder.output;
+ this.sourceLang = builder.sourceLang;
+ this.targetLangList = builder.targetLangList;
+ this.logger = builder.logger;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public void translate(SupportedProvider provider) throws IOException {
+ this.translate(provider, (List) null);
+ }
+
+ public void translate(SupportedProvider provider, List targets) throws IOException {
+
+ this.sourceDir = this.dir.resolve(this.sourceLang);
+
+ Language sourceLanguage = this.getSourceLanguage(provider);
+ this.loadJsonFiles();
+ this.collectJsonNodes();
+ this.collectTranslatableText();
+
+ long tt = System.currentTimeMillis();
+
+ List targetLanguageList;
+ if (targets != null) {
+ targetLanguageList = targets;
+ } else {
+ targetLanguageList = sourceLanguage.getTargets();
+ }
+
+ for (String targetLanguage : targetLanguageList) {
+ if (this.sourceLang.equals(targetLanguage)) {
+ continue;
+ }
+ if (!this.targetLangList.isEmpty() && !this.targetLangList.contains(targetLanguage)) {
+ continue;
+ }
+ long t = System.currentTimeMillis();
+
+ this.logger.info("translate " + this.sourceLang + " -> " + targetLanguage);
+ this.translate(provider, targetLanguage);
+ long duration = (System.currentTimeMillis() - t) / 1000;
+ this.logger.info(
+ "translated "
+ + this.sourceLang
+ + " -> "
+ + targetLanguage
+ + " in "
+ + duration
+ + " seconds.");
+ this.write(targetLanguage);
+ }
+ long totalDuration = (System.currentTimeMillis() - tt) / 1000;
+ this.logger.info("translated in " + totalDuration + " seconds.");
+ }
+
+ private void write(String lang) throws IOException {
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ for (JsonFile jsonFile : this.jsonFiles) {
+ Path translatedFile = this.getOutputDir(lang).resolve(jsonFile.sourceFile);
+ Path parent = translatedFile.getParent();
+ if (parent != null && !Files.exists(parent)) {
+ Files.createDirectories(parent);
+ }
+ mapper.writerWithDefaultPrettyPrinter().writeValue(translatedFile.toFile(), jsonFile.node);
+ }
+ }
+
+ private void collectJsonNodes() {
+ this.jsonNodes = this.jsonFiles.stream().map(json -> json.node).collect(Collectors.toList());
+ }
+
+ private void collectTranslatableText() {
+ TranslatableTextNodeCollector collector = new TranslatableTextNodeCollector();
+ this.translatableTextNodeList = collector.collect(this.jsonNodes);
+ }
+
+ @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE")
+ private void loadJsonFiles() throws IOException {
+ try (Stream stream = Files.walk(this.sourceDir)) {
+ this.jsonFiles =
+ stream
+ .filter(Files::isRegularFile)
+ .filter(p -> p.toString().endsWith(".json"))
+ .map(this::createJsonFile)
+ .collect(Collectors.toList());
+ }
+ }
+
+ private Language getSourceLanguage(SupportedProvider provider) {
+ TranslationProvider translator = this.createTransporter(provider);
+ SupportedLanguages supportedLanguages = translator.getSupportedLanguages();
+ Optional sourceLanguage = supportedLanguages.getSourceLanguage(this.sourceLang);
+ return sourceLanguage.orElseThrow(
+ () ->
+ new IllegalArgumentException("Unsupported source language '" + this.sourceLang + "'"));
+ }
+
+ private void translate(SupportedProvider provider, String targetLang) {
+
+ TranslationFileCache cache = this.createTranslationCache(targetLang);
+
+ TranslatableTextListTranslator translator =
+ TranslatableTextListTranslator.builder()
+ .translatorConfiguration(
+ this.getTranslatorConfiguration().toBuilder().translationCache(cache))
+ .build();
+
+ TranslationLanguage language =
+ TranslationLanguage.builder().source(this.sourceLang).target(targetLang).build();
+
+ TranslationParameter parameter =
+ TranslationParameter.builder().providerType(provider).language(language).build();
+
+ translator.translate(parameter, this.translatableTextNodeList);
+
+ try {
+ cache.store();
+ } catch (Exception e) {
+ this.logger.error("Unable to store cache " + cache.getFile() + ": " + e.getMessage(), e);
+ }
+ }
+
+ private JsonFile createJsonFile(Path file) {
+
+ if (this.sourceDir == null) {
+ throw new IllegalStateException("sourceDir is not set");
+ }
+
+ Path path = file.subpath(this.sourceDir.getNameCount(), file.getNameCount());
+ JsonNode node = this.parseJson(file);
+ return new JsonFile(path, node);
+ }
+
+ private JsonNode parseJson(Path file) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.readTree(file.toFile());
+ } catch (Exception e) {
+ throw new TranslatorException(e.getMessage(), e);
+ }
+ }
+
+ private TranslationFileCache createTranslationCache(String targetLang) {
+
+ Path cacheFile = this.getOutputDir(targetLang).resolve(".translation-cache-file");
+
+ TranslationFileCache cache = new TranslationFileCache(cacheFile);
+ try {
+ cache.load();
+ } catch (Exception e) {
+ this.logger.error("Unalbe to load cache " + cacheFile + ": " + e.getMessage(), e);
+ }
+ return cache;
+ }
+
+ private Path getOutputDir(String lang) {
+ return this.output.resolve(lang);
+ }
+
+ public static interface Logger {
+ void info(String msg);
+
+ void error(String msg, Throwable t);
+ }
+
+ private static final class JsonFile {
+ private final Path sourceFile;
+ private final JsonNode node;
+
+ private JsonFile(Path sourceFile, JsonNode node) {
+ this.sourceFile = sourceFile;
+ this.node = node;
+ }
+ }
+
+ public static final class Builder extends Translator.Builder {
+
+ private Path dir;
+
+ private Path output;
+
+ private String sourceLang;
+
+ private final Set targetLangList = new HashSet<>();
+
+ private Logger logger;
+
+ private Builder() {}
+
+ public Builder dir(Path dir) {
+ Objects.requireNonNull(dir, "dir is null");
+ this.dir = dir.toAbsolutePath();
+ return this;
+ }
+
+ public Builder output(Path output) {
+ Objects.requireNonNull(output, "output is null");
+ this.output = output.toAbsolutePath();
+ return this;
+ }
+
+ public Builder sourceLang(String sourceLang) {
+ Objects.requireNonNull(sourceLang, "sourceLang is null");
+ this.sourceLang = sourceLang;
+ return this;
+ }
+
+ public Builder targetLangList(String... targetLangList) {
+ Objects.requireNonNull(targetLangList, "targetLangList is null");
+ this.targetLangList.addAll(Arrays.asList(targetLangList));
+ return this;
+ }
+
+ public Builder targetLangList(Set targetLangList) {
+ Objects.requireNonNull(targetLangList, "targetLangList is null");
+ this.targetLangList.addAll(targetLangList);
+ return this;
+ }
+
+ public Builder logger(Logger logger) {
+ Objects.requireNonNull(logger, "logger is null");
+ this.logger = logger;
+ return this;
+ }
+
+ @Override
+ protected Builder self() {
+ return this;
+ }
+
+ @Override
+ public JsonFileListTranslator build() {
+ assert dir != null : "dir is null";
+ assert output != null : "output is null";
+ assert sourceLang != null : "sourceLang is null";
+ if (this.logger == null) {
+ this.logger = new NullLogger();
+ }
+ return new JsonFileListTranslator(this);
+ }
+ }
+
+ private static final class NullLogger implements Logger {
+ @Override
+ public void info(String msg) {
+ // null logger
+ }
+
+ @Override
+ public void error(String msg, Throwable t) {
+ // null logger
+ }
+ }
}
diff --git a/src/main/java/com/sitepark/translate/translator/JsonNodeTranslator.java b/src/main/java/com/sitepark/translate/translator/JsonNodeTranslator.java
index 11fc762..643b298 100644
--- a/src/main/java/com/sitepark/translate/translator/JsonNodeTranslator.java
+++ b/src/main/java/com/sitepark/translate/translator/JsonNodeTranslator.java
@@ -1,93 +1,91 @@
package com.sitepark.translate.translator;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.sitepark.translate.TranslationParameter;
-
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
public final class JsonNodeTranslator extends Translator {
- private final boolean copy;
+ private final boolean copy;
- private List jsonList;
+ private List jsonList;
- private List translatableTextNodeList;
+ private List translatableTextNodeList;
- private JsonNodeTranslator(Builder builder) {
- super(builder);
- this.copy = builder.copy;
- }
+ private JsonNodeTranslator(Builder builder) {
+ super(builder);
+ this.copy = builder.copy;
+ }
- public JsonNode translate(TranslationParameter parameter, JsonNode json) {
- List jsonList = this.translate(parameter, Arrays.asList(json));
- return jsonList.get(0);
- }
+ public JsonNode translate(TranslationParameter parameter, JsonNode json) {
+ List jsonList = this.translate(parameter, Arrays.asList(json));
+ return jsonList.get(0);
+ }
- @SuppressFBWarnings({"EI_EXPOSE_REP2", "EI_EXPOSE_REP"})
- public List translate(TranslationParameter parameter, List jsonList) {
+ @SuppressFBWarnings({"EI_EXPOSE_REP2", "EI_EXPOSE_REP"})
+ public List translate(TranslationParameter parameter, List jsonList) {
- if (this.copy) {
- this.jsonList = this.deepCopy(jsonList);
- } else {
- this.jsonList = jsonList;
- }
+ if (this.copy) {
+ this.jsonList = this.deepCopy(jsonList);
+ } else {
+ this.jsonList = jsonList;
+ }
- this.collectTranslatableText();
+ this.collectTranslatableText();
- TranslatableTextListTranslator translatableTextListTranslator = TranslatableTextListTranslator.builder()
- .translatorConfiguration(this.getTranslatorConfiguration())
- .build();
+ TranslatableTextListTranslator translatableTextListTranslator =
+ TranslatableTextListTranslator.builder()
+ .translatorConfiguration(this.getTranslatorConfiguration())
+ .build();
- translatableTextListTranslator.translate(parameter, this.translatableTextNodeList);
+ translatableTextListTranslator.translate(parameter, this.translatableTextNodeList);
- return this.jsonList;
- }
+ return this.jsonList;
+ }
- private List deepCopy(List jsonList) {
- List copy = new ArrayList<>();
- for (JsonNode json : jsonList) {
- copy.add(json.deepCopy());
- }
- return copy;
- }
+ private List