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 src/integration-test/java @@ -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 translated); + /** + * Passes all translated texts of a translation process. Also those that + * were determined via caching. + */ + public void update(List 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, 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, 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 deepCopy(List jsonList) { + List copy = new ArrayList<>(); + for (JsonNode json : jsonList) { + copy.add(json.deepCopy()); + } + return copy; + } - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - private void collectTranslatableText() { - TranslatableTextNodeCollector collector = new TranslatableTextNodeCollector(); - this.translatableTextNodeList = collector.collect(this.jsonList); - } + private void collectTranslatableText() { + TranslatableTextNodeCollector collector = new TranslatableTextNodeCollector(); + this.translatableTextNodeList = collector.collect(this.jsonList); + } - public static class Builder extends Translator.Builder { + public static class Builder extends Translator.Builder { - private boolean copy = true; + private boolean copy = true; - protected Builder() { - } + protected Builder() {} - protected Builder(JsonNodeTranslator jsonNodeTranslator) { - super(jsonNodeTranslator); - } + protected Builder(JsonNodeTranslator jsonNodeTranslator) { + super(jsonNodeTranslator); + } - public Builder copy(boolean copy) { - this.copy = copy; - return this; - } + public Builder copy(boolean copy) { + this.copy = copy; + return this; + } - @Override - protected Builder self() { - return this; - } + @Override + protected Builder self() { + return this; + } - @Override - public JsonNodeTranslator build() { - return new JsonNodeTranslator(this); - } - } + @Override + public JsonNodeTranslator build() { + return new JsonNodeTranslator(this); + } + } } diff --git a/src/main/java/com/sitepark/translate/translator/JsonStringTranslator.java b/src/main/java/com/sitepark/translate/translator/JsonStringTranslator.java index 9d17190..c8c6b0d 100644 --- a/src/main/java/com/sitepark/translate/translator/JsonStringTranslator.java +++ b/src/main/java/com/sitepark/translate/translator/JsonStringTranslator.java @@ -6,62 +6,62 @@ public final class JsonStringTranslator extends Translator { - private JsonStringTranslator(Builder builder) { - super(builder); - } + private JsonStringTranslator(Builder builder) { + super(builder); + } - public String translate(TranslationParameter parameter, String json) { + public String translate(TranslationParameter parameter, String json) { - JsonNode jsonNode = this.parseJson(json); + JsonNode jsonNode = this.parseJson(json); - JsonNodeTranslator jsonNodeTranslator = JsonNodeTranslator.builder() - .translatorConfiguration(this.getTranslatorConfiguration()) - .copy(false) - .build(); + JsonNodeTranslator jsonNodeTranslator = + JsonNodeTranslator.builder() + .translatorConfiguration(this.getTranslatorConfiguration()) + .copy(false) + .build(); - jsonNode = jsonNodeTranslator.translate(parameter, jsonNode); + jsonNode = jsonNodeTranslator.translate(parameter, jsonNode); - return this.jsonToString(jsonNode); - } + return this.jsonToString(jsonNode); + } - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - private String jsonToString(JsonNode jsonNode) { - try { - ObjectMapper mapper = new ObjectMapper(); - return mapper.writeValueAsString(jsonNode); - } catch (Exception e) { - throw new TranslatorException(e.getMessage(), e); - } - } + private String jsonToString(JsonNode jsonNode) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(jsonNode); + } catch (Exception e) { + throw new TranslatorException(e.getMessage(), e); + } + } - private JsonNode parseJson(String s) { - try { - ObjectMapper mapper = new ObjectMapper(); - return mapper.readTree(s); - } catch (Exception e) { - throw new TranslatorException(e.getMessage(), e); - } - } + private JsonNode parseJson(String s) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readTree(s); + } catch (Exception e) { + throw new TranslatorException(e.getMessage(), e); + } + } - public static class Builder extends Translator.Builder { - protected Builder() { - } + public static class Builder extends Translator.Builder { + protected Builder() {} - protected Builder(JsonStringTranslator stringTranslator) { - super(stringTranslator); - } + protected Builder(JsonStringTranslator stringTranslator) { + super(stringTranslator); + } - @Override - protected Builder self() { - return this; - } + @Override + protected Builder self() { + return this; + } - @Override - public JsonStringTranslator build() { - return new JsonStringTranslator(this); - } - } + @Override + public JsonStringTranslator build() { + return new JsonStringTranslator(this); + } + } } diff --git a/src/main/java/com/sitepark/translate/translator/StringArrayTranslator.java b/src/main/java/com/sitepark/translate/translator/StringArrayTranslator.java index 62756e1..8a63254 100644 --- a/src/main/java/com/sitepark/translate/translator/StringArrayTranslator.java +++ b/src/main/java/com/sitepark/translate/translator/StringArrayTranslator.java @@ -2,29 +2,29 @@ public final class StringArrayTranslator extends Translator { - private StringArrayTranslator(Builder builder) { - super(builder); - } + private StringArrayTranslator(Builder builder) { + super(builder); + } - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - public static class Builder extends Translator.Builder { - protected Builder() {} + public static class Builder extends Translator.Builder { + protected Builder() {} - protected Builder(StringArrayTranslator stringTranslator) { - super(stringTranslator); - } + protected Builder(StringArrayTranslator stringTranslator) { + super(stringTranslator); + } - @Override - protected Builder self() { - return this; - } + @Override + protected Builder self() { + return this; + } - @Override - public StringArrayTranslator build() { - return new StringArrayTranslator(this); - } - } + @Override + public StringArrayTranslator build() { + return new StringArrayTranslator(this); + } + } } diff --git a/src/main/java/com/sitepark/translate/translator/StringTranslator.java b/src/main/java/com/sitepark/translate/translator/StringTranslator.java index ad872d7..f807d5b 100644 --- a/src/main/java/com/sitepark/translate/translator/StringTranslator.java +++ b/src/main/java/com/sitepark/translate/translator/StringTranslator.java @@ -6,38 +6,36 @@ public final class StringTranslator extends Translator { - private StringTranslator(Builder builder) { - super(builder); - } - - public String translate(TranslationParameter parameter, String q) { - TranslationRequest req = TranslationRequest.builder() - .parameter(parameter) - .sourceText(q) - .build(); - TranslationResult result = super.translate(req); - return result.getText()[0]; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends Translator.Builder { - protected Builder() {} - - protected Builder(StringTranslator stringTranslator) { - super(stringTranslator); - } - - @Override - protected Builder self() { - return this; - } - - @Override - public StringTranslator build() { - return new StringTranslator(this); - } - } + private StringTranslator(Builder builder) { + super(builder); + } + + public String translate(TranslationParameter parameter, String q) { + TranslationRequest req = + TranslationRequest.builder().parameter(parameter).sourceText(q).build(); + TranslationResult result = super.translate(req); + return result.getText()[0]; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends Translator.Builder { + protected Builder() {} + + protected Builder(StringTranslator stringTranslator) { + super(stringTranslator); + } + + @Override + protected Builder self() { + return this; + } + + @Override + public StringTranslator build() { + return new StringTranslator(this); + } + } } diff --git a/src/main/java/com/sitepark/translate/translator/TranslatableText.java b/src/main/java/com/sitepark/translate/translator/TranslatableText.java index 4ab07ed..1829f27 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatableText.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatableText.java @@ -1,78 +1,76 @@ package com.sitepark.translate.translator; +import com.sitepark.translate.Format; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import com.sitepark.translate.Format; - public class TranslatableText { - private final String sourceText; - - private String sourceTextHash; - - private final Format format; - - private String targetText; - - public TranslatableText(String sourceText) { - this.sourceText = sourceText; - this.format = FormatDetector.detect(sourceText); - } - - public TranslatableText(String sourceText, Format format) { - this.sourceText = sourceText; - this.format = format; - } - - public void setTargetText(String targetText) { - this.targetText = targetText; - } - - public Format getFormat() { - return this.format; - } - - public String getSourceText() { - return this.sourceText; - } - - public String getTargetText() { - return this.targetText; - } - - public String toHash() { - - if (this.sourceTextHash != null) { - return this.sourceTextHash; - } - if (this.sourceText == null) { - return null; - } - - this.sourceTextHash = TranslatableText.toHash(this.sourceText); - return this.sourceTextHash; - } - - public static String toHash(String sourceText) { - - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] hash = digest.digest(sourceText.getBytes(StandardCharsets.UTF_8)); - - int singleChar = 1; - StringBuilder hexString = new StringBuilder(2 * hash.length); - for (byte b : hash) { - String hex = Integer.toHexString(0xff & b); - if (hex.length() == singleChar) { - hexString.append('0'); - } - hexString.append(hex); - } - return hexString.toString(); - } catch (Exception e) { - throw new TranslatorException(e.getMessage(), e); - } - } - -} \ No newline at end of file + private final String sourceText; + + private String sourceTextHash; + + private final Format format; + + private String targetText; + + public TranslatableText(String sourceText) { + this.sourceText = sourceText; + this.format = FormatDetector.detect(sourceText); + } + + public TranslatableText(String sourceText, Format format) { + this.sourceText = sourceText; + this.format = format; + } + + public void setTargetText(String targetText) { + this.targetText = targetText; + } + + public Format getFormat() { + return this.format; + } + + public String getSourceText() { + return this.sourceText; + } + + public String getTargetText() { + return this.targetText; + } + + public String toHash() { + + if (this.sourceTextHash != null) { + return this.sourceTextHash; + } + if (this.sourceText == null) { + return null; + } + + this.sourceTextHash = TranslatableText.toHash(this.sourceText); + return this.sourceTextHash; + } + + public static String toHash(String sourceText) { + + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(sourceText.getBytes(StandardCharsets.UTF_8)); + + int singleChar = 1; + StringBuilder hexString = new StringBuilder(2 * hash.length); + for (byte b : hash) { + String hex = Integer.toHexString(0xff & b); + if (hex.length() == singleChar) { + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + } catch (Exception e) { + throw new TranslatorException(e.getMessage(), e); + } + } +} diff --git a/src/main/java/com/sitepark/translate/translator/TranslatableTextListTranslator.java b/src/main/java/com/sitepark/translate/translator/TranslatableTextListTranslator.java index bb6a833..d00c4fe 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatableTextListTranslator.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatableTextListTranslator.java @@ -1,141 +1,129 @@ package com.sitepark.translate.translator; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - import com.sitepark.translate.Format; import com.sitepark.translate.TranslationCache; import com.sitepark.translate.TranslationParameter; import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; import com.sitepark.translate.TranslationResultStatistic; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; public final class TranslatableTextListTranslator extends Translator { - private TranslatableTextListTranslator(Builder builder) { - super(builder); - } - - public TranslationResultStatistic translate( - TranslationParameter parameter, - List translatableTextList) { - - List untranslated = - this.translateWithCacheIfPossible(translatableTextList); - - if (untranslated.isEmpty()) { - return TranslationResultStatistic.EMPTY; - } - - TranslationResultStatistic htmlStatistic = this.translate( - Format.HTML, - parameter, - untranslated); - - TranslationResultStatistic textStatistic = this.translate( - Format.TEXT, - parameter, - untranslated); - - if (this.getTranslationCache() != null) { - this.getTranslationCache().update(translatableTextList); - } - - return htmlStatistic.add(textStatistic); - } - - private TranslationResultStatistic translate( - Format format, - TranslationParameter parameter, - List translatableTextList) { - - List formatFiltered = translatableTextList.stream() - .filter(text -> text.getFormat() == format) - .collect(Collectors.toList()); - - if (formatFiltered.isEmpty()) { - return TranslationResultStatistic.EMPTY; - } - - String[] source = formatFiltered.stream() - .map(node -> { - String text = node.getSourceText(); - return text; - }) - .toArray(String[]::new); - - TranslationParameter parameterWithFormat = parameter.toBuilder() - .format(format) - .build(); - - TranslationRequest req = TranslationRequest.builder() - .parameter(parameterWithFormat) - .sourceText(source) - .build(); - - TranslationResult result = super.translate(req); - for (int i = 0; i < result.getText().length; i++) { - TranslatableText node = formatFiltered.get(i); - String text = result.getText()[i]; - node.setTargetText(text); - } - - return result.getStatistic(); - } - - private TranslationCache getTranslationCache() { - return this.getTranslatorConfiguration().getTranslationCache() - .orElse(null); - } - - /** - * @return all untranslated texts - */ - private List translateWithCacheIfPossible( - List translatableTextList) { - - if (this.getTranslationCache() == null) { - return translatableTextList; - } - - List untranslated = new ArrayList<>(); - - for (TranslatableText text : translatableTextList) { - Optional translatedText = - this.getTranslationCache().translate(text.getSourceText()); - if (translatedText.isPresent()) { - text.setTargetText(translatedText.get()); - } else { - untranslated.add(text); - } - } - - return untranslated; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends Translator.Builder { - - protected Builder() { - } - - protected Builder(TranslatableTextListTranslator updatableListTranslator) { - super(updatableListTranslator); - } - - @Override - protected Builder self() { - return this; - } - - @Override - public TranslatableTextListTranslator build() { - return new TranslatableTextListTranslator(this); - } - } -} \ No newline at end of file + private TranslatableTextListTranslator(Builder builder) { + super(builder); + } + + public TranslationResultStatistic translate( + TranslationParameter parameter, List translatableTextList) { + + List untranslated = + this.translateWithCacheIfPossible(translatableTextList); + + if (untranslated.isEmpty()) { + return TranslationResultStatistic.EMPTY; + } + + TranslationResultStatistic htmlStatistic = this.translate(Format.HTML, parameter, untranslated); + + TranslationResultStatistic textStatistic = this.translate(Format.TEXT, parameter, untranslated); + + if (this.getTranslationCache() != null) { + this.getTranslationCache().update(translatableTextList); + } + + return htmlStatistic.add(textStatistic); + } + + private TranslationResultStatistic translate( + Format format, + TranslationParameter parameter, + List translatableTextList) { + + List formatFiltered = + translatableTextList.stream() + .filter(text -> text.getFormat() == format) + .collect(Collectors.toList()); + + if (formatFiltered.isEmpty()) { + return TranslationResultStatistic.EMPTY; + } + + String[] source = + formatFiltered.stream() + .map( + node -> { + String text = node.getSourceText(); + return text; + }) + .toArray(String[]::new); + + TranslationParameter parameterWithFormat = parameter.toBuilder().format(format).build(); + + TranslationRequest req = + TranslationRequest.builder().parameter(parameterWithFormat).sourceText(source).build(); + + TranslationResult result = super.translate(req); + for (int i = 0; i < result.getText().length; i++) { + TranslatableText node = formatFiltered.get(i); + String text = result.getText()[i]; + node.setTargetText(text); + } + + return result.getStatistic(); + } + + private TranslationCache getTranslationCache() { + return this.getTranslatorConfiguration().getTranslationCache().orElse(null); + } + + /** + * @return all untranslated texts + */ + private List translateWithCacheIfPossible( + List translatableTextList) { + + if (this.getTranslationCache() == null) { + return translatableTextList; + } + + List untranslated = new ArrayList<>(); + + for (TranslatableText text : translatableTextList) { + Optional translatedText = this.getTranslationCache().translate(text.getSourceText()); + if (translatedText.isPresent()) { + text.setTargetText(translatedText.get()); + } else { + untranslated.add(text); + } + } + + return untranslated; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends Translator.Builder { + + protected Builder() {} + + protected Builder(TranslatableTextListTranslator updatableListTranslator) { + super(updatableListTranslator); + } + + @Override + protected Builder self() { + return this; + } + + @Override + public TranslatableTextListTranslator build() { + return new TranslatableTextListTranslator(this); + } + } +} diff --git a/src/main/java/com/sitepark/translate/translator/TranslatableTextNode.java b/src/main/java/com/sitepark/translate/translator/TranslatableTextNode.java index 234fc86..62a86dc 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatableTextNode.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatableTextNode.java @@ -1,42 +1,44 @@ package com.sitepark.translate.translator; -import java.util.Objects; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; public abstract class TranslatableTextNode extends TranslatableText { - private final TextNode node; - - protected TranslatableTextNode(TextNode node) { - super(node.asText()); - this.node = node; - } - - @SuppressFBWarnings("EI_EXPOSE_REP") - public TextNode getNode() { - return this.node; - } - - public static TranslatableTextNode create(JsonNode parent, Object key, TextNode node) { - - Objects.requireNonNull(parent, "parent is null"); - Objects.requireNonNull(key, "key is null"); - Objects.requireNonNull(node, "node is null"); - - if (parent instanceof ObjectNode && key instanceof String) { - return new TranslatableTextNodeInObject((ObjectNode)parent, (String)key, node); - } else if (parent instanceof ArrayNode && key instanceof Integer) { - return new TranslatableTextNodeOfArray((ArrayNode)parent, (Integer)key, node); - } else { - throw new IllegalArgumentException("ObjectNode-Parent with String-Key or " + - "ArrayNode-Parent with Integer-Key expected. " + - "parent:" + parent.getClass().getName() + ", key:" + key.getClass().getName()); - } - } -} \ No newline at end of file + private final TextNode node; + + protected TranslatableTextNode(TextNode node) { + super(node.asText()); + this.node = node; + } + + @SuppressFBWarnings("EI_EXPOSE_REP") + public TextNode getNode() { + return this.node; + } + + public static TranslatableTextNode create(JsonNode parent, Object key, TextNode node) { + + Objects.requireNonNull(parent, "parent is null"); + Objects.requireNonNull(key, "key is null"); + Objects.requireNonNull(node, "node is null"); + + if (parent instanceof ObjectNode && key instanceof String) { + return new TranslatableTextNodeInObject((ObjectNode) parent, (String) key, node); + } else if (parent instanceof ArrayNode && key instanceof Integer) { + return new TranslatableTextNodeOfArray((ArrayNode) parent, (Integer) key, node); + } else { + throw new IllegalArgumentException( + "ObjectNode-Parent with String-Key or " + + "ArrayNode-Parent with Integer-Key expected. " + + "parent:" + + parent.getClass().getName() + + ", key:" + + key.getClass().getName()); + } + } +} diff --git a/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeCollector.java b/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeCollector.java index e663ab5..0123492 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeCollector.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeCollector.java @@ -1,39 +1,45 @@ package com.sitepark.translate.translator; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.function.Consumer; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Consumer; public class TranslatableTextNodeCollector { - public List collect(List jsonList) { - List translatableTextNodeList = new ArrayList<>(); - for (JsonNode json : jsonList) { - this.filterTextNodes(null, null, json, (node) -> { - translatableTextNodeList.add(node); - }); - } - return translatableTextNodeList; - } + public List collect(List jsonList) { + List translatableTextNodeList = new ArrayList<>(); + for (JsonNode json : jsonList) { + this.filterTextNodes( + null, + null, + json, + (node) -> { + translatableTextNodeList.add(node); + }); + } + return translatableTextNodeList; + } - private void filterTextNodes(JsonNode parent, Object key, JsonNode node, Consumer consumer) { - if (node instanceof ObjectNode) { - node.fields().forEachRemaining(e -> filterTextNodes(node, e.getKey(), e.getValue(), consumer)); - } else if (node instanceof ArrayNode) { - ArrayNode arrayNode = (ArrayNode)node; - Iterator it = arrayNode.elements(); - for (int i = 0; it.hasNext(); i++) { - this.filterTextNodes(node, i, it.next(), consumer); - } - } else if (node instanceof TextNode) { - TranslatableTextNode updatableTextNode = TranslatableTextNode.create(parent, key, (TextNode)node); - consumer.accept(updatableTextNode); - } - } + private void filterTextNodes( + JsonNode parent, Object key, JsonNode node, Consumer consumer) { + if (node instanceof ObjectNode) { + node.fields() + .forEachRemaining(e -> filterTextNodes(node, e.getKey(), e.getValue(), consumer)); + } else if (node instanceof ArrayNode) { + ArrayNode arrayNode = (ArrayNode) node; + Iterator it = arrayNode.elements(); + for (int i = 0; it.hasNext(); i++) { + this.filterTextNodes(node, i, it.next(), consumer); + } + } else if (node instanceof TextNode) { + TranslatableTextNode updatableTextNode = + TranslatableTextNode.create(parent, key, (TextNode) node); + consumer.accept(updatableTextNode); + } + } } diff --git a/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeInObject.java b/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeInObject.java index 3a35efe..a9c8c9e 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeInObject.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeInObject.java @@ -5,19 +5,19 @@ class TranslatableTextNodeInObject extends TranslatableTextNode { - private final ObjectNode object; + private final ObjectNode object; - private final String key; + private final String key; - public TranslatableTextNodeInObject(ObjectNode object, String key, TextNode node) { - super(node); - this.object = object; - this.key = key; - } + public TranslatableTextNodeInObject(ObjectNode object, String key, TextNode node) { + super(node); + this.object = object; + this.key = key; + } - @Override - public void setTargetText(String text) { - this.object.put(this.key, text); - super.setTargetText(text); - } -} \ No newline at end of file + @Override + public void setTargetText(String text) { + this.object.put(this.key, text); + super.setTargetText(text); + } +} diff --git a/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeOfArray.java b/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeOfArray.java index 5904eab..5ff0893 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeOfArray.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatableTextNodeOfArray.java @@ -5,19 +5,19 @@ class TranslatableTextNodeOfArray extends TranslatableTextNode { - private final ArrayNode array; + private final ArrayNode array; - private final int index; + private final int index; - public TranslatableTextNodeOfArray(ArrayNode array, int index, TextNode node) { - super(node); - this.array = array; - this.index = index; - } + public TranslatableTextNodeOfArray(ArrayNode array, int index, TextNode node) { + super(node); + this.array = array; + this.index = index; + } - @Override - public void setTargetText(String targetText) { - this.array.set(this.index, targetText); - super.setTargetText(targetText); - } -} \ No newline at end of file + @Override + public void setTargetText(String targetText) { + this.array.set(this.index, targetText); + super.setTargetText(targetText); + } +} diff --git a/src/main/java/com/sitepark/translate/translator/TranslationFileCache.java b/src/main/java/com/sitepark/translate/translator/TranslationFileCache.java index a7e7acd..beec834 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslationFileCache.java +++ b/src/main/java/com/sitepark/translate/translator/TranslationFileCache.java @@ -1,5 +1,8 @@ package com.sitepark.translate.translator; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sitepark.translate.TranslationCache; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -8,63 +11,58 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.sitepark.translate.TranslationCache; - public class TranslationFileCache implements TranslationCache { - private final Map cache = new ConcurrentHashMap<>(); + private final Map cache = new ConcurrentHashMap<>(); - private final Path file; + private final Path file; - public TranslationFileCache(Path file) { - this.file = file.toAbsolutePath(); - } + public TranslationFileCache(Path file) { + this.file = file.toAbsolutePath(); + } - public Path getFile() { - return this.file; - } + public Path getFile() { + return this.file; + } - public void load() throws IOException { + public void load() throws IOException { - if (!Files.exists(this.file)) { - return; - } + if (!Files.exists(this.file)) { + return; + } - ObjectMapper mapper = new ObjectMapper(); - this.cache.clear(); - this.cache.putAll( - mapper.readValue(this.file.toFile(), new CacheType())); - } + ObjectMapper mapper = new ObjectMapper(); + this.cache.clear(); + this.cache.putAll(mapper.readValue(this.file.toFile(), new CacheType())); + } - public void store() throws IOException { - Path parent = this.getFile().getParent(); - if (parent != null) { - Files.createDirectories(parent); - } - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(this.file.toFile(), this.cache); - } + public void store() throws IOException { + Path parent = this.getFile().getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(this.file.toFile(), this.cache); + } - @Override - public Optional translate(String sourceText) { - Integer key = this.toKey(sourceText); - return Optional.ofNullable(this.cache.get(key)); - } + @Override + public Optional translate(String sourceText) { + Integer key = this.toKey(sourceText); + return Optional.ofNullable(this.cache.get(key)); + } - @Override - public void update(List translated) { - this.cache.clear(); - for (TranslatableText text : translated) { - Integer key = this.toKey(text.getSourceText()); - this.cache.put(key, text.getTargetText()); - } - } + @Override + public void update(List translated) { + this.cache.clear(); + for (TranslatableText text : translated) { + Integer key = this.toKey(text.getSourceText()); + this.cache.put(key, text.getTargetText()); + } + } - private Integer toKey(String text) { - return text.hashCode(); - } + private Integer toKey(String text) { + return text.hashCode(); + } - private final static class CacheType extends TypeReference> { } + private static final class CacheType extends TypeReference> {} } diff --git a/src/main/java/com/sitepark/translate/translator/Translator.java b/src/main/java/com/sitepark/translate/translator/Translator.java index fe73b09..5ae6e2e 100644 --- a/src/main/java/com/sitepark/translate/translator/Translator.java +++ b/src/main/java/com/sitepark/translate/translator/Translator.java @@ -1,65 +1,61 @@ package com.sitepark.translate.translator; -import java.util.Objects; - import com.sitepark.translate.SupportedProvider; import com.sitepark.translate.TranslationConfiguration; import com.sitepark.translate.TranslationProvider; import com.sitepark.translate.TranslationProviderFactory; import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; +import java.util.Objects; public abstract class Translator { - private final TranslationConfiguration translatorConfiguration; - - protected Translator(Builder builder) { - this.translatorConfiguration = builder.translatorConfiguration; - } + private final TranslationConfiguration translatorConfiguration; - protected TranslationConfiguration getTranslatorConfiguration() { - return this.translatorConfiguration; - } + protected Translator(Builder builder) { + this.translatorConfiguration = builder.translatorConfiguration; + } - protected TranslationProvider createTransporter(SupportedProvider providerType) { - return this.getTransporterFactory().create(providerType); - } + protected TranslationConfiguration getTranslatorConfiguration() { + return this.translatorConfiguration; + } - private TranslationProviderFactory getTransporterFactory() { - return this.translatorConfiguration.getTranslationProviderFactory(); - } + protected TranslationProvider createTransporter(SupportedProvider providerType) { + return this.getTransporterFactory().create(providerType); + } - protected TranslationResult translate(TranslationRequest req) { - return this.createTransporter(req.getParameter().getProviderType()) - .translate(req); - } + private TranslationProviderFactory getTransporterFactory() { + return this.translatorConfiguration.getTranslationProviderFactory(); + } - public static abstract class Builder> { + protected TranslationResult translate(TranslationRequest req) { + return this.createTransporter(req.getParameter().getProviderType()).translate(req); + } - private TranslationConfiguration translatorConfiguration; + public abstract static class Builder> { - protected Builder() { - } + private TranslationConfiguration translatorConfiguration; - protected Builder(Translator translator) { - this.translatorConfiguration = translator.translatorConfiguration; - } + protected Builder() {} - public B translatorConfiguration(TranslationConfiguration.Builder translatorConfiguration) { - Objects.requireNonNull(translatorConfiguration, "translatorConfiguration is null"); - this.translatorConfiguration = translatorConfiguration.build(); - return this.self(); - } + protected Builder(Translator translator) { + this.translatorConfiguration = translator.translatorConfiguration; + } - public B translatorConfiguration(TranslationConfiguration translatorConfiguration) { - Objects.requireNonNull(translatorConfiguration, "translatorConfiguration is null"); - this.translatorConfiguration = translatorConfiguration; - return this.self(); - } + public B translatorConfiguration(TranslationConfiguration.Builder translatorConfiguration) { + Objects.requireNonNull(translatorConfiguration, "translatorConfiguration is null"); + this.translatorConfiguration = translatorConfiguration.build(); + return this.self(); + } - protected abstract B self(); + public B translatorConfiguration(TranslationConfiguration translatorConfiguration) { + Objects.requireNonNull(translatorConfiguration, "translatorConfiguration is null"); + this.translatorConfiguration = translatorConfiguration; + return this.self(); + } - public abstract Translator build(); + protected abstract B self(); - } + public abstract Translator build(); + } } diff --git a/src/main/java/com/sitepark/translate/translator/TranslatorException.java b/src/main/java/com/sitepark/translate/translator/TranslatorException.java index d6eab1e..9b7fab4 100644 --- a/src/main/java/com/sitepark/translate/translator/TranslatorException.java +++ b/src/main/java/com/sitepark/translate/translator/TranslatorException.java @@ -2,10 +2,9 @@ public class TranslatorException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public TranslatorException(String msg, Throwable t) { - super(msg, t); - } + private static final long serialVersionUID = 1L; + public TranslatorException(String msg, Throwable t) { + super(msg, t); + } } diff --git a/src/main/java/com/sitepark/translate/translator/UnifiedSourceText.java b/src/main/java/com/sitepark/translate/translator/UnifiedSourceText.java index 9abd566..f4200b5 100644 --- a/src/main/java/com/sitepark/translate/translator/UnifiedSourceText.java +++ b/src/main/java/com/sitepark/translate/translator/UnifiedSourceText.java @@ -8,48 +8,48 @@ public class UnifiedSourceText { - private final String[] sourceText; - - private String[] unifiedText; - - @SuppressWarnings("PMD.UseConcurrentHashMap") - private final Map> index = new LinkedHashMap<>(); - - public UnifiedSourceText(String... sourceText) { - this.sourceText = Arrays.copyOf(sourceText, sourceText.length); - this.unify(); - } - - private void unify() { - for (int i = 0; i < this.sourceText.length; i++) { - this.unify(i, this.sourceText[i]); - } - this.unifiedText = this.index.keySet().stream().toArray(String[]::new); - } - - private void unify(int i, String text) { - List list = this.index.get(text); - if (list == null) { - list = new ArrayList<>(); - this.index.put(text, list); - } - list.add(i); - } - - public String[] getSourceText() { - return Arrays.copyOf(this.unifiedText, this.unifiedText.length); - } - - public String[] expandTranslation(String... unifiedTranslation) { - String[] translation = new String[this.sourceText.length]; - for (int i = 0; i < unifiedTranslation.length; i++) { - String text = unifiedTranslation[i]; - - List indexList = this.index.get(this.unifiedText[i]); - for (Integer index : indexList) { - translation[index] = text; - } - } - return translation; - } -} \ No newline at end of file + private final String[] sourceText; + + private String[] unifiedText; + + @SuppressWarnings("PMD.UseConcurrentHashMap") + private final Map> index = new LinkedHashMap<>(); + + public UnifiedSourceText(String... sourceText) { + this.sourceText = Arrays.copyOf(sourceText, sourceText.length); + this.unify(); + } + + private void unify() { + for (int i = 0; i < this.sourceText.length; i++) { + this.unify(i, this.sourceText[i]); + } + this.unifiedText = this.index.keySet().stream().toArray(String[]::new); + } + + private void unify(int i, String text) { + List list = this.index.get(text); + if (list == null) { + list = new ArrayList<>(); + this.index.put(text, list); + } + list.add(i); + } + + public String[] getSourceText() { + return Arrays.copyOf(this.unifiedText, this.unifiedText.length); + } + + public String[] expandTranslation(String... unifiedTranslation) { + String[] translation = new String[this.sourceText.length]; + for (int i = 0; i < unifiedTranslation.length; i++) { + String text = unifiedTranslation[i]; + + List indexList = this.index.get(this.unifiedText[i]); + for (Integer index : indexList) { + translation[index] = text; + } + } + return translation; + } +} diff --git a/src/main/java/com/sitepark/translate/translator/entity/Decoder.java b/src/main/java/com/sitepark/translate/translator/entity/Decoder.java index 3a2b69a..7806360 100644 --- a/src/main/java/com/sitepark/translate/translator/entity/Decoder.java +++ b/src/main/java/com/sitepark/translate/translator/entity/Decoder.java @@ -6,26 +6,23 @@ public final class Decoder { - private Decoder() {} + private Decoder() {} - public static String[] decode(String... text) { - return Arrays.stream(text) - .map(Decoder::decode) - .toArray(String[]::new); - } + public static String[] decode(String... text) { + return Arrays.stream(text).map(Decoder::decode).toArray(String[]::new); + } - public static String decode(String text) { - Pattern pattern = Pattern.compile("()(.*?)()"); - Matcher matcher = pattern.matcher(text); - int start = 0; - StringBuilder decoded = new StringBuilder(); - while (matcher.find()) { - decoded - .append(text.substring(start, matcher.start(1))) - .append(matcher.group(2)); - start = matcher.end(); - } - decoded.append(text.substring(start, text.length())); - return decoded.toString(); - } + public static String decode(String text) { + Pattern pattern = + Pattern.compile("()(.*?)()"); + Matcher matcher = pattern.matcher(text); + int start = 0; + StringBuilder decoded = new StringBuilder(); + while (matcher.find()) { + decoded.append(text.substring(start, matcher.start(1))).append(matcher.group(2)); + start = matcher.end(); + } + decoded.append(text.substring(start, text.length())); + return decoded.toString(); + } } diff --git a/src/main/java/com/sitepark/translate/translator/entity/Encoder.java b/src/main/java/com/sitepark/translate/translator/entity/Encoder.java index 9dc6d62..504ce1d 100644 --- a/src/main/java/com/sitepark/translate/translator/entity/Encoder.java +++ b/src/main/java/com/sitepark/translate/translator/entity/Encoder.java @@ -4,30 +4,28 @@ public final class Encoder { - private Encoder() {} - - public static String[] encode(String... text) { - return Arrays.stream(text) - .map(Encoder::encode) - .toArray(String[]::new); - } - - public static String encode(String text) { - - StringBuilder encoded = new StringBuilder(70); - Scanner scanner = new Scanner(text); - - for (Token token : scanner.scanTokens()) { - if (token.type == TokenType.STRING) { - encoded.append(token.lexeme); - } else if (token.type == TokenType.ENTITY) { - encoded - .append("") - .append(token.lexeme) - .append(""); - } - } - - return encoded.toString(); - } + private Encoder() {} + + public static String[] encode(String... text) { + return Arrays.stream(text).map(Encoder::encode).toArray(String[]::new); + } + + public static String encode(String text) { + + StringBuilder encoded = new StringBuilder(70); + Scanner scanner = new Scanner(text); + + for (Token token : scanner.scanTokens()) { + if (token.type == TokenType.STRING) { + encoded.append(token.lexeme); + } else if (token.type == TokenType.ENTITY) { + encoded + .append("") + .append(token.lexeme) + .append(""); + } + } + + return encoded.toString(); + } } diff --git a/src/main/java/com/sitepark/translate/translator/entity/Scanner.java b/src/main/java/com/sitepark/translate/translator/entity/Scanner.java index 5270c10..08ef0eb 100644 --- a/src/main/java/com/sitepark/translate/translator/entity/Scanner.java +++ b/src/main/java/com/sitepark/translate/translator/entity/Scanner.java @@ -8,114 +8,112 @@ class Scanner { - private final String source; - private final List tokens = new ArrayList<>(); - private int start; - private int current; - - Scanner(String source) { - this.source = source; - } - - List scanTokens() { - while (!isAtEnd()) { - // We are at the beginning of the next lexeme. - start = current; // NOPMD by veltrup on 24.05.23, 15:38 - scanToken(); - } - - tokens.add(new Token(EOF, "")); - return tokens; - } - - private boolean isAtEnd() { - return current >= source.length(); - } - - private void scanToken() { - char c = advance(); - switch (c) { - case '$': - if (match('{')) { - entity('}'); - } else { - string(); - } - break; - case '{': - entity('}'); - break; - default : - string(); - break; - } - } - - private void entity(char expectedEnd) { - while (!isAtEnd() && isIdentifierChar(peek())) { - advance(); - } - if (peek() == expectedEnd) { - advance(); - addToken(TokenType.ENTITY); - } else { - string(); - } - } - - private void string() { - while (!isAtEnd() && isStringChar(peek())) { - advance(); - } - addToken(STRING); - } - - private char advance() { - return source.charAt(current++); - } - - private void addToken(TokenType type) { - String text = source.substring(start, current); - tokens.add(new Token(type, text)); - } - - private boolean match(char expected) { - if (isAtEnd()) { - return false; - } - if (source.charAt(current) != expected) { - return false; - } - current++; - return true; - } - - private char peek() { - if (isAtEnd()) { - return '\0'; - } - return source.charAt(current); - } - - private boolean isDigit(char c) { - return c >= '0' && c <= '9'; - } - - private boolean isAlpha(char c) { - return (c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - c == '_'; - } - - private boolean isAlphaNumeric(char c) { - return isAlpha(c) || isDigit(c); - } - - private boolean isIdentifierChar(char c) { - return isAlphaNumeric(c) || c == '-' || c == '.'; - } - - private boolean isStringChar(char c) { - return c != '$' && c != '{'; - } + private final String source; + private final List tokens = new ArrayList<>(); + private int start; + private int current; + + Scanner(String source) { + this.source = source; + } + + List scanTokens() { + while (!isAtEnd()) { + // We are at the beginning of the next lexeme. + start = current; // NOPMD by veltrup on 24.05.23, 15:38 + scanToken(); + } + + tokens.add(new Token(EOF, "")); + return tokens; + } + + private boolean isAtEnd() { + return current >= source.length(); + } + + private void scanToken() { + char c = advance(); + switch (c) { + case '$': + if (match('{')) { + entity('}'); + } else { + string(); + } + break; + case '{': + entity('}'); + break; + default: + string(); + break; + } + } + + private void entity(char expectedEnd) { + while (!isAtEnd() && isIdentifierChar(peek())) { + advance(); + } + if (peek() == expectedEnd) { + advance(); + addToken(TokenType.ENTITY); + } else { + string(); + } + } + + private void string() { + while (!isAtEnd() && isStringChar(peek())) { + advance(); + } + addToken(STRING); + } + + private char advance() { + return source.charAt(current++); + } + + private void addToken(TokenType type) { + String text = source.substring(start, current); + tokens.add(new Token(type, text)); + } + + private boolean match(char expected) { + if (isAtEnd()) { + return false; + } + if (source.charAt(current) != expected) { + return false; + } + current++; + return true; + } + + private char peek() { + if (isAtEnd()) { + return '\0'; + } + return source.charAt(current); + } + + private boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + private boolean isAlpha(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; + } + + private boolean isAlphaNumeric(char c) { + return isAlpha(c) || isDigit(c); + } + + private boolean isIdentifierChar(char c) { + return isAlphaNumeric(c) || c == '-' || c == '.'; + } + + private boolean isStringChar(char c) { + return c != '$' && c != '{'; + } } diff --git a/src/main/java/com/sitepark/translate/translator/entity/Token.java b/src/main/java/com/sitepark/translate/translator/entity/Token.java index 3b6fc84..5cf969e 100644 --- a/src/main/java/com/sitepark/translate/translator/entity/Token.java +++ b/src/main/java/com/sitepark/translate/translator/entity/Token.java @@ -1,16 +1,16 @@ package com.sitepark.translate.translator.entity; public class Token { - final TokenType type; - final String lexeme; + final TokenType type; + final String lexeme; - Token(TokenType type, String lexeme) { - this.type = type; - this.lexeme = lexeme; - } + Token(TokenType type, String lexeme) { + this.type = type; + this.lexeme = lexeme; + } - @Override - public String toString() { - return type + " " + lexeme; - } + @Override + public String toString() { + return type + " " + lexeme; + } } diff --git a/src/main/java/com/sitepark/translate/translator/entity/TokenType.java b/src/main/java/com/sitepark/translate/translator/entity/TokenType.java index efff5c2..c38a4ca 100644 --- a/src/main/java/com/sitepark/translate/translator/entity/TokenType.java +++ b/src/main/java/com/sitepark/translate/translator/entity/TokenType.java @@ -2,8 +2,9 @@ public enum TokenType { - // Literals. - ENTITY, STRING, + // Literals. + ENTITY, + STRING, - EOF + EOF } diff --git a/src/test/java/com/sitepark/translate/FormatTest.java b/src/test/java/com/sitepark/translate/FormatTest.java index 1c7e86c..c7ec14b 100644 --- a/src/test/java/com/sitepark/translate/FormatTest.java +++ b/src/test/java/com/sitepark/translate/FormatTest.java @@ -6,14 +6,13 @@ class FormatTest { - @Test - void testText() { - assertEquals("text", Format.TEXT.toString(), "should be lower case"); - } - - @Test - void testHtml() { - assertEquals("html", Format.HTML.toString(), "should be lower case"); - } + @Test + void testText() { + assertEquals("text", Format.TEXT.toString(), "should be lower case"); + } + @Test + void testHtml() { + assertEquals("html", Format.HTML.toString(), "should be lower case"); + } } diff --git a/src/test/java/com/sitepark/translate/GlossaryChangeSetTest.java b/src/test/java/com/sitepark/translate/GlossaryChangeSetTest.java index 7bfa6f2..1d6bfc1 100644 --- a/src/test/java/com/sitepark/translate/GlossaryChangeSetTest.java +++ b/src/test/java/com/sitepark/translate/GlossaryChangeSetTest.java @@ -3,45 +3,36 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; - -import org.junit.jupiter.api.Test; - import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; class GlossaryChangeSetTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - public void testEqualsContract() { - EqualsVerifier.forClass(GlossaryChangeSet.class).verify(); - } - - @Test - public void testAdded() { + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + public void testEqualsContract() { + EqualsVerifier.forClass(GlossaryChangeSet.class).verify(); + } - GlossaryChangeSet changeSet = new GlossaryChangeSet(); - GlossaryEntry entry = GlossaryEntry.builder() - .source("Hallo") - .target("Hello") - .build(); + @Test + public void testAdded() { - changeSet.added(entry); + GlossaryChangeSet changeSet = new GlossaryChangeSet(); + GlossaryEntry entry = GlossaryEntry.builder().source("Hallo").target("Hello").build(); - assertEquals(Arrays.asList(entry), changeSet.getAdded(), "unexpected added list"); - } + changeSet.added(entry); - @Test - public void testDeleted() { + assertEquals(Arrays.asList(entry), changeSet.getAdded(), "unexpected added list"); + } - GlossaryChangeSet changeSet = new GlossaryChangeSet(); - GlossaryEntry entry = GlossaryEntry.builder() - .source("Hallo") - .target("Hello") - .build(); + @Test + public void testDeleted() { - changeSet.deleted(entry); + GlossaryChangeSet changeSet = new GlossaryChangeSet(); + GlossaryEntry entry = GlossaryEntry.builder().source("Hallo").target("Hello").build(); - assertEquals(Arrays.asList(entry), changeSet.getDeleted(), "unexpected deleted list"); - } + changeSet.deleted(entry); + assertEquals(Arrays.asList(entry), changeSet.getDeleted(), "unexpected deleted list"); + } } diff --git a/src/test/java/com/sitepark/translate/GlossaryDifferTest.java b/src/test/java/com/sitepark/translate/GlossaryDifferTest.java index f174a26..5a1d101 100644 --- a/src/test/java/com/sitepark/translate/GlossaryDifferTest.java +++ b/src/test/java/com/sitepark/translate/GlossaryDifferTest.java @@ -6,61 +6,32 @@ class GlossaryDifferTest { - @Test - void test() { - - Glossary a = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Hallo") - .target("Hello") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Blau") - .target("Blue") - .build() - ) - .build(); - - Glossary b = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Hallo") - .target("Hello") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Grün") - .target("Green") - .build() - ) - .build(); - - GlossaryDiffer differ = new GlossaryDiffer(a, b); - GlossaryChangeSet changeSet = differ.diff(); - - GlossaryChangeSet expected = new GlossaryChangeSet(); - expected.added(GlossaryEntry.builder() - .source("Grün") - .target("Green") - .build()); - expected.deleted(GlossaryEntry.builder() - .source("Blau") - .target("Blue") - .build()); - - assertEquals(expected, changeSet, "unexpected changeset"); - } - + @Test + void test() { + + Glossary a = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(GlossaryEntry.builder().source("Hallo").target("Hello").build()) + .entry(GlossaryEntry.builder().source("Blau").target("Blue").build()) + .build(); + + Glossary b = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(GlossaryEntry.builder().source("Hallo").target("Hello").build()) + .entry(GlossaryEntry.builder().source("Grün").target("Green").build()) + .build(); + + GlossaryDiffer differ = new GlossaryDiffer(a, b); + GlossaryChangeSet changeSet = differ.diff(); + + GlossaryChangeSet expected = new GlossaryChangeSet(); + expected.added(GlossaryEntry.builder().source("Grün").target("Green").build()); + expected.deleted(GlossaryEntry.builder().source("Blau").target("Blue").build()); + + assertEquals(expected, changeSet, "unexpected changeset"); + } } diff --git a/src/test/java/com/sitepark/translate/GlossaryEntryTest.java b/src/test/java/com/sitepark/translate/GlossaryEntryTest.java index b648e4c..b400d39 100644 --- a/src/test/java/com/sitepark/translate/GlossaryEntryTest.java +++ b/src/test/java/com/sitepark/translate/GlossaryEntryTest.java @@ -3,89 +3,97 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; class GlossaryEntryTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - public void testEqualsContract() { - EqualsVerifier.forClass(GlossaryEntry.class).verify(); - } - - @Test - public void testSetSource() { - GlossaryEntry entry = GlossaryEntry.builder() - .source("de") - .target("en") - .build(); - assertEquals("de", entry.getSource(), "unexpected source"); - } - - @Test - public void testNullSource() { - assertThrows(NullPointerException.class, () -> { - GlossaryEntry.builder().source(null); - }, "Setting null as source should not be allowed"); - } - - @Test - public void testBlankSource() { - assertThrows(IllegalArgumentException.class, () -> { - GlossaryEntry.builder().source(" "); - }, "Setting blank string as source should not be allowed"); - } - - @Test - public void testUnsetSource() { - assertThrows(IllegalStateException.class, () -> { - GlossaryEntry.builder().target("en").build(); - }, "Unset source should not be allowed"); - } - - @Test - public void testSetTarget() { - GlossaryEntry entry = GlossaryEntry.builder() - .source("de") - .target("en") - .build(); - assertEquals("en", entry.getTarget(), "unexpected source"); - } - - @Test - public void testNullTarget() { - assertThrows(NullPointerException.class, () -> { - GlossaryEntry.builder().target(null); - }, "Setting null as target should not be allowed"); - } - - @Test - public void testBlankTarget() { - assertThrows(IllegalArgumentException.class, () -> { - GlossaryEntry.builder().target(" "); - }, "Setting blank string as target should not be allowed"); - } - - @Test - public void testUnsetTarget() { - assertThrows(IllegalStateException.class, () -> { - GlossaryEntry.builder().source("de").build(); - }, "Unset source should not be allowed"); - } - - @Test - public void testToBuilder() { - - GlossaryEntry entry = GlossaryEntry.builder() - .source("de") - .target("en") - .build(); - - GlossaryEntry copy = entry.toBuilder().build(); - - assertEquals("de", copy.getSource(), "unexpected source"); - assertEquals("en", copy.getTarget(), "unexpected target"); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + public void testEqualsContract() { + EqualsVerifier.forClass(GlossaryEntry.class).verify(); + } + + @Test + public void testSetSource() { + GlossaryEntry entry = GlossaryEntry.builder().source("de").target("en").build(); + assertEquals("de", entry.getSource(), "unexpected source"); + } + + @Test + public void testNullSource() { + assertThrows( + NullPointerException.class, + () -> { + GlossaryEntry.builder().source(null); + }, + "Setting null as source should not be allowed"); + } + + @Test + public void testBlankSource() { + assertThrows( + IllegalArgumentException.class, + () -> { + GlossaryEntry.builder().source(" "); + }, + "Setting blank string as source should not be allowed"); + } + + @Test + public void testUnsetSource() { + assertThrows( + IllegalStateException.class, + () -> { + GlossaryEntry.builder().target("en").build(); + }, + "Unset source should not be allowed"); + } + + @Test + public void testSetTarget() { + GlossaryEntry entry = GlossaryEntry.builder().source("de").target("en").build(); + assertEquals("en", entry.getTarget(), "unexpected source"); + } + + @Test + public void testNullTarget() { + assertThrows( + NullPointerException.class, + () -> { + GlossaryEntry.builder().target(null); + }, + "Setting null as target should not be allowed"); + } + + @Test + public void testBlankTarget() { + assertThrows( + IllegalArgumentException.class, + () -> { + GlossaryEntry.builder().target(" "); + }, + "Setting blank string as target should not be allowed"); + } + + @Test + public void testUnsetTarget() { + assertThrows( + IllegalStateException.class, + () -> { + GlossaryEntry.builder().source("de").build(); + }, + "Unset source should not be allowed"); + } + + @Test + public void testToBuilder() { + + GlossaryEntry entry = GlossaryEntry.builder().source("de").target("en").build(); + + GlossaryEntry copy = entry.toBuilder().build(); + + assertEquals("de", copy.getSource(), "unexpected source"); + assertEquals("en", copy.getTarget(), "unexpected target"); + } } diff --git a/src/test/java/com/sitepark/translate/GlossaryTest.java b/src/test/java/com/sitepark/translate/GlossaryTest.java index 35fc76f..51bc4a8 100644 --- a/src/test/java/com/sitepark/translate/GlossaryTest.java +++ b/src/test/java/com/sitepark/translate/GlossaryTest.java @@ -5,223 +5,198 @@ import java.util.Arrays; import java.util.List; - -import org.junit.jupiter.api.Test; - import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.AvoidDuplicateLiterals") class GlossaryTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - public void testEqualsContract() { - EqualsVerifier.forClass(Glossary.class).verify(); - } - - @Test - public void testSetName() { - - Glossary glossar = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .build(); - - assertEquals("test:de/en", glossar.getName(), "unexpected name"); - } - - @Test - public void testNullName() { - assertThrows(NullPointerException.class, () -> { - Glossary.builder().name(null); - }, "Setting null as name should not be allowed"); - } - - @Test - public void testBlankName() { - assertThrows(IllegalArgumentException.class, () -> { - Glossary.builder().name(" "); - }, "Setting blank name should not be allowed"); - } - - @Test - public void testUnsetName() { - assertThrows(IllegalStateException.class, () -> { - Glossary.builder() - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .build(); - }, "Missing name must lead to an error"); - } - - @Test - public void testSetLanguage() { - - Glossary glossar = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .build(); - - TranslationLanguage expected = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); - - assertEquals(expected, glossar.getLanguage(), "unexpected language"); - } - - @Test - public void testNullSourceLanguage() { - assertThrows(NullPointerException.class, () -> { - Glossary.builder().language(null); - }, "Setting null as language should not be allowed"); - } - - @Test - public void testUnsetLanguage() { - assertThrows(IllegalStateException.class, () -> { - Glossary.builder() - .name("test:de/en") - .build(); - }, "Missing language must lead to an error"); - } - - @Test - public void testSetEntry() { - - GlossaryEntry entry = GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build(); - - Glossary glossar = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(entry) - .build(); - - assertEquals(Arrays.asList(entry), glossar.getEntryList(), "unexpected entryList"); - } - - @Test - public void testSetEntryArray() { - - GlossaryEntry[] entryArray = new GlossaryEntry[] { - GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build() - }; - - Glossary glossar = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entryList(entryArray) - .build(); - - assertEquals(Arrays.asList(entryArray), glossar.getEntryList(), "unexpected entryList"); - } - - @Test - public void testSetEntryList() { - - List entryList = Arrays.asList( - GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build()); - - Glossary glossar = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entryList(entryList) - .build(); - - assertEquals(entryList, glossar.getEntryList(), "unexpected entryList"); - } - - @Test - public void testNullEntryList() { - assertThrows(NullPointerException.class, () -> { - Glossary.builder().entryList((List)null); - }); - } - - @Test - public void testNullEntryInList() { - assertThrows(NullPointerException.class, () -> { - Glossary.builder().entryList(Arrays.asList((GlossaryEntry)null)); - }); - } - - @Test - public void testNullEntryArray() { - assertThrows(NullPointerException.class, () -> { - Glossary.builder().entryList((GlossaryEntry[])null); - }); - } - - @Test - public void testNullEntry() { - assertThrows(NullPointerException.class, () -> { - Glossary.builder().entry(null); - }); - } - - @Test - public void testToBuilder() { - - Glossary glossary = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build()) - .build(); - - Glossary copy = glossary.toBuilder().build(); - - Glossary expected = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build()) - .build(); - - assertEquals(expected, copy, "unexpected glossary"); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + public void testEqualsContract() { + EqualsVerifier.forClass(Glossary.class).verify(); + } + + @Test + public void testSetName() { + + Glossary glossar = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .build(); + + assertEquals("test:de/en", glossar.getName(), "unexpected name"); + } + + @Test + public void testNullName() { + assertThrows( + NullPointerException.class, + () -> { + Glossary.builder().name(null); + }, + "Setting null as name should not be allowed"); + } + + @Test + public void testBlankName() { + assertThrows( + IllegalArgumentException.class, + () -> { + Glossary.builder().name(" "); + }, + "Setting blank name should not be allowed"); + } + + @Test + public void testUnsetName() { + assertThrows( + IllegalStateException.class, + () -> { + Glossary.builder() + .language(TranslationLanguage.builder().source("de").target("en").build()) + .build(); + }, + "Missing name must lead to an error"); + } + + @Test + public void testSetLanguage() { + + Glossary glossar = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .build(); + + TranslationLanguage expected = TranslationLanguage.builder().source("de").target("en").build(); + + assertEquals(expected, glossar.getLanguage(), "unexpected language"); + } + + @Test + public void testNullSourceLanguage() { + assertThrows( + NullPointerException.class, + () -> { + Glossary.builder().language(null); + }, + "Setting null as language should not be allowed"); + } + + @Test + public void testUnsetLanguage() { + assertThrows( + IllegalStateException.class, + () -> { + Glossary.builder().name("test:de/en").build(); + }, + "Missing language must lead to an error"); + } + + @Test + public void testSetEntry() { + + GlossaryEntry entry = GlossaryEntry.builder().source("Hallo").target("Hey").build(); + + Glossary glossar = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(entry) + .build(); + + assertEquals(Arrays.asList(entry), glossar.getEntryList(), "unexpected entryList"); + } + + @Test + public void testSetEntryArray() { + + GlossaryEntry[] entryArray = + new GlossaryEntry[] {GlossaryEntry.builder().source("Hallo").target("Hey").build()}; + + Glossary glossar = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entryList(entryArray) + .build(); + + assertEquals(Arrays.asList(entryArray), glossar.getEntryList(), "unexpected entryList"); + } + + @Test + public void testSetEntryList() { + + List entryList = + Arrays.asList(GlossaryEntry.builder().source("Hallo").target("Hey").build()); + + Glossary glossar = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entryList(entryList) + .build(); + + assertEquals(entryList, glossar.getEntryList(), "unexpected entryList"); + } + + @Test + public void testNullEntryList() { + assertThrows( + NullPointerException.class, + () -> { + Glossary.builder().entryList((List) null); + }); + } + + @Test + public void testNullEntryInList() { + assertThrows( + NullPointerException.class, + () -> { + Glossary.builder().entryList(Arrays.asList((GlossaryEntry) null)); + }); + } + + @Test + public void testNullEntryArray() { + assertThrows( + NullPointerException.class, + () -> { + Glossary.builder().entryList((GlossaryEntry[]) null); + }); + } + + @Test + public void testNullEntry() { + assertThrows( + NullPointerException.class, + () -> { + Glossary.builder().entry(null); + }); + } + + @Test + public void testToBuilder() { + + Glossary glossary = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(GlossaryEntry.builder().source("Hallo").target("Hey").build()) + .build(); + + Glossary copy = glossary.toBuilder().build(); + + Glossary expected = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(GlossaryEntry.builder().source("Hallo").target("Hey").build()) + .build(); + + assertEquals(expected, copy, "unexpected glossary"); + } } diff --git a/src/test/java/com/sitepark/translate/LanguageTest.java b/src/test/java/com/sitepark/translate/LanguageTest.java index a053f01..0841742 100644 --- a/src/test/java/com/sitepark/translate/LanguageTest.java +++ b/src/test/java/com/sitepark/translate/LanguageTest.java @@ -3,145 +3,144 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Arrays; import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; - import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class LanguageTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - public void testEqualsContract() { - EqualsVerifier.forClass(Language.class).verify(); - } - - @Test - @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") - void testDeserialize() throws Exception { - String json = "{\"code\":\"de\", \"name\":\"deutsch\",\"targets\":[\"en\",\"it\"]}"; - ObjectMapper mapper = new ObjectMapper(); - Language language = mapper.readValue(json, Language.class); - assertEquals("de", language.getCode(), "wrong code"); - assertEquals("deutsch", language.getName(), "wrong name"); - assertEquals(Arrays.asList(new String[] {"en", "it"}), language.getTargets(), "wrong name"); - } - - @Test - void testBuilder() { - Language language = Language.builder() - .code("de") - .name("deutsch") - .targets(Arrays.asList(new String[] {"en", "fr"})) - .targets("it") - .build(); - assertEquals("de", language.getCode(), "unexpected code"); - assertEquals("deutsch", language.getName(), "unexpected name"); - assertEquals( - Arrays.asList(new String[] { - "en", - "fr", - "it" - }), - language.getTargets(), - "unexpected targets"); - } - - @Test - void testToBuilder() { - Language language = Language.builder() - .code("de") - .name("deutsch") - .targets(Arrays.asList(new String[] {"en", "fr"})) - .targets("it") - .build(); - language = language.toBuilder() - .code("es") - .name("espanol") - .build(); - assertEquals("es", language.getCode(), "unexpected code"); - assertEquals("espanol", language.getName(), "unexpected name"); - assertEquals( - Arrays.asList(new String[] { - "en", - "fr", - "it" - }), - language.getTargets(), - "unexpected targets"); - } - - @Test - void testSetCodeToNull() { - assertThrows(NullPointerException.class, () -> { - Language.builder().code(null); - }, "code null should not allowed"); - } - - @Test - void testMissingCode() { - assertThrows(IllegalStateException.class, () -> { - Language.builder() - .name("deutsch") - .targets("it") - .build(); - }, "source null should not allowed"); - } - - @Test - void testSetNameToNull() { - assertThrows(NullPointerException.class, () -> { - Language.builder().name(null); - }, "name null should not allowed"); - } - - @Test - void testMissingName() { - assertThrows(IllegalStateException.class, () -> { - Language.builder() - .code("de") - .targets("it") - .build(); - }, "source null should not allowed"); - } - - @Test - void testSetTargetsToNull() { - assertThrows(NullPointerException.class, () -> { - Language.builder().targets((String)null); - }, "targets null should not allowed"); - } - - @Test - void testSetTargetsArrayToNull() { - assertThrows(NullPointerException.class, () -> { - Language.builder().targets((String[])null); - }, "targets null should not allowed"); - } - - @Test - void testSetTargetsListToNull() { - assertThrows(NullPointerException.class, () -> { - Language.builder().targets((List)null); - }, "targets null should not allowed"); - } - - @Test - void testMissingTargets() { - assertThrows(IllegalStateException.class, () -> { - Language.builder() - .code("de") - .name("deutsch") - .build(); - }, "empty targets should not allowed"); - } - + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + public void testEqualsContract() { + EqualsVerifier.forClass(Language.class).verify(); + } + + @Test + @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") + void testDeserialize() throws Exception { + String json = "{\"code\":\"de\", \"name\":\"deutsch\",\"targets\":[\"en\",\"it\"]}"; + ObjectMapper mapper = new ObjectMapper(); + Language language = mapper.readValue(json, Language.class); + assertEquals("de", language.getCode(), "wrong code"); + assertEquals("deutsch", language.getName(), "wrong name"); + assertEquals(Arrays.asList(new String[] {"en", "it"}), language.getTargets(), "wrong name"); + } + + @Test + void testBuilder() { + Language language = + Language.builder() + .code("de") + .name("deutsch") + .targets(Arrays.asList(new String[] {"en", "fr"})) + .targets("it") + .build(); + assertEquals("de", language.getCode(), "unexpected code"); + assertEquals("deutsch", language.getName(), "unexpected name"); + assertEquals( + Arrays.asList(new String[] {"en", "fr", "it"}), + language.getTargets(), + "unexpected targets"); + } + + @Test + void testToBuilder() { + Language language = + Language.builder() + .code("de") + .name("deutsch") + .targets(Arrays.asList(new String[] {"en", "fr"})) + .targets("it") + .build(); + language = language.toBuilder().code("es").name("espanol").build(); + assertEquals("es", language.getCode(), "unexpected code"); + assertEquals("espanol", language.getName(), "unexpected name"); + assertEquals( + Arrays.asList(new String[] {"en", "fr", "it"}), + language.getTargets(), + "unexpected targets"); + } + + @Test + void testSetCodeToNull() { + assertThrows( + NullPointerException.class, + () -> { + Language.builder().code(null); + }, + "code null should not allowed"); + } + + @Test + void testMissingCode() { + assertThrows( + IllegalStateException.class, + () -> { + Language.builder().name("deutsch").targets("it").build(); + }, + "source null should not allowed"); + } + + @Test + void testSetNameToNull() { + assertThrows( + NullPointerException.class, + () -> { + Language.builder().name(null); + }, + "name null should not allowed"); + } + + @Test + void testMissingName() { + assertThrows( + IllegalStateException.class, + () -> { + Language.builder().code("de").targets("it").build(); + }, + "source null should not allowed"); + } + + @Test + void testSetTargetsToNull() { + assertThrows( + NullPointerException.class, + () -> { + Language.builder().targets((String) null); + }, + "targets null should not allowed"); + } + + @Test + void testSetTargetsArrayToNull() { + assertThrows( + NullPointerException.class, + () -> { + Language.builder().targets((String[]) null); + }, + "targets null should not allowed"); + } + + @Test + void testSetTargetsListToNull() { + assertThrows( + NullPointerException.class, + () -> { + Language.builder().targets((List) null); + }, + "targets null should not allowed"); + } + + @Test + void testMissingTargets() { + assertThrows( + IllegalStateException.class, + () -> { + Language.builder().code("de").name("deutsch").build(); + }, + "empty targets should not allowed"); + } } diff --git a/src/test/java/com/sitepark/translate/SupportedLanguagesTest.java b/src/test/java/com/sitepark/translate/SupportedLanguagesTest.java index 8e7e218..e844fb1 100644 --- a/src/test/java/com/sitepark/translate/SupportedLanguagesTest.java +++ b/src/test/java/com/sitepark/translate/SupportedLanguagesTest.java @@ -5,162 +5,107 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.Arrays; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Arrays; +import java.util.Optional; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class SupportedLanguagesTest { - @Test - void testBuilder() { - - Language de = Language.builder() - .code("de") - .name("deutsch") - .targets("en", "fr") - .build(); - - Language en = Language.builder() - .code("en") - .name("engish") - .targets("de", "fr") - .build(); - - SupportedLanguages supportedLanguages = SupportedLanguages.builder() - .language(de) - .language(en.toBuilder()) - .build(); - - assertEquals( - Arrays.asList(de, en), - supportedLanguages.getAll(), - "unexpected supported languages"); - assertSame( - de, - supportedLanguages.getSourceLanguage("de").get(), - "unexpected source language"); - assertEquals( - en, - supportedLanguages.getTargetLanguage("de", "en").get(), - "unexpected target language"); - - } - - @Test - void testToBuilder() { - - Language de = Language.builder() - .code("de") - .name("deutsch") - .targets("en", "fr") - .build(); - - Language en = Language.builder() - .code("en") - .name("engish") - .targets("de", "fr") - .build(); - - SupportedLanguages supportedLanguages = SupportedLanguages.builder() - .language(de) - .build(); - - supportedLanguages = supportedLanguages.toBuilder() - .language(en) - .build(); - - assertSame( - de, - supportedLanguages.getSourceLanguage("de").get(), - "unexprected source language"); - assertSame( - en, - supportedLanguages.getSourceLanguage("en").get(), - "unexprected source language"); - } - - @Test - void testSetLanguageToNull() { - assertThrows(NullPointerException.class, () -> { - SupportedLanguages.builder().language((Language)null); - }); - } - - @Test - void testSetLanguageBuilderToNull() { - assertThrows(NullPointerException.class, () -> { - SupportedLanguages.builder().language((Language.Builder)null); - }); - } - - @Test - void testReturnMissingSourceLanguage() { - - SupportedLanguages supportedLanguages = SupportedLanguages.builder() - .build(); - - assertEquals( - Optional.empty(), - supportedLanguages.getSourceLanguage("de"), - "source languge 'de' should not be found"); - } - - @Test - void testReturnMissingTargetLanguage() { - - Language de = Language.builder() - .code("de") - .name("deutsch") - .targets("en", "fr") - .build(); - - Language en = Language.builder() - .code("en") - .name("engish") - .targets("de", "fr") - .build(); - - SupportedLanguages supportedLanguages = SupportedLanguages.builder() - .language(de) - .language(en) - .build(); - - assertEquals( - Optional.empty(), - supportedLanguages.getTargetLanguage("de", "it"), - "target language 'it' should not be found"); - assertEquals( - Optional.empty(), - supportedLanguages.getTargetLanguage("fr", "de"), - "source language 'fr' should not be found"); - } - - @Test - void testDeserialze() throws JsonMappingException, JsonProcessingException { - - String json = "[{" + - "\"code\":\"de\"," + - "\"name\":\"deutsch\"," + - "\"targets\":[\"en\"]" + - "}]"; - - ObjectMapper objectMapper = new ObjectMapper(); - SupportedLanguages supportedLanguages = - objectMapper.readValue(json, SupportedLanguages.class); - - assertTrue( - supportedLanguages.getSourceLanguage("de").isPresent(), - "language 'de' should be present" - ); - } + @Test + void testBuilder() { + + Language de = Language.builder().code("de").name("deutsch").targets("en", "fr").build(); + + Language en = Language.builder().code("en").name("engish").targets("de", "fr").build(); + + SupportedLanguages supportedLanguages = + SupportedLanguages.builder().language(de).language(en.toBuilder()).build(); + + assertEquals( + Arrays.asList(de, en), supportedLanguages.getAll(), "unexpected supported languages"); + assertSame(de, supportedLanguages.getSourceLanguage("de").get(), "unexpected source language"); + assertEquals( + en, supportedLanguages.getTargetLanguage("de", "en").get(), "unexpected target language"); + } + + @Test + void testToBuilder() { + + Language de = Language.builder().code("de").name("deutsch").targets("en", "fr").build(); + + Language en = Language.builder().code("en").name("engish").targets("de", "fr").build(); + + SupportedLanguages supportedLanguages = SupportedLanguages.builder().language(de).build(); + + supportedLanguages = supportedLanguages.toBuilder().language(en).build(); + + assertSame(de, supportedLanguages.getSourceLanguage("de").get(), "unexprected source language"); + assertSame(en, supportedLanguages.getSourceLanguage("en").get(), "unexprected source language"); + } + + @Test + void testSetLanguageToNull() { + assertThrows( + NullPointerException.class, + () -> { + SupportedLanguages.builder().language((Language) null); + }); + } + + @Test + void testSetLanguageBuilderToNull() { + assertThrows( + NullPointerException.class, + () -> { + SupportedLanguages.builder().language((Language.Builder) null); + }); + } + + @Test + void testReturnMissingSourceLanguage() { + + SupportedLanguages supportedLanguages = SupportedLanguages.builder().build(); + + assertEquals( + Optional.empty(), + supportedLanguages.getSourceLanguage("de"), + "source languge 'de' should not be found"); + } + + @Test + void testReturnMissingTargetLanguage() { + + Language de = Language.builder().code("de").name("deutsch").targets("en", "fr").build(); + + Language en = Language.builder().code("en").name("engish").targets("de", "fr").build(); + + SupportedLanguages supportedLanguages = + SupportedLanguages.builder().language(de).language(en).build(); + + assertEquals( + Optional.empty(), + supportedLanguages.getTargetLanguage("de", "it"), + "target language 'it' should not be found"); + assertEquals( + Optional.empty(), + supportedLanguages.getTargetLanguage("fr", "de"), + "source language 'fr' should not be found"); + } + + @Test + void testDeserialze() throws JsonMappingException, JsonProcessingException { + + String json = + "[{" + "\"code\":\"de\"," + "\"name\":\"deutsch\"," + "\"targets\":[\"en\"]" + "}]"; + + ObjectMapper objectMapper = new ObjectMapper(); + SupportedLanguages supportedLanguages = objectMapper.readValue(json, SupportedLanguages.class); + assertTrue( + supportedLanguages.getSourceLanguage("de").isPresent(), "language 'de' should be present"); + } } diff --git a/src/test/java/com/sitepark/translate/SupportedProviderTest.java b/src/test/java/com/sitepark/translate/SupportedProviderTest.java index 853ef69..58cbf6d 100644 --- a/src/test/java/com/sitepark/translate/SupportedProviderTest.java +++ b/src/test/java/com/sitepark/translate/SupportedProviderTest.java @@ -8,36 +8,36 @@ class SupportedProviderTest { - @Test - void testOfSchemeDeepl() { - SupportedProvider supportedProvider = SupportedProvider.ofScheme("deepl"); - assertEquals( - SupportedProvider.DEEPL, - supportedProvider, - SupportedProvider.DEEPL + " expected"); - } + @Test + void testOfSchemeDeepl() { + SupportedProvider supportedProvider = SupportedProvider.ofScheme("deepl"); + assertEquals(SupportedProvider.DEEPL, supportedProvider, SupportedProvider.DEEPL + " expected"); + } - @Test - void testOfSchemeLibretranslate() { - SupportedProvider supportedProvider = SupportedProvider.ofScheme("libretranslate"); - assertEquals( - SupportedProvider.LIBRE_TRANSLATE, - supportedProvider, - SupportedProvider.LIBRE_TRANSLATE + " expected"); - } + @Test + void testOfSchemeLibretranslate() { + SupportedProvider supportedProvider = SupportedProvider.ofScheme("libretranslate"); + assertEquals( + SupportedProvider.LIBRE_TRANSLATE, + supportedProvider, + SupportedProvider.LIBRE_TRANSLATE + " expected"); + } - @Test - void testOfSchemeInvalidValue() { - assertThrows(IllegalArgumentException.class, () -> { - SupportedProvider.ofScheme("abc"); - }, "should throw an exception"); - } + @Test + void testOfSchemeInvalidValue() { + assertThrows( + IllegalArgumentException.class, + () -> { + SupportedProvider.ofScheme("abc"); + }, + "should throw an exception"); + } - @Test - void testSchemes() { - assertArrayEquals( - new String[] {"deepl", "libretranslate"}, - SupportedProvider.scheme(), - "unexpected scheme list"); - } -} \ No newline at end of file + @Test + void testSchemes() { + assertArrayEquals( + new String[] {"deepl", "libretranslate"}, + SupportedProvider.scheme(), + "unexpected scheme list"); + } +} diff --git a/src/test/java/com/sitepark/translate/TranslationEventTest.java b/src/test/java/com/sitepark/translate/TranslationEventTest.java index fc79987..90b3feb 100644 --- a/src/test/java/com/sitepark/translate/TranslationEventTest.java +++ b/src/test/java/com/sitepark/translate/TranslationEventTest.java @@ -6,45 +6,48 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts"}) class TranslationEventTest { - @Test - void testBuilder() { - TranslationLanguage language = Mockito.mock(TranslationLanguage.class); - TranslationEvent event = TranslationEvent.builder() - .translationLanguage(language) - .translationTime(123) - .chunks(12) - .sourceBytes(345) - .targetBytes(346) - .build(); + @Test + void testBuilder() { + TranslationLanguage language = Mockito.mock(TranslationLanguage.class); + TranslationEvent event = + TranslationEvent.builder() + .translationLanguage(language) + .translationTime(123) + .chunks(12) + .sourceBytes(345) + .targetBytes(346) + .build(); - assertEquals(language, event.getTranslationLanguage(), "unexpected translationLanguage"); - assertEquals(123, event.getTranslationTime(), "unexpected translationTime"); - assertEquals(12, event.getChunks(), "unexpected chunks"); - assertEquals(345, event.getSourceBytes(), "unexpected sourceBytes"); - assertEquals(346, event.getTargetBytes(), "unexpected targetBytes"); - } + assertEquals(language, event.getTranslationLanguage(), "unexpected translationLanguage"); + assertEquals(123, event.getTranslationTime(), "unexpected translationTime"); + assertEquals(12, event.getChunks(), "unexpected chunks"); + assertEquals(345, event.getSourceBytes(), "unexpected sourceBytes"); + assertEquals(346, event.getTargetBytes(), "unexpected targetBytes"); + } - @Test - void testSetTranslationLanguageToNull() { - assertThrows(NullPointerException.class, () -> { - TranslationEvent.builder().translationLanguage(null); - }); - } + @Test + void testSetTranslationLanguageToNull() { + assertThrows( + NullPointerException.class, + () -> { + TranslationEvent.builder().translationLanguage(null); + }); + } - @Test - void testMissingTranslationLanguage() { - assertThrows(IllegalStateException.class, () -> { - TranslationEvent.builder() - .translationTime(123) - .chunks(12) - .sourceBytes(345) - .targetBytes(346) - .build(); - }); - } + @Test + void testMissingTranslationLanguage() { + assertThrows( + IllegalStateException.class, + () -> { + TranslationEvent.builder() + .translationTime(123) + .chunks(12) + .sourceBytes(345) + .targetBytes(346) + .build(); + }); + } } diff --git a/src/test/java/com/sitepark/translate/TranslationLanguageTest.java b/src/test/java/com/sitepark/translate/TranslationLanguageTest.java index 4cc459e..74c0313 100644 --- a/src/test/java/com/sitepark/translate/TranslationLanguageTest.java +++ b/src/test/java/com/sitepark/translate/TranslationLanguageTest.java @@ -3,77 +3,74 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class TranslationLanguageTest { - @Test - @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") - public void testEqualsContract() { - EqualsVerifier.forClass(TranslationLanguage.class).verify(); - } - - @Test - void testBuilder() { - TranslationLanguage language = TranslationLanguage.builder() - .source("de_DE") - .target("en_US") - .build(); - assertEquals("de_DE", language.getSource(), "unexpected source"); - assertEquals("en_US", language.getTarget(), "unexpected target"); - } + @Test + @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") + public void testEqualsContract() { + EqualsVerifier.forClass(TranslationLanguage.class).verify(); + } - @Test - void testSetNullSource() { - assertThrows(NullPointerException.class, () -> { - TranslationLanguage.builder().source(null); - }, "source null should not allowed"); - } + @Test + void testBuilder() { + TranslationLanguage language = + TranslationLanguage.builder().source("de_DE").target("en_US").build(); + assertEquals("de_DE", language.getSource(), "unexpected source"); + assertEquals("en_US", language.getTarget(), "unexpected target"); + } - @Test - void testMissingSource() { - assertThrows(IllegalStateException.class, () -> { - TranslationLanguage.builder() - .target("en_US") - .build(); - }, "source null should not allowed"); - } + @Test + void testSetNullSource() { + assertThrows( + NullPointerException.class, + () -> { + TranslationLanguage.builder().source(null); + }, + "source null should not allowed"); + } - @Test - void testSetNullTarget() { - assertThrows(NullPointerException.class, () -> { - TranslationLanguage.builder().target(null); - }, "target null should not allowed"); - } + @Test + void testMissingSource() { + assertThrows( + IllegalStateException.class, + () -> { + TranslationLanguage.builder().target("en_US").build(); + }, + "source null should not allowed"); + } - @Test - void testMissingTarget() { - assertThrows(IllegalStateException.class, () -> { - TranslationLanguage.builder() - .source("de_DE") - .build(); - }, "target null should not allowed"); - } + @Test + void testSetNullTarget() { + assertThrows( + NullPointerException.class, + () -> { + TranslationLanguage.builder().target(null); + }, + "target null should not allowed"); + } - @Test - void testToBuilder() { - TranslationLanguage language = TranslationLanguage.builder() - .source("de_DE") - .target("en_US") - .build(); + @Test + void testMissingTarget() { + assertThrows( + IllegalStateException.class, + () -> { + TranslationLanguage.builder().source("de_DE").build(); + }, + "target null should not allowed"); + } - language = language.toBuilder() - .source("fr_FR") - .build(); + @Test + void testToBuilder() { + TranslationLanguage language = + TranslationLanguage.builder().source("de_DE").target("en_US").build(); - assertEquals("fr_FR", language.getSource(), "unexpected source"); - assertEquals("en_US", language.getTarget(), "unexpected target"); - } + language = language.toBuilder().source("fr_FR").build(); + assertEquals("fr_FR", language.getSource(), "unexpected source"); + assertEquals("en_US", language.getTarget(), "unexpected target"); + } } diff --git a/src/test/java/com/sitepark/translate/TranslationProviderConfigurationTest.java b/src/test/java/com/sitepark/translate/TranslationProviderConfigurationTest.java index e2d9aaf..21dec58 100644 --- a/src/test/java/com/sitepark/translate/TranslationProviderConfigurationTest.java +++ b/src/test/java/com/sitepark/translate/TranslationProviderConfigurationTest.java @@ -10,137 +10,128 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts"}) class TranslationProviderConfigurationTest { - @Test - void testBuilder() { - - TranslationCache translationCache = - Mockito.mock(TranslationCache.class); - TranslationProviderFactory translationProviderFactory = - Mockito.mock(TranslationProviderFactory.class); - TranslationProviderConfiguration translationProviderConfiguration = - Mockito.mock(TranslationProviderConfiguration.class); - when(translationProviderConfiguration.getType()).thenReturn(SupportedProvider.DEEPL); - - TranslationConfiguration config = TranslationConfiguration.builder() - .translationCache(translationCache) - .translationProviderConfiguration(translationProviderConfiguration) - .translationProviderFactory(translationProviderFactory) - .encodePlaceholder(true) - .build(); - - assertSame( - translationCache, - config.getTranslationCache().get(), - "unexpected translationCache"); - assertSame( - translationProviderFactory, - config.getTranslationProviderFactory(), - "unexpected translationProviderFactory"); - assertArrayEquals( - new SupportedProvider[] {translationProviderConfiguration.getType()}, - config.getConfiguredProvider(), - "unexpected translationProviderConfiguration"); - assertEquals( - true, - config.isEncodePlaceholder(), - "unexpected encodePlaceholder"); - } - - @Test - void testGetTranslationProviderConfiguration() { - - TranslationConfiguration config = TranslationConfiguration.builder() - .translationProviderConfiguration(new TranslationProviderConfigurationDummy()) - .build(); - - TranslationProviderConfigurationDummy testProviderConfiguration = - config.getTranslationProviderConfiguration(TranslationProviderConfigurationDummy.class); - - assertNotNull( - testProviderConfiguration, - "expect non null providerConfiguration"); - } - - @Test - void testMissingTranslationProviderConfiguration() { - - TranslationConfiguration config = TranslationConfiguration.builder() - .build(); - - assertThrows(IllegalArgumentException.class, () -> { - config.getTranslationProviderConfiguration(TranslationProviderConfigurationDummy.class); - }); - } - - @Test - void testToBuilder() { - - TranslationCache translationCache = - Mockito.mock(TranslationCache.class); - TranslationProviderFactory translationProviderFactory = - Mockito.mock(TranslationProviderFactory.class); - TranslationProviderConfiguration translationProviderConfiguration = - Mockito.mock(TranslationProviderConfiguration.class); - when(translationProviderConfiguration.getType()).thenReturn(SupportedProvider.DEEPL); - - TranslationConfiguration config = TranslationConfiguration.builder() - .translationCache(translationCache) - .translationProviderConfiguration(translationProviderConfiguration) - .translationProviderFactory(translationProviderFactory) - .encodePlaceholder(true) - .build(); - - assertSame( - translationCache, - config.getTranslationCache().get(), - "unexpected translationCache"); - assertSame( - translationProviderFactory, - config.getTranslationProviderFactory(), - "unexpected translationProviderFactory"); - assertArrayEquals( - new SupportedProvider[] {translationProviderConfiguration.getType()}, - config.getConfiguredProvider(), - "unexpected translationProviderConfiguration"); - assertEquals( - true, - config.isEncodePlaceholder(), - "unexpected encodePlaceholder"); - } - - @Test - void testSetTranslationCacheToNull() { - assertThrows(NullPointerException.class, () -> { - TranslationConfiguration.builder().translationCache(null); - }); - } - - @Test - void testSetTranslationProviderFactoryToNull() { - assertThrows(NullPointerException.class, () -> { - TranslationConfiguration.builder().translationProviderFactory(null); - }); - } - - @Test - void testSetTranslationProviderConfigurationToNull() { - assertThrows(NullPointerException.class, () -> { - TranslationConfiguration.builder().translationProviderConfiguration(null); - }); - } - - private static final class TranslationProviderConfigurationDummy - implements TranslationProviderConfiguration { - - @Override - public SupportedProvider getType() { - return SupportedProvider.DEEPL; - } - - } + @Test + void testBuilder() { + + TranslationCache translationCache = Mockito.mock(TranslationCache.class); + TranslationProviderFactory translationProviderFactory = + Mockito.mock(TranslationProviderFactory.class); + TranslationProviderConfiguration translationProviderConfiguration = + Mockito.mock(TranslationProviderConfiguration.class); + when(translationProviderConfiguration.getType()).thenReturn(SupportedProvider.DEEPL); + + TranslationConfiguration config = + TranslationConfiguration.builder() + .translationCache(translationCache) + .translationProviderConfiguration(translationProviderConfiguration) + .translationProviderFactory(translationProviderFactory) + .encodePlaceholder(true) + .build(); + + assertSame(translationCache, config.getTranslationCache().get(), "unexpected translationCache"); + assertSame( + translationProviderFactory, + config.getTranslationProviderFactory(), + "unexpected translationProviderFactory"); + assertArrayEquals( + new SupportedProvider[] {translationProviderConfiguration.getType()}, + config.getConfiguredProvider(), + "unexpected translationProviderConfiguration"); + assertEquals(true, config.isEncodePlaceholder(), "unexpected encodePlaceholder"); + } + + @Test + void testGetTranslationProviderConfiguration() { + + TranslationConfiguration config = + TranslationConfiguration.builder() + .translationProviderConfiguration(new TranslationProviderConfigurationDummy()) + .build(); + + TranslationProviderConfigurationDummy testProviderConfiguration = + config.getTranslationProviderConfiguration(TranslationProviderConfigurationDummy.class); + + assertNotNull(testProviderConfiguration, "expect non null providerConfiguration"); + } + + @Test + void testMissingTranslationProviderConfiguration() { + + TranslationConfiguration config = TranslationConfiguration.builder().build(); + + assertThrows( + IllegalArgumentException.class, + () -> { + config.getTranslationProviderConfiguration(TranslationProviderConfigurationDummy.class); + }); + } + + @Test + void testToBuilder() { + + TranslationCache translationCache = Mockito.mock(TranslationCache.class); + TranslationProviderFactory translationProviderFactory = + Mockito.mock(TranslationProviderFactory.class); + TranslationProviderConfiguration translationProviderConfiguration = + Mockito.mock(TranslationProviderConfiguration.class); + when(translationProviderConfiguration.getType()).thenReturn(SupportedProvider.DEEPL); + + TranslationConfiguration config = + TranslationConfiguration.builder() + .translationCache(translationCache) + .translationProviderConfiguration(translationProviderConfiguration) + .translationProviderFactory(translationProviderFactory) + .encodePlaceholder(true) + .build(); + + assertSame(translationCache, config.getTranslationCache().get(), "unexpected translationCache"); + assertSame( + translationProviderFactory, + config.getTranslationProviderFactory(), + "unexpected translationProviderFactory"); + assertArrayEquals( + new SupportedProvider[] {translationProviderConfiguration.getType()}, + config.getConfiguredProvider(), + "unexpected translationProviderConfiguration"); + assertEquals(true, config.isEncodePlaceholder(), "unexpected encodePlaceholder"); + } + + @Test + void testSetTranslationCacheToNull() { + assertThrows( + NullPointerException.class, + () -> { + TranslationConfiguration.builder().translationCache(null); + }); + } + + @Test + void testSetTranslationProviderFactoryToNull() { + assertThrows( + NullPointerException.class, + () -> { + TranslationConfiguration.builder().translationProviderFactory(null); + }); + } + + @Test + void testSetTranslationProviderConfigurationToNull() { + assertThrows( + NullPointerException.class, + () -> { + TranslationConfiguration.builder().translationProviderConfiguration(null); + }); + } + + private static final class TranslationProviderConfigurationDummy + implements TranslationProviderConfiguration { + + @Override + public SupportedProvider getType() { + return SupportedProvider.DEEPL; + } + } } diff --git a/src/test/java/com/sitepark/translate/TranslationProviderExceptionTest.java b/src/test/java/com/sitepark/translate/TranslationProviderExceptionTest.java index c777722..973bed4 100644 --- a/src/test/java/com/sitepark/translate/TranslationProviderExceptionTest.java +++ b/src/test/java/com/sitepark/translate/TranslationProviderExceptionTest.java @@ -6,20 +6,20 @@ import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts"}) class TranslationProviderExceptionTest { - @Test - void test() { - Exception cause = new Exception(); - Exception exception = assertThrows(TranslationProviderException.class, () -> { - throw new TranslationProviderException("test", cause); - }); - - assertSame(cause, exception.getCause(), "same cause exception expected"); - assertEquals(exception.getMessage(), "test", "'test' message expected"); - } + @Test + void test() { + Exception cause = new Exception(); + Exception exception = + assertThrows( + TranslationProviderException.class, + () -> { + throw new TranslationProviderException("test", cause); + }); + assertSame(cause, exception.getCause(), "same cause exception expected"); + assertEquals(exception.getMessage(), "test", "'test' message expected"); + } } diff --git a/src/test/java/com/sitepark/translate/TranslationProviderFactoryTest.java b/src/test/java/com/sitepark/translate/TranslationProviderFactoryTest.java index 35e0474..5136ab8 100644 --- a/src/test/java/com/sitepark/translate/TranslationProviderFactoryTest.java +++ b/src/test/java/com/sitepark/translate/TranslationProviderFactoryTest.java @@ -1,43 +1,47 @@ package com.sitepark.translate; - import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import com.sitepark.translate.provider.deepl.DeeplTranslationProvider; import com.sitepark.translate.provider.libretranslate.LibreTranslateTranslationProvider; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; class TranslationProviderFactoryTest { - @Test - void testCreateLibreTranslateTranslationProvider() { - - TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); - TranslationProviderFactory factory = new TranslationProviderFactory(config); - TranslationProvider provider = factory.create(SupportedProvider.LIBRE_TRANSLATE); - assertThat("libretranslate provider expected", provider, instanceOf(LibreTranslateTranslationProvider.class)); - } - - @Test - void testCreateDeeplTranslationProvider() { - - TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); - TranslationProviderFactory factory = new TranslationProviderFactory(config); - TranslationProvider provider = factory.create(SupportedProvider.DEEPL); - assertThat("deepl provider expected", provider, instanceOf(DeeplTranslationProvider.class)); - } - - @Test - void testInvalidTranslationProvider() { - - TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); - TranslationProviderFactory factory = new TranslationProviderFactory(config); - assertThrows(IllegalArgumentException.class, () -> { - factory.create(null); - }, "IllegalArgumentException expected"); - } + @Test + void testCreateLibreTranslateTranslationProvider() { + + TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); + TranslationProviderFactory factory = new TranslationProviderFactory(config); + TranslationProvider provider = factory.create(SupportedProvider.LIBRE_TRANSLATE); + assertThat( + "libretranslate provider expected", + provider, + instanceOf(LibreTranslateTranslationProvider.class)); + } + + @Test + void testCreateDeeplTranslationProvider() { + + TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); + TranslationProviderFactory factory = new TranslationProviderFactory(config); + TranslationProvider provider = factory.create(SupportedProvider.DEEPL); + assertThat("deepl provider expected", provider, instanceOf(DeeplTranslationProvider.class)); + } + + @Test + void testInvalidTranslationProvider() { + + TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); + TranslationProviderFactory factory = new TranslationProviderFactory(config); + assertThrows( + IllegalArgumentException.class, + () -> { + factory.create(null); + }, + "IllegalArgumentException expected"); + } } diff --git a/src/test/java/com/sitepark/translate/cli/MainTest.java b/src/test/java/com/sitepark/translate/cli/MainTest.java index 3bbb8f0..574ff43 100644 --- a/src/test/java/com/sitepark/translate/cli/MainTest.java +++ b/src/test/java/com/sitepark/translate/cli/MainTest.java @@ -5,45 +5,44 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MainTest { - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - private static final PrintStream ORIGINAL_OUT = System.out; - private static final PrintStream ORIGINAL_ERR = System.err; - - @BeforeEach - public void setUpStreams() { - System.setOut(new PrintStream(outContent, true, StandardCharsets.UTF_8)); - System.setErr(new PrintStream(errContent, true, StandardCharsets.UTF_8)); - } - - @AfterEach - public void restoreStreams() { - System.setOut(ORIGINAL_OUT); - System.setErr(ORIGINAL_ERR); - } - - @Test - void testMissingCommand() { - Main.main(); - assertEquals( - "missing command" + System.lineSeparator(), - this.outContent.toString(StandardCharsets.UTF_8), - "unexprected message"); - } - - @Test - void testUnknwonCommand() { - Main.main("test"); - assertEquals( - "unknown command: test" + System.lineSeparator(), - this.errContent.toString(StandardCharsets.UTF_8), - "unexprected message"); - } + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + private static final PrintStream ORIGINAL_OUT = System.out; + private static final PrintStream ORIGINAL_ERR = System.err; + + @BeforeEach + public void setUpStreams() { + System.setOut(new PrintStream(outContent, true, StandardCharsets.UTF_8)); + System.setErr(new PrintStream(errContent, true, StandardCharsets.UTF_8)); + } + + @AfterEach + public void restoreStreams() { + System.setOut(ORIGINAL_OUT); + System.setErr(ORIGINAL_ERR); + } + + @Test + void testMissingCommand() { + Main.main(); + assertEquals( + "missing command" + System.lineSeparator(), + this.outContent.toString(StandardCharsets.UTF_8), + "unexprected message"); + } + + @Test + void testUnknwonCommand() { + Main.main("test"); + assertEquals( + "unknown command: test" + System.lineSeparator(), + this.errContent.toString(StandardCharsets.UTF_8), + "unexprected message"); + } } diff --git a/src/test/java/com/sitepark/translate/cli/TranslateJsonTest.java b/src/test/java/com/sitepark/translate/cli/TranslateJsonTest.java index ee1eb0d..7f927c9 100644 --- a/src/test/java/com/sitepark/translate/cli/TranslateJsonTest.java +++ b/src/test/java/com/sitepark/translate/cli/TranslateJsonTest.java @@ -6,28 +6,25 @@ class TranslateJsonTest { - @Test - void testParseArgumentsWithDeepl() { - TranslateJson translateJson = new TranslateJson(); - translateJson.parseArguments( - "deepl:https://dummy?authKey=abc", - "src/test/resources/translate-json", - "de", - "target/test/translate-json" - ); - assertNotNull(translateJson.getTranslator(), "translator expected"); - } - - @Test - void testParseArgumentsWithLibreTranslate() { - TranslateJson translateJson = new TranslateJson(); - translateJson.parseArguments( - "libretranslate:https://dummy?apiKey=abc", - "src/test/resources/translate-json", - "de", - "target/test/translate-json" - ); - assertNotNull(translateJson.getTranslator(), "translator expected"); - } + @Test + void testParseArgumentsWithDeepl() { + TranslateJson translateJson = new TranslateJson(); + translateJson.parseArguments( + "deepl:https://dummy?authKey=abc", + "src/test/resources/translate-json", + "de", + "target/test/translate-json"); + assertNotNull(translateJson.getTranslator(), "translator expected"); + } + @Test + void testParseArgumentsWithLibreTranslate() { + TranslateJson translateJson = new TranslateJson(); + translateJson.parseArguments( + "libretranslate:https://dummy?apiKey=abc", + "src/test/resources/translate-json", + "de", + "target/test/translate-json"); + assertNotNull(translateJson.getTranslator(), "translator expected"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfigurationTest.java b/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfigurationTest.java index bd65d23..e38c433 100644 --- a/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfigurationTest.java +++ b/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderConfigurationTest.java @@ -4,146 +4,160 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.sitepark.translate.SupportedProvider; import java.net.InetSocketAddress; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; - import org.junit.jupiter.api.Test; -import com.sitepark.translate.SupportedProvider; - -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class DeeplTranslationProviderConfigurationTest { - @Test - void testBuilder() throws URISyntaxException { - - DeeplTranslationProviderConfiguration providerConfig = DeeplTranslationProviderConfiguration.builder() - .url("https://test") - .authKey("abc") - .proxy("sitepark.com", 8080) - .build(); - - assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); - assertEquals("abc", providerConfig.getAuthKey(), "unexpected authKey"); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testToBuilder() throws URISyntaxException { - - DeeplTranslationProviderConfiguration providerConfig = DeeplTranslationProviderConfiguration.builder() - .url("https://test") - .authKey("abc") - .proxy("sitepark.com", 8080) - .build(); - - providerConfig = providerConfig.toBuilder() - .authKey("cde") - .build(); - - assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); - assertEquals("cde", providerConfig.getAuthKey(), "unexpected authKey"); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testBuilderWithProxySelector() throws URISyntaxException { - - DeeplTranslationProviderConfiguration providerConfig = DeeplTranslationProviderConfiguration.builder() - .url("https://test") - .authKey("abc") - .proxy(ProxySelector.of(new InetSocketAddress("sitepark.com", 8080))) - .build(); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testBuilderWithProxyInetSocketAddress() throws URISyntaxException { - - DeeplTranslationProviderConfiguration providerConfig = DeeplTranslationProviderConfiguration.builder() - .url("https://test") - .authKey("abc") - .proxy(new InetSocketAddress("sitepark.com", 8080)) - .build(); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testSetUrlToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - DeeplTranslationProviderConfiguration.builder().url(null); - }); - } - - @Test - void testSetAuthKeyToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - DeeplTranslationProviderConfiguration.builder().authKey(null); - }); - } - - @Test - void testSetProxyHostToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - DeeplTranslationProviderConfiguration.builder().proxy(null, 8080); - }); - } - - @Test - void testSetProxyPortToZero() throws URISyntaxException { - assertThrows(IllegalArgumentException.class, () -> { - DeeplTranslationProviderConfiguration.builder().proxy("test.de", 0); - }); - } - - @Test - void testSetProxySelectorToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - DeeplTranslationProviderConfiguration.builder().proxy((ProxySelector)null); - }); - } - - @Test - void testSetProxyInetSocketAddressToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - DeeplTranslationProviderConfiguration.builder().proxy((InetSocketAddress)null); - }); - } - - @Test - void testMissingUri() throws URISyntaxException { - assertThrows(IllegalStateException.class, () -> { - DeeplTranslationProviderConfiguration.builder() - .authKey("abc") - .proxy("sitepark.com", 8080) - .build(); - }); - } - - @Test - void testMissingAuthKey() throws URISyntaxException { - assertThrows(IllegalStateException.class, () -> { - DeeplTranslationProviderConfiguration.builder() - .url("https://test") - .proxy("sitepark.com", 8080) - .build(); - }); - } - - @Test - void tetGetType() throws URISyntaxException { - - DeeplTranslationProviderConfiguration providerConfig = DeeplTranslationProviderConfiguration.builder() - .url("https://test") - .authKey("abc") - .proxy("sitepark.com", 8080) - .build(); - - assertEquals(SupportedProvider.DEEPL, providerConfig.getType(), "unexpected type"); - } + @Test + void testBuilder() throws URISyntaxException { + + DeeplTranslationProviderConfiguration providerConfig = + DeeplTranslationProviderConfiguration.builder() + .url("https://test") + .authKey("abc") + .proxy("sitepark.com", 8080) + .build(); + + assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); + assertEquals("abc", providerConfig.getAuthKey(), "unexpected authKey"); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testToBuilder() throws URISyntaxException { + + DeeplTranslationProviderConfiguration providerConfig = + DeeplTranslationProviderConfiguration.builder() + .url("https://test") + .authKey("abc") + .proxy("sitepark.com", 8080) + .build(); + + providerConfig = providerConfig.toBuilder().authKey("cde").build(); + + assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); + assertEquals("cde", providerConfig.getAuthKey(), "unexpected authKey"); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testBuilderWithProxySelector() throws URISyntaxException { + + DeeplTranslationProviderConfiguration providerConfig = + DeeplTranslationProviderConfiguration.builder() + .url("https://test") + .authKey("abc") + .proxy(ProxySelector.of(new InetSocketAddress("sitepark.com", 8080))) + .build(); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testBuilderWithProxyInetSocketAddress() throws URISyntaxException { + + DeeplTranslationProviderConfiguration providerConfig = + DeeplTranslationProviderConfiguration.builder() + .url("https://test") + .authKey("abc") + .proxy(new InetSocketAddress("sitepark.com", 8080)) + .build(); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testSetUrlToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + DeeplTranslationProviderConfiguration.builder().url(null); + }); + } + + @Test + void testSetAuthKeyToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + DeeplTranslationProviderConfiguration.builder().authKey(null); + }); + } + + @Test + void testSetProxyHostToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + DeeplTranslationProviderConfiguration.builder().proxy(null, 8080); + }); + } + + @Test + void testSetProxyPortToZero() throws URISyntaxException { + assertThrows( + IllegalArgumentException.class, + () -> { + DeeplTranslationProviderConfiguration.builder().proxy("test.de", 0); + }); + } + + @Test + void testSetProxySelectorToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + DeeplTranslationProviderConfiguration.builder().proxy((ProxySelector) null); + }); + } + + @Test + void testSetProxyInetSocketAddressToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + DeeplTranslationProviderConfiguration.builder().proxy((InetSocketAddress) null); + }); + } + + @Test + void testMissingUri() throws URISyntaxException { + assertThrows( + IllegalStateException.class, + () -> { + DeeplTranslationProviderConfiguration.builder() + .authKey("abc") + .proxy("sitepark.com", 8080) + .build(); + }); + } + + @Test + void testMissingAuthKey() throws URISyntaxException { + assertThrows( + IllegalStateException.class, + () -> { + DeeplTranslationProviderConfiguration.builder() + .url("https://test") + .proxy("sitepark.com", 8080) + .build(); + }); + } + + @Test + void tetGetType() throws URISyntaxException { + + DeeplTranslationProviderConfiguration providerConfig = + DeeplTranslationProviderConfiguration.builder() + .url("https://test") + .authKey("abc") + .proxy("sitepark.com", 8080) + .build(); + + assertEquals(SupportedProvider.DEEPL, providerConfig.getType(), "unexpected type"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTest.java b/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTest.java index 6a17e6a..91c4c6b 100644 --- a/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTest.java +++ b/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTest.java @@ -3,13 +3,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; -import java.net.URISyntaxException; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import com.sitepark.translate.Format; import com.sitepark.translate.Glossary; import com.sitepark.translate.GlossaryEntry; @@ -20,166 +13,139 @@ import com.sitepark.translate.TranslationParameter; import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; - +import java.io.IOException; +import java.net.URISyntaxException; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.AvoidDuplicateLiterals", - "PMD.JUnitTestContainsTooManyAsserts" -}) +@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.JUnitTestContainsTooManyAsserts"}) class DeeplTranslationProviderTest { - private MockWebServer mockWebServer; - private DeeplTranslationProvider provider; - - private static final Dispatcher DISPATCHER = new DeeplTranslationProviderTestDispatcher(); - - @BeforeEach - void setUp() throws URISyntaxException { - this.mockWebServer = new MockWebServer(); - this.mockWebServer.setDispatcher(DISPATCHER); - String baseUrl = this.mockWebServer.url("").toString(); - if (baseUrl.endsWith("/")) { - baseUrl = baseUrl.substring(0, baseUrl.length() - 1); - } - DeeplTranslationProviderConfiguration providerConfig = DeeplTranslationProviderConfiguration.builder() - .url(baseUrl) - .authKey("test") - .build(); - - TranslationConfiguration config = TranslationConfiguration.builder() - .translationProviderConfiguration(providerConfig) - .build(); - - this.provider = new DeeplTranslationProvider(config); - } - - @AfterEach - void tearDown() throws IOException { - this.mockWebServer.shutdown(); - } - - @Test - void testTranslation() { - - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); - - TranslationRequest req = TranslationRequest.builder() - .parameter(TranslationParameter.builder() - .format(Format.TEXT) - .language(language) - .providerType(SupportedProvider.DEEPL) - .build() - ) - .sourceText("Hallo", "Welt") - .build(); - - TranslationResult translated = this.provider.translate(req); - - assertArrayEquals( - new String[] {"Hello", "World"}, - translated.getText(), - "unexpected translation"); - } - - @Test - void testGetSupportedLanguages() { - - SupportedLanguages supportedLanguages = this.provider.getSupportedLanguages(); - - assertEquals( - "de", - supportedLanguages.getSourceLanguage("de").get().getCode(), - "unexpected source language"); - assertEquals( - "en-us", - supportedLanguages.getTargetLanguage("de", "en-us").get().getCode(), - "unexpected source language"); - } - - @Test - void testGetGlossaryId() { - String id = this.provider.getGlossaryId("test:de/en").get(); - assertEquals("ee0c28af-e9cd-4b59-9199-f114ebc0d602", id, "unexpected glossary id"); - } - - @Test - void testGetGlossary() { - - Glossary glossary = this.provider.getGlossary("ee0c28af-e9cd-4b59-9199-f114ebc0d602").get(); - - Glossary expected = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Foo") - .target("Bar") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build() - ) - .build(); - - assertEquals(expected, glossary, "unexpected glossary"); - - } - - @Test - void testRemoveGlossary() throws Exception { - this.provider.removeGlossary("ee0c28af-e9cd-4b59-9199-f114ebc0d602"); - RecordedRequest req = mockWebServer.takeRequest(); - assertEquals("/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602", req.getPath(), "unexpected path"); - assertEquals("DELETE", req.getMethod(), "unexpected method"); - } - - @Test - void testRecreateGlossary() throws Exception { - Glossary glossary = Glossary.builder() - .name("test:de/en") - .language(TranslationLanguage.builder() - .source("de") - .target("en") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Foo") - .target("Bar") - .build() - ) - .entry(GlossaryEntry.builder() - .source("Hallo") - .target("Hey") - .build() - ) - .build(); - - String id = this.provider.recreate(glossary); - assertEquals("ee0c28af-e9cd-4b59-9199-f114ebc0d602", id, "unexpected glossary id"); - - RecordedRequest lastRequest = null; - for (int i = 0; i < this.mockWebServer.getRequestCount(); i++) { - lastRequest = this.mockWebServer.takeRequest(); - } - - String expected = "{\"name\":\"test:de/en\"," + - "\"entries\":\"Foo\\tBar\\nHallo\\tHey\\n\"," + - "\"source_lang\":\"de\"," + - "\"target_lang\":\"en\"," + - "\"entries_format\":\"tsv\"}"; - - assertEquals("POST", lastRequest.getMethod(), "unexpected request method"); - assertEquals(expected, lastRequest.getBody().readUtf8(), "unexpected request body"); - } + private MockWebServer mockWebServer; + private DeeplTranslationProvider provider; + + private static final Dispatcher DISPATCHER = new DeeplTranslationProviderTestDispatcher(); + + @BeforeEach + void setUp() throws URISyntaxException { + this.mockWebServer = new MockWebServer(); + this.mockWebServer.setDispatcher(DISPATCHER); + String baseUrl = this.mockWebServer.url("").toString(); + if (baseUrl.endsWith("/")) { + baseUrl = baseUrl.substring(0, baseUrl.length() - 1); + } + DeeplTranslationProviderConfiguration providerConfig = + DeeplTranslationProviderConfiguration.builder().url(baseUrl).authKey("test").build(); + + TranslationConfiguration config = + TranslationConfiguration.builder().translationProviderConfiguration(providerConfig).build(); + + this.provider = new DeeplTranslationProvider(config); + } + + @AfterEach + void tearDown() throws IOException { + this.mockWebServer.shutdown(); + } + + @Test + void testTranslation() { + + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); + + TranslationRequest req = + TranslationRequest.builder() + .parameter( + TranslationParameter.builder() + .format(Format.TEXT) + .language(language) + .providerType(SupportedProvider.DEEPL) + .build()) + .sourceText("Hallo", "Welt") + .build(); + + TranslationResult translated = this.provider.translate(req); + + assertArrayEquals( + new String[] {"Hello", "World"}, translated.getText(), "unexpected translation"); + } + + @Test + void testGetSupportedLanguages() { + + SupportedLanguages supportedLanguages = this.provider.getSupportedLanguages(); + + assertEquals( + "de", + supportedLanguages.getSourceLanguage("de").get().getCode(), + "unexpected source language"); + assertEquals( + "en-us", + supportedLanguages.getTargetLanguage("de", "en-us").get().getCode(), + "unexpected source language"); + } + + @Test + void testGetGlossaryId() { + String id = this.provider.getGlossaryId("test:de/en").get(); + assertEquals("ee0c28af-e9cd-4b59-9199-f114ebc0d602", id, "unexpected glossary id"); + } + + @Test + void testGetGlossary() { + + Glossary glossary = this.provider.getGlossary("ee0c28af-e9cd-4b59-9199-f114ebc0d602").get(); + + Glossary expected = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(GlossaryEntry.builder().source("Foo").target("Bar").build()) + .entry(GlossaryEntry.builder().source("Hallo").target("Hey").build()) + .build(); + + assertEquals(expected, glossary, "unexpected glossary"); + } + + @Test + void testRemoveGlossary() throws Exception { + this.provider.removeGlossary("ee0c28af-e9cd-4b59-9199-f114ebc0d602"); + RecordedRequest req = mockWebServer.takeRequest(); + assertEquals( + "/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602", req.getPath(), "unexpected path"); + assertEquals("DELETE", req.getMethod(), "unexpected method"); + } + + @Test + void testRecreateGlossary() throws Exception { + Glossary glossary = + Glossary.builder() + .name("test:de/en") + .language(TranslationLanguage.builder().source("de").target("en").build()) + .entry(GlossaryEntry.builder().source("Foo").target("Bar").build()) + .entry(GlossaryEntry.builder().source("Hallo").target("Hey").build()) + .build(); + + String id = this.provider.recreate(glossary); + assertEquals("ee0c28af-e9cd-4b59-9199-f114ebc0d602", id, "unexpected glossary id"); + + RecordedRequest lastRequest = null; + for (int i = 0; i < this.mockWebServer.getRequestCount(); i++) { + lastRequest = this.mockWebServer.takeRequest(); + } + + String expected = + "{\"name\":\"test:de/en\"," + + "\"entries\":\"Foo\\tBar\\nHallo\\tHey\\n\"," + + "\"source_lang\":\"de\"," + + "\"target_lang\":\"en\"," + + "\"entries_format\":\"tsv\"}"; + + assertEquals("POST", lastRequest.getMethod(), "unexpected request method"); + assertEquals(expected, lastRequest.getBody().readUtf8(), "unexpected request body"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTestDispatcher.java b/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTestDispatcher.java index d9a6229..594e16a 100644 --- a/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTestDispatcher.java +++ b/src/test/java/com/sitepark/translate/provider/deepl/DeeplTranslationProviderTestDispatcher.java @@ -1,8 +1,7 @@ package com.sitepark.translate.provider.deepl; -import java.net.HttpURLConnection; - import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.HttpURLConnection; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; @@ -10,100 +9,117 @@ @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") public class DeeplTranslationProviderTestDispatcher extends Dispatcher { - private static final String METHOD_GET = "GET"; - private static final String METHOD_POST = "POST"; - private static final String METHOD_DELETE = "DELETE"; + private static final String METHOD_GET = "GET"; + private static final String METHOD_POST = "POST"; + private static final String METHOD_DELETE = "DELETE"; - @Override - public MockResponse dispatch(RecordedRequest request) throws InterruptedException { - if (METHOD_GET.equals(request.getMethod())) { - return this.dispatchGet(request); - } else if (METHOD_POST.equals(request.getMethod())) { - return this.dispatchPost(request); - } else if (METHOD_DELETE.equals(request.getMethod())) { - return this.dispatchDelete(request); - } else { - throw new InterruptedException("Unsupported method: " + request.getMethod()); - } - } + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + if (METHOD_GET.equals(request.getMethod())) { + return this.dispatchGet(request); + } else if (METHOD_POST.equals(request.getMethod())) { + return this.dispatchPost(request); + } else if (METHOD_DELETE.equals(request.getMethod())) { + return this.dispatchDelete(request); + } else { + throw new InterruptedException("Unsupported method: " + request.getMethod()); + } + } - private MockResponse dispatchGet(RecordedRequest request) throws InterruptedException { + private MockResponse dispatchGet(RecordedRequest request) throws InterruptedException { - switch (request.getPath()) { - case "/glossaries": - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody("{\"glossaries\": [{\n" - + " \"glossary_id\": \"ee0c28af-e9cd-4b59-9199-f114ebc0d602\",\n" - + " \"name\": \"test:de/en\",\n" - + " \"ready\": true,\n" - + " \"source_lang\": \"de\",\n" - + " \"target_lang\": \"en\",\n" - + " \"creation_time\": \"2023-10-02T14:07:01.218419Z\",\n" - + " \"entry_count\": 2\n" - + "}]}"); - case "/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602": - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody("{\n" - + " \"glossary_id\": \"ee0c28af-e9cd-4b59-9199-f114ebc0d602\",\n" - + " \"name\": \"test:de/en\",\n" - + " \"ready\": true,\n" - + " \"source_lang\": \"de\",\n" - + " \"target_lang\": \"en\",\n" - + " \"creation_time\": \"2023-10-02T14:07:01.218419Z\",\n" - + " \"entry_count\": 2\n" - + "}"); - case "/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602/entries": - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody("Foo\tBar\nHallo\tHey\n"); - case "/languages?type=source": - case "/languages?type=target": - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody("[{\n" - + " \"language\": \"DE\",\n" - + " \"name\": \"German\",\n" - + " \"supports_formality\": true\n" - + " },{\n" - + " \"language\": \"EN-US\",\n" - + " \"name\": \"English (American)\",\n" - + " \"supports_formality\": false\n" - + " }]"); - default: - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); - } - } + switch (request.getPath()) { + case "/glossaries": + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_OK) + .setBody( + "{\"glossaries\": [{\n" + + " \"glossary_id\": \"ee0c28af-e9cd-4b59-9199-f114ebc0d602\",\n" + + " \"name\": \"test:de/en\",\n" + + " \"ready\": true,\n" + + " \"source_lang\": \"de\",\n" + + " \"target_lang\": \"en\",\n" + + " \"creation_time\": \"2023-10-02T14:07:01.218419Z\",\n" + + " \"entry_count\": 2\n" + + "}]}"); + case "/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602": + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_OK) + .setBody( + "{\n" + + " \"glossary_id\": \"ee0c28af-e9cd-4b59-9199-f114ebc0d602\",\n" + + " \"name\": \"test:de/en\",\n" + + " \"ready\": true,\n" + + " \"source_lang\": \"de\",\n" + + " \"target_lang\": \"en\",\n" + + " \"creation_time\": \"2023-10-02T14:07:01.218419Z\",\n" + + " \"entry_count\": 2\n" + + "}"); + case "/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602/entries": + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_OK) + .setBody("Foo\tBar\nHallo\tHey\n"); + case "/languages?type=source": + case "/languages?type=target": + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_OK) + .setBody( + "[{\n" + + " \"language\": \"DE\",\n" + + " \"name\": \"German\",\n" + + " \"supports_formality\": true\n" + + " },{\n" + + " \"language\": \"EN-US\",\n" + + " \"name\": \"English (American)\",\n" + + " \"supports_formality\": false\n" + + " }]"); + default: + return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); + } + } - private MockResponse dispatchPost(RecordedRequest request) throws InterruptedException { + private MockResponse dispatchPost(RecordedRequest request) throws InterruptedException { - switch (request.getPath()) { - case "/translate": - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody("{\n" - + " \"translations\": [\n" - + " {\n" - + " \"detected_source_language\": \"DE\",\n" - + " \"text\": \"Hello\"\n" - + " },\n" - + " {\n" - + " \"detected_source_language\": \"DE\",\n" - + " \"text\": \"World\"\n" - + " }\n" - + " ]\n" - + "}"); - case "/glossaries": - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody("{\n" - + " \"glossary_id\": \"ee0c28af-e9cd-4b59-9199-f114ebc0d602\",\n" - + " \"name\": \"de - en\",\n" - + " \"ready\": true,\n" - + " \"source_lang\": \"en\",\n" - + " \"target_lang\": \"de\",\n" - + " \"creation_time\": \"2023-10-04T09:15:55.805876Z\",\n" - + " \"entry_count\": 2\n" - + "}"); - default: - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); - } - } + switch (request.getPath()) { + case "/translate": + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_OK) + .setBody( + "{\n" + + " \"translations\": [\n" + + " {\n" + + " \"detected_source_language\": \"DE\",\n" + + " \"text\": \"Hello\"\n" + + " },\n" + + " {\n" + + " \"detected_source_language\": \"DE\",\n" + + " \"text\": \"World\"\n" + + " }\n" + + " ]\n" + + "}"); + case "/glossaries": + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_OK) + .setBody( + "{\n" + + " \"glossary_id\": \"ee0c28af-e9cd-4b59-9199-f114ebc0d602\",\n" + + " \"name\": \"de - en\",\n" + + " \"ready\": true,\n" + + " \"source_lang\": \"en\",\n" + + " \"target_lang\": \"de\",\n" + + " \"creation_time\": \"2023-10-04T09:15:55.805876Z\",\n" + + " \"entry_count\": 2\n" + + "}"); + default: + return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); + } + } - @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") - private MockResponse dispatchDelete(RecordedRequest request) throws InterruptedException { - if ("/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602".equals(request.getPath())) { - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NO_CONTENT); - } - return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); - } + @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") + private MockResponse dispatchDelete(RecordedRequest request) throws InterruptedException { + if ("/glossaries/ee0c28af-e9cd-4b59-9199-f114ebc0d602".equals(request.getPath())) { + return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NO_CONTENT); + } + return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); + } } diff --git a/src/test/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandlerTest.java b/src/test/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandlerTest.java index fa40a83..c82fbac 100644 --- a/src/test/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandlerTest.java +++ b/src/test/java/com/sitepark/translate/provider/deepl/JsonBodyLanguagesHandlerTest.java @@ -7,31 +7,29 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.function.Supplier; - import org.junit.jupiter.api.Test; @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts") class JsonBodyLanguagesHandlerTest { - @Test - void test() { - String json = "[{" + - "\"language\":\"de\"," + - "\"name\":\"deutsch\"," + - "\"supports_formality\":true" + - "}]"; - ByteArrayInputStream in = new ByteArrayInputStream( - json.getBytes(StandardCharsets.UTF_8)); + @Test + void test() { + String json = + "[{" + + "\"language\":\"de\"," + + "\"name\":\"deutsch\"," + + "\"supports_formality\":true" + + "}]"; + ByteArrayInputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); - Supplier> supplier = - JsonBodyLanguagesHandler.toSupplierOfType(in); + Supplier> supplier = JsonBodyLanguagesHandler.toSupplierOfType(in); - List res = supplier.get(); + List res = supplier.get(); - TransportLanguage transportLanguage = res.get(0); + TransportLanguage transportLanguage = res.get(0); - assertEquals("de", transportLanguage.getLanguage(), "unexpected language"); - assertEquals("deutsch", transportLanguage.getName(), "unexpected name"); - assertTrue(transportLanguage.isSupportsFormality(), "expect supports formality"); - } + assertEquals("de", transportLanguage.getLanguage(), "unexpected language"); + assertEquals("deutsch", transportLanguage.getName(), "unexpected name"); + assertTrue(transportLanguage.isSupportsFormality(), "expect supports formality"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/deepl/JsonResultTest.java b/src/test/java/com/sitepark/translate/provider/deepl/JsonResultTest.java index af6aff8..efb110e 100644 --- a/src/test/java/com/sitepark/translate/provider/deepl/JsonResultTest.java +++ b/src/test/java/com/sitepark/translate/provider/deepl/JsonResultTest.java @@ -7,52 +7,59 @@ import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class JsonResultTest { - @Test - void testErrorResult() { + @Test + void testErrorResult() { - JsonResult result = JsonResult.error(400, "test"); + JsonResult result = JsonResult.error(400, "test"); - assertEquals(400, result.getStatusCode(), "unexpected status code"); - assertThrows(IllegalStateException.class, () -> { - result.getSuccessValue(); - }, "success value should not returned"); - assertEquals("test", result.getErrorValue(), "unexpected error value"); - assertFalse(result.isSuccess(), "the result should not be a success"); - } + assertEquals(400, result.getStatusCode(), "unexpected status code"); + assertThrows( + IllegalStateException.class, + () -> { + result.getSuccessValue(); + }, + "success value should not returned"); + assertEquals("test", result.getErrorValue(), "unexpected error value"); + assertFalse(result.isSuccess(), "the result should not be a success"); + } - @Test - @SuppressWarnings("PMD.GuardLogStatement") - void testNullErrorValue() { - assertThrows(NullPointerException.class, () -> { - JsonResult.error(400, null); - }, "null error not allowed"); - } + @Test + @SuppressWarnings("PMD.GuardLogStatement") + void testNullErrorValue() { + assertThrows( + NullPointerException.class, + () -> { + JsonResult.error(400, null); + }, + "null error not allowed"); + } - @Test - void testSuccessResult() { + @Test + void testSuccessResult() { - JsonResult result = JsonResult.success(200, "test"); - - assertEquals(200, result.getStatusCode(), "unexpected status code"); - assertThrows(IllegalStateException.class, () -> { - result.getErrorValue(); - }, "error value should not returned"); - assertEquals("test", result.getSuccessValue(), "unexpected success value"); - assertTrue(result.isSuccess(), "the result should be a success"); - } - - @Test - void testNullSuccessValue() { - assertThrows(NullPointerException.class, () -> { - JsonResult.success(400, null); - }, "null error not allowed"); - } + JsonResult result = JsonResult.success(200, "test"); + assertEquals(200, result.getStatusCode(), "unexpected status code"); + assertThrows( + IllegalStateException.class, + () -> { + result.getErrorValue(); + }, + "error value should not returned"); + assertEquals("test", result.getSuccessValue(), "unexpected success value"); + assertTrue(result.isSuccess(), "the result should be a success"); + } + @Test + void testNullSuccessValue() { + assertThrows( + NullPointerException.class, + () -> { + JsonResult.success(400, null); + }, + "null error not allowed"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/deepl/LanguageTypeTest.java b/src/test/java/com/sitepark/translate/provider/deepl/LanguageTypeTest.java index 5c88893..1be91e4 100644 --- a/src/test/java/com/sitepark/translate/provider/deepl/LanguageTypeTest.java +++ b/src/test/java/com/sitepark/translate/provider/deepl/LanguageTypeTest.java @@ -4,16 +4,15 @@ import org.junit.jupiter.api.Test; - class LanguageTypeTest { - @Test - void testText() { - assertEquals("source", LanguageType.SOURCE.toString(), "should be lower case"); - } + @Test + void testText() { + assertEquals("source", LanguageType.SOURCE.toString(), "should be lower case"); + } - @Test - void testHtml() { - assertEquals("target", LanguageType.TARGET.toString(), "should be lower case"); - } + @Test + void testHtml() { + assertEquals("target", LanguageType.TARGET.toString(), "should be lower case"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandlerTest.java b/src/test/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandlerTest.java index 16eff01..f212197 100644 --- a/src/test/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandlerTest.java +++ b/src/test/java/com/sitepark/translate/provider/libretranslate/JsonBodyHandlerTest.java @@ -5,30 +5,22 @@ import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.function.Supplier; - import org.junit.jupiter.api.Test; class JsonBodyHandlerTest { - @Test - void test() { - String json = "{\"translatedText\":[" + - "\"Hello\"," + - "\"World\"" + - "]}"; - ByteArrayInputStream in = new ByteArrayInputStream( - json.getBytes(StandardCharsets.UTF_8)); + @Test + void test() { + String json = "{\"translatedText\":[" + "\"Hello\"," + "\"World\"" + "]}"; + ByteArrayInputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); - Supplier supplier = - JsonBodyHandler.toSupplierOfType(in, TransportResponse.class); + Supplier supplier = + JsonBodyHandler.toSupplierOfType(in, TransportResponse.class); - TransportResponse res = supplier.get(); + TransportResponse res = supplier.get(); - String[] translations = res.getTranslatedText(); + String[] translations = res.getTranslatedText(); - assertArrayEquals( - new String[] {"Hello", "World"}, - translations, - "unexpected translations"); - } + assertArrayEquals(new String[] {"Hello", "World"}, translations, "unexpected translations"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfigurationTest.java b/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfigurationTest.java index dc00f5d..230a0a9 100644 --- a/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfigurationTest.java +++ b/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderConfigurationTest.java @@ -4,145 +4,148 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.sitepark.translate.SupportedProvider; import java.net.InetSocketAddress; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; - import org.junit.jupiter.api.Test; -import com.sitepark.translate.SupportedProvider; - -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class LibreTranslateTranslationProviderConfigurationTest { - @Test - void testBuilder() throws URISyntaxException { - - LibreTranslateTranslationProviderConfiguration providerConfig = - LibreTranslateTranslationProviderConfiguration.builder() - .url("https://test") - .apiKey("abc") - .proxy("sitepark.com", 8080) - .build(); - - assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); - assertEquals("abc", providerConfig.getApiKey().get(), "unexpected authKey"); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testToBuilder() throws URISyntaxException { - - LibreTranslateTranslationProviderConfiguration providerConfig = - LibreTranslateTranslationProviderConfiguration.builder() - .url("https://test") - .apiKey("abc") - .proxy("sitepark.com", 8080) - .build(); - - providerConfig = providerConfig.toBuilder() - .apiKey("cde") - .build(); - - assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); - assertEquals("cde", providerConfig.getApiKey().get(), "unexpected authKey"); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testBuilderWithProxySelector() throws URISyntaxException { - - LibreTranslateTranslationProviderConfiguration providerConfig = - LibreTranslateTranslationProviderConfiguration.builder() - .url("https://test") - .apiKey("abc") - .proxy(ProxySelector.of(new InetSocketAddress("sitepark.com", 8080))) - .build(); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testBuilderWithProxyInetSocketAddress() throws URISyntaxException { - - LibreTranslateTranslationProviderConfiguration providerConfig = - LibreTranslateTranslationProviderConfiguration.builder() - .url("https://test") - .apiKey("abc") - .proxy(new InetSocketAddress("sitepark.com", 8080)) - .build(); - assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); - } - - @Test - void testSetUrlToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder().url(null); - }); - } - - @Test - void testSetAuthKeyToNull() { - assertThrows(NullPointerException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder().apiKey(null); - }); - } - - @Test - void testSetProxyHostToNull() { - assertThrows(NullPointerException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder().proxy(null, 8080); - }); - } - - @Test - void testSetProxyPortToZero() { - assertThrows(IllegalArgumentException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder().proxy("test.de", 0); - }); - } - - @Test - void testSetProxySelectorToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder().proxy((ProxySelector)null); - }); - } - - @Test - void testSetProxyInetSocketAddressToNull() throws URISyntaxException { - assertThrows(NullPointerException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder().proxy((InetSocketAddress)null); - }); - } - - @Test - void testMissingUri() throws URISyntaxException { - assertThrows(IllegalStateException.class, () -> { - LibreTranslateTranslationProviderConfiguration.builder() - .apiKey("abc") - .proxy("sitepark.com", 8080) - .build(); - }); - } - - @Test - void tetGetType() throws URISyntaxException { - - LibreTranslateTranslationProviderConfiguration providerConfig = - LibreTranslateTranslationProviderConfiguration.builder() - .url("https://test") - .apiKey("abc") - .proxy("sitepark.com", 8080) - .build(); - - assertEquals( - SupportedProvider.LIBRE_TRANSLATE, - providerConfig.getType(), - "unexpected type"); - } - + @Test + void testBuilder() throws URISyntaxException { + + LibreTranslateTranslationProviderConfiguration providerConfig = + LibreTranslateTranslationProviderConfiguration.builder() + .url("https://test") + .apiKey("abc") + .proxy("sitepark.com", 8080) + .build(); + + assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); + assertEquals("abc", providerConfig.getApiKey().get(), "unexpected authKey"); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testToBuilder() throws URISyntaxException { + + LibreTranslateTranslationProviderConfiguration providerConfig = + LibreTranslateTranslationProviderConfiguration.builder() + .url("https://test") + .apiKey("abc") + .proxy("sitepark.com", 8080) + .build(); + + providerConfig = providerConfig.toBuilder().apiKey("cde").build(); + + assertEquals(new URI("https://test"), providerConfig.getUri(), "unexpected uri"); + assertEquals("cde", providerConfig.getApiKey().get(), "unexpected authKey"); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testBuilderWithProxySelector() throws URISyntaxException { + + LibreTranslateTranslationProviderConfiguration providerConfig = + LibreTranslateTranslationProviderConfiguration.builder() + .url("https://test") + .apiKey("abc") + .proxy(ProxySelector.of(new InetSocketAddress("sitepark.com", 8080))) + .build(); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testBuilderWithProxyInetSocketAddress() throws URISyntaxException { + + LibreTranslateTranslationProviderConfiguration providerConfig = + LibreTranslateTranslationProviderConfiguration.builder() + .url("https://test") + .apiKey("abc") + .proxy(new InetSocketAddress("sitepark.com", 8080)) + .build(); + assertTrue(providerConfig.getProxy().isPresent(), "proxy expected"); + } + + @Test + void testSetUrlToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder().url(null); + }); + } + + @Test + void testSetAuthKeyToNull() { + assertThrows( + NullPointerException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder().apiKey(null); + }); + } + + @Test + void testSetProxyHostToNull() { + assertThrows( + NullPointerException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder().proxy(null, 8080); + }); + } + + @Test + void testSetProxyPortToZero() { + assertThrows( + IllegalArgumentException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder().proxy("test.de", 0); + }); + } + + @Test + void testSetProxySelectorToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder().proxy((ProxySelector) null); + }); + } + + @Test + void testSetProxyInetSocketAddressToNull() throws URISyntaxException { + assertThrows( + NullPointerException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder().proxy((InetSocketAddress) null); + }); + } + + @Test + void testMissingUri() throws URISyntaxException { + assertThrows( + IllegalStateException.class, + () -> { + LibreTranslateTranslationProviderConfiguration.builder() + .apiKey("abc") + .proxy("sitepark.com", 8080) + .build(); + }); + } + + @Test + void tetGetType() throws URISyntaxException { + + LibreTranslateTranslationProviderConfiguration providerConfig = + LibreTranslateTranslationProviderConfiguration.builder() + .url("https://test") + .apiKey("abc") + .proxy("sitepark.com", 8080) + .build(); + + assertEquals(SupportedProvider.LIBRE_TRANSLATE, providerConfig.getType(), "unexpected type"); + } } diff --git a/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderTest.java b/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderTest.java index 4529f2e..4e85f39 100644 --- a/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderTest.java +++ b/src/test/java/com/sitepark/translate/provider/libretranslate/LibreTranslateTranslationProviderTest.java @@ -3,11 +3,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.mockito.Mockito.when; -import java.io.IOException; - -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import com.sitepark.translate.Format; import com.sitepark.translate.SupportedProvider; import com.sitepark.translate.TranslationConfiguration; @@ -15,57 +10,53 @@ import com.sitepark.translate.TranslationParameter; import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; +import java.io.IOException; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; -@SuppressWarnings({ - "PMD.AvoidDuplicateLiterals", - "PMD.JUnitTestContainsTooManyAsserts" -}) +@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.JUnitTestContainsTooManyAsserts"}) class LibreTranslateTranslationProviderTest { - @Test - void testTranslation() { - - TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); - when(config.isEncodePlaceholder()).thenReturn(true); + @Test + void testTranslation() { - LibreTranslateTranslationProvider provider = new HelloWorldLibreTranslateTranslationProvider(config); + TranslationConfiguration config = Mockito.mock(TranslationConfiguration.class); + when(config.isEncodePlaceholder()).thenReturn(true); - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); + LibreTranslateTranslationProvider provider = + new HelloWorldLibreTranslateTranslationProvider(config); - TranslationRequest req = TranslationRequest.builder() - .parameter(TranslationParameter.builder() - .format(Format.TEXT) - .language(language) - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .build() - ) - .sourceText("Hallo", "Welt") - .build(); + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); - TranslationResult translated = provider.translate(req); + TranslationRequest req = + TranslationRequest.builder() + .parameter( + TranslationParameter.builder() + .format(Format.TEXT) + .language(language) + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .build()) + .sourceText("Hallo", "Welt") + .build(); - assertArrayEquals( - new String[] {"Hello", "World"}, - translated.getText(), - "unexpected translation"); - } + TranslationResult translated = provider.translate(req); - private static final class HelloWorldLibreTranslateTranslationProvider extends LibreTranslateTranslationProvider { + assertArrayEquals( + new String[] {"Hello", "World"}, translated.getText(), "unexpected translation"); + } - public HelloWorldLibreTranslateTranslationProvider(TranslationConfiguration translatorConfiguration) { - super(translatorConfiguration); - } + private static final class HelloWorldLibreTranslateTranslationProvider + extends LibreTranslateTranslationProvider { - @Override - protected String[] translationRequest( - TranslationParameter parameter, - String... source) - throws IOException, InterruptedException { - return new String[] {"Hello", "World"}; - } - } + public HelloWorldLibreTranslateTranslationProvider( + TranslationConfiguration translatorConfiguration) { + super(translatorConfiguration); + } + @Override + protected String[] translationRequest(TranslationParameter parameter, String... source) + throws IOException, InterruptedException { + return new String[] {"Hello", "World"}; + } + } } diff --git a/src/test/java/com/sitepark/translate/provider/libretranslate/TransportRequestTest.java b/src/test/java/com/sitepark/translate/provider/libretranslate/TransportRequestTest.java index 4daf16a..8532580 100644 --- a/src/test/java/com/sitepark/translate/provider/libretranslate/TransportRequestTest.java +++ b/src/test/java/com/sitepark/translate/provider/libretranslate/TransportRequestTest.java @@ -4,111 +4,112 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.Test; - import com.sitepark.translate.Format; +import org.junit.jupiter.api.Test; -@SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.AvoidDuplicateLiterals" -}) +@SuppressWarnings({"PMD.JUnitTestContainsTooManyAsserts", "PMD.AvoidDuplicateLiterals"}) class TransportRequestTest { - @Test - void testBuilder() { - - TransportRequest request = TransportRequest.builder() - .q("Hallo", "Welt") - .source("de") - .target("en") - .format(Format.HTML) - .apiKey("abc") - .build(); - - assertArrayEquals( - new String[] {"Hallo", "Welt"}, - request.getQ(), - "unexpected q-field" - ); - assertEquals("de", request.getSource(), "unexpected source"); - assertEquals("en", request.getTarget(), "unexpected target"); - assertEquals(Format.HTML, request.getFormat(), "unexpected format"); - assertEquals("abc", request.getApiKey(), "unexpected apiKey"); - } - - @Test - void testToBuilder() { - - TransportRequest request = TransportRequest.builder() - .q("Hallo", "Welt") - .source("de") - .target("en") - .format(Format.HTML) - .apiKey("abc") - .build(); - - request = request.toBuilder() - .q("Apfel") - .build(); - - assertArrayEquals( - new String[] {"Apfel"}, - request.getQ(), - "unexpected q-field" - ); - assertEquals("de", request.getSource(), "unexpected source"); - assertEquals("en", request.getTarget(), "unexpected target"); - assertEquals(Format.HTML, request.getFormat(), "unexpected format"); - assertEquals("abc", request.getApiKey(), "unexpected apiKey"); - } - - @Test - void testQSetNullArray() { - assertThrows(NullPointerException.class, () -> { - TransportRequest.builder().q((String[])null); - }); - } - - @Test - void testQSetEmptyArray() { - assertThrows(IllegalArgumentException.class, () -> { - TransportRequest.builder().q(new String[] {}); - }); - } - - @Test - void testQSetNullString() { - assertThrows(NullPointerException.class, () -> { - TransportRequest.builder().q((String)null); - }); - } - - @Test - void testSourceSetNull() { - assertThrows(NullPointerException.class, () -> { - TransportRequest.builder().source(null); - }); - } - - @Test - void testTargetSetNull() { - assertThrows(NullPointerException.class, () -> { - TransportRequest.builder().target(null); - }); - } - - @Test - void testFormatSetNull() { - assertThrows(NullPointerException.class, () -> { - TransportRequest.builder().format(null); - }); - } - - @Test - void testApiKeysSetNull() { - assertThrows(NullPointerException.class, () -> { - TransportRequest.builder().apiKey(null); - }); - } - + @Test + void testBuilder() { + + TransportRequest request = + TransportRequest.builder() + .q("Hallo", "Welt") + .source("de") + .target("en") + .format(Format.HTML) + .apiKey("abc") + .build(); + + assertArrayEquals(new String[] {"Hallo", "Welt"}, request.getQ(), "unexpected q-field"); + assertEquals("de", request.getSource(), "unexpected source"); + assertEquals("en", request.getTarget(), "unexpected target"); + assertEquals(Format.HTML, request.getFormat(), "unexpected format"); + assertEquals("abc", request.getApiKey(), "unexpected apiKey"); + } + + @Test + void testToBuilder() { + + TransportRequest request = + TransportRequest.builder() + .q("Hallo", "Welt") + .source("de") + .target("en") + .format(Format.HTML) + .apiKey("abc") + .build(); + + request = request.toBuilder().q("Apfel").build(); + + assertArrayEquals(new String[] {"Apfel"}, request.getQ(), "unexpected q-field"); + assertEquals("de", request.getSource(), "unexpected source"); + assertEquals("en", request.getTarget(), "unexpected target"); + assertEquals(Format.HTML, request.getFormat(), "unexpected format"); + assertEquals("abc", request.getApiKey(), "unexpected apiKey"); + } + + @Test + void testQSetNullArray() { + assertThrows( + NullPointerException.class, + () -> { + TransportRequest.builder().q((String[]) null); + }); + } + + @Test + void testQSetEmptyArray() { + assertThrows( + IllegalArgumentException.class, + () -> { + TransportRequest.builder().q(new String[] {}); + }); + } + + @Test + void testQSetNullString() { + assertThrows( + NullPointerException.class, + () -> { + TransportRequest.builder().q((String) null); + }); + } + + @Test + void testSourceSetNull() { + assertThrows( + NullPointerException.class, + () -> { + TransportRequest.builder().source(null); + }); + } + + @Test + void testTargetSetNull() { + assertThrows( + NullPointerException.class, + () -> { + TransportRequest.builder().target(null); + }); + } + + @Test + void testFormatSetNull() { + assertThrows( + NullPointerException.class, + () -> { + TransportRequest.builder().format(null); + }); + } + + @Test + void testApiKeysSetNull() { + assertThrows( + NullPointerException.class, + () -> { + TransportRequest.builder().apiKey(null); + }); + } } diff --git a/src/test/java/com/sitepark/translate/translator/FormatDetectorTest.java b/src/test/java/com/sitepark/translate/translator/FormatDetectorTest.java index dd7426c..99c7705 100644 --- a/src/test/java/com/sitepark/translate/translator/FormatDetectorTest.java +++ b/src/test/java/com/sitepark/translate/translator/FormatDetectorTest.java @@ -8,60 +8,53 @@ @SuppressWarnings("PMD.AvoidDuplicateLiterals") class FormatDetectorTest { - @Test - void testContainsHtmlPlainText() { - assertFalse(FormatDetector.containsHtml( - "A text without HTML"), - "should be plain text"); - } - - @Test - void testContainsHtmlPlainTextGreaterThan() { - assertFalse(FormatDetector.containsHtml( - "A text without HTML, but with >"), - "should be plain text"); - } - - @Test - void testContainsHtmlPlainTextLowerThan() { - assertFalse(FormatDetector.containsHtml( - "A text without HTML, but with <"), - "should be plain text"); - } - - @Test - void testContainsHtmlPlainTextLowerThanGreaterThanMix() { - assertFalse(FormatDetector.containsHtml( - "A text without HTML, but with < 1 > 7"), - "should be plain text"); - } - - @Test - void testContainsHtmlWithHtmlEntity() { - assertTrue( - FormatDetector.containsHtml("A text with entity &, so it's HTML"), - "should be html text"); - } - - @Test - void testContainsHtmlWithHtmlTag() { - assertTrue( - FormatDetector.containsHtml("A text with tag , so it's HTML"), - "should be html text"); - } - - @Test - void testContainsHtmlWithHtmlBodyTag() { - assertTrue( - FormatDetector.containsHtml("A text with body-tag text, so it's HTML"), - "should be html text"); - } - - @Test - void testContainsPlaceholder() { - assertTrue( - FormatDetector.containsPlaceholder("Good morning ${name}"), - "should find placeholder"); - } - + @Test + void testContainsHtmlPlainText() { + assertFalse(FormatDetector.containsHtml("A text without HTML"), "should be plain text"); + } + + @Test + void testContainsHtmlPlainTextGreaterThan() { + assertFalse( + FormatDetector.containsHtml("A text without HTML, but with >"), "should be plain text"); + } + + @Test + void testContainsHtmlPlainTextLowerThan() { + assertFalse( + FormatDetector.containsHtml("A text without HTML, but with <"), "should be plain text"); + } + + @Test + void testContainsHtmlPlainTextLowerThanGreaterThanMix() { + assertFalse( + FormatDetector.containsHtml("A text without HTML, but with < 1 > 7"), + "should be plain text"); + } + + @Test + void testContainsHtmlWithHtmlEntity() { + assertTrue( + FormatDetector.containsHtml("A text with entity &, so it's HTML"), + "should be html text"); + } + + @Test + void testContainsHtmlWithHtmlTag() { + assertTrue( + FormatDetector.containsHtml("A text with tag , so it's HTML"), "should be html text"); + } + + @Test + void testContainsHtmlWithHtmlBodyTag() { + assertTrue( + FormatDetector.containsHtml("A text with body-tag text, so it's HTML"), + "should be html text"); + } + + @Test + void testContainsPlaceholder() { + assertTrue( + FormatDetector.containsPlaceholder("Good morning ${name}"), "should find placeholder"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/JsonFileListTranslatorTest.java b/src/test/java/com/sitepark/translate/translator/JsonFileListTranslatorTest.java index 7ff66a1..7ea9c08 100644 --- a/src/test/java/com/sitepark/translate/translator/JsonFileListTranslatorTest.java +++ b/src/test/java/com/sitepark/translate/translator/JsonFileListTranslatorTest.java @@ -5,6 +5,15 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.sitepark.translate.Language; +import com.sitepark.translate.SupportedLanguages; +import com.sitepark.translate.SupportedProvider; +import com.sitepark.translate.TranslationConfiguration; +import com.sitepark.translate.TranslationProvider; +import com.sitepark.translate.TranslationProviderFactory; +import com.sitepark.translate.TranslationRequest; +import com.sitepark.translate.TranslationResult; +import com.sitepark.translate.TranslationResultStatistic; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -14,96 +23,80 @@ import java.util.Comparator; import java.util.HashMap; import java.util.Map; - import org.junit.jupiter.api.Test; -import com.sitepark.translate.Language; -import com.sitepark.translate.SupportedLanguages; -import com.sitepark.translate.SupportedProvider; -import com.sitepark.translate.TranslationConfiguration; -import com.sitepark.translate.TranslationProvider; -import com.sitepark.translate.TranslationProviderFactory; -import com.sitepark.translate.TranslationRequest; -import com.sitepark.translate.TranslationResult; -import com.sitepark.translate.TranslationResultStatistic; - class JsonFileListTranslatorTest { - @Test - @SuppressWarnings({"PMD.UseConcurrentHashMap"}) - void test() throws Exception { - - SupportedLanguages supportedLanguages = SupportedLanguages.builder() - .language(Language.builder() - .code("de") - .name("deutsch") - .targets("en") - ) - .build(); - - Map dictionary = new HashMap<>(); - dictionary.put("Hallo", "Hello"); - dictionary.put("Welt", "World"); - - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenAnswer(invocationOnMock -> { - - TranslationRequest req = (TranslationRequest)invocationOnMock.getArguments()[0]; - String[] sourceText = req.getSourceText(); - String[] translations = new String[sourceText.length]; - for (int i = 0; i < translations.length; i++) { - translations[i] = dictionary.get(sourceText[i]); - } - - return TranslationResult.builder() - .request(req) - .text(translations) - .statistic(TranslationResultStatistic.EMPTY) - .build(); - }); - when(transporter.getSupportedLanguages()).thenReturn(supportedLanguages); - - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); - - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .build(); - - Path dir = Paths.get("src/test/resources/JsonFileListTranslator"); - Path output = Paths.get("target/test/JsonFileListTranslator/translations"); - this.cleanCache(output); - - JsonFileListTranslator jsonFileListTranslator = JsonFileListTranslator.builder() - .dir(dir) - .output(output) - .sourceLang("de") - .targetLangList("en") - .translatorConfiguration(translatorConfiguration) - .build(); - - jsonFileListTranslator.translate(SupportedProvider.LIBRE_TRANSLATE); - - Path resultA = output.resolve("en/a.json"); - assertEquals("{\n" - + " \"text\" : \"Hello\"\n" - + "}", Files.readString(resultA, StandardCharsets.UTF_8), - "wrong content in en/a.json"); - - Path resultC = output.resolve("en/b/c.json"); - assertEquals("{\n" - + " \"d\" : \"World\"\n" - + "}", Files.readString(resultC, StandardCharsets.UTF_8), - "wrong content in en/b/c.json"); - } - - private void cleanCache(Path dir) throws IOException { - if (!Files.exists(dir)) { - return; - } - Files.walk(dir) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } + @Test + @SuppressWarnings({"PMD.UseConcurrentHashMap"}) + void test() throws Exception { + + SupportedLanguages supportedLanguages = + SupportedLanguages.builder() + .language(Language.builder().code("de").name("deutsch").targets("en")) + .build(); + + Map dictionary = new HashMap<>(); + dictionary.put("Hallo", "Hello"); + dictionary.put("Welt", "World"); + + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))) + .thenAnswer( + invocationOnMock -> { + TranslationRequest req = (TranslationRequest) invocationOnMock.getArguments()[0]; + String[] sourceText = req.getSourceText(); + String[] translations = new String[sourceText.length]; + for (int i = 0; i < translations.length; i++) { + translations[i] = dictionary.get(sourceText[i]); + } + + return TranslationResult.builder() + .request(req) + .text(translations) + .statistic(TranslationResultStatistic.EMPTY) + .build(); + }); + when(transporter.getSupportedLanguages()).thenReturn(supportedLanguages); + + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); + + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder().translationProviderFactory(transporterFactory).build(); + + Path dir = Paths.get("src/test/resources/JsonFileListTranslator"); + Path output = Paths.get("target/test/JsonFileListTranslator/translations"); + this.cleanCache(output); + + JsonFileListTranslator jsonFileListTranslator = + JsonFileListTranslator.builder() + .dir(dir) + .output(output) + .sourceLang("de") + .targetLangList("en") + .translatorConfiguration(translatorConfiguration) + .build(); + + jsonFileListTranslator.translate(SupportedProvider.LIBRE_TRANSLATE); + + Path resultA = output.resolve("en/a.json"); + assertEquals( + "{\n" + " \"text\" : \"Hello\"\n" + "}", + Files.readString(resultA, StandardCharsets.UTF_8), + "wrong content in en/a.json"); + + Path resultC = output.resolve("en/b/c.json"); + assertEquals( + "{\n" + " \"d\" : \"World\"\n" + "}", + Files.readString(resultC, StandardCharsets.UTF_8), + "wrong content in en/b/c.json"); + } + + private void cleanCache(Path dir) throws IOException { + if (!Files.exists(dir)) { + return; + } + Files.walk(dir).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } } diff --git a/src/test/java/com/sitepark/translate/translator/JsonNodeTranslatorTest.java b/src/test/java/com/sitepark/translate/translator/JsonNodeTranslatorTest.java index a6b17fc..e63df84 100644 --- a/src/test/java/com/sitepark/translate/translator/JsonNodeTranslatorTest.java +++ b/src/test/java/com/sitepark/translate/translator/JsonNodeTranslatorTest.java @@ -5,8 +5,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; @@ -21,59 +19,54 @@ import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; import com.sitepark.translate.TranslationResultStatistic; +import org.junit.jupiter.api.Test; class JsonNodeTranslatorTest { - @Test - void test() throws Exception { + @Test + void test() throws Exception { - TranslationResult result = TranslationResult.builder() - .request(mock(TranslationRequest.class)) - .text(new String[] { - "Flowers", - "Blue" - }) - .statistic(TranslationResultStatistic.EMPTY) - .build(); + TranslationResult result = + TranslationResult.builder() + .request(mock(TranslationRequest.class)) + .text(new String[] {"Flowers", "Blue"}) + .statistic(TranslationResultStatistic.EMPTY) + .build(); - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenReturn(result); + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))).thenReturn(result); - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .build(); + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder().translationProviderFactory(transporterFactory).build(); - JsonNodeFactory factory = JsonNodeFactory.instance; + JsonNodeFactory factory = JsonNodeFactory.instance; - ArrayNode array = factory.arrayNode(); - ObjectNode object = factory.objectNode(); - TextNode textInObject = factory.textNode("Blume"); - TextNode textInArray = factory.textNode("Blaue"); + ArrayNode array = factory.arrayNode(); + ObjectNode object = factory.objectNode(); + TextNode textInObject = factory.textNode("Blume"); + TextNode textInArray = factory.textNode("Blaue"); - array.add(object); - object.set("text", textInObject); - array.add(textInArray); + array.add(object); + object.set("text", textInObject); + array.add(textInArray); - JsonNodeTranslator translator = JsonNodeTranslator.builder() - .translatorConfiguration(translatorConfiguration) - .build(); + JsonNodeTranslator translator = + JsonNodeTranslator.builder().translatorConfiguration(translatorConfiguration).build(); - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); - TranslationParameter parameter = TranslationParameter.builder() - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .language(language) - .build(); + TranslationParameter parameter = + TranslationParameter.builder() + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .language(language) + .build(); - JsonNode translation = translator.translate(parameter, array); + JsonNode translation = translator.translate(parameter, array); - assertEquals("Flowers", translation.get(0).get("text").asText(), "wrong translation"); - assertEquals("Blue", translation.get(1).asText(), "wrong translation"); - } + assertEquals("Flowers", translation.get(0).get("text").asText(), "wrong translation"); + assertEquals("Blue", translation.get(1).asText(), "wrong translation"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/JsonStringTranslatorTest.java b/src/test/java/com/sitepark/translate/translator/JsonStringTranslatorTest.java index 78f2a20..8d49f17 100644 --- a/src/test/java/com/sitepark/translate/translator/JsonStringTranslatorTest.java +++ b/src/test/java/com/sitepark/translate/translator/JsonStringTranslatorTest.java @@ -5,8 +5,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; - import com.sitepark.translate.SupportedProvider; import com.sitepark.translate.TranslationConfiguration; import com.sitepark.translate.TranslationLanguage; @@ -16,66 +14,60 @@ import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; import com.sitepark.translate.TranslationResultStatistic; +import org.junit.jupiter.api.Test; class JsonStringTranslatorTest { - @Test - void test() throws Exception { - - TranslationResult translationResult = TranslationResult.builder() - .request(mock(TranslationRequest.class)) - .text(new String[] { - "Heading", - "A beautiful text", - "Flowers" - }) - .statistic(TranslationResultStatistic.EMPTY) - .build(); - - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); - - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); - - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .build(); - - - JsonStringTranslator translator = JsonStringTranslator.builder() - .translatorConfiguration(translatorConfiguration) - .build(); - - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); - - TranslationParameter parameter = TranslationParameter.builder() - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .language(language) - .build(); - - String result = translator.translate( - parameter, - "{\n" - + " \"headline\":\"Überschrift\",\n" - + " \"text\":\"Ein schöner Text\",\n" - + " \"items\" : [\n" - + " {\n" - + " \"text\" : \"Blumen\",\n" - + " \"number\" : 10,\n" - + " \"boolean\" :true\n" - + " }\n" - + " ]\n" - + "}"); - - String expected = "{\"headline\":\"Heading\"," + - "\"text\":\"A beautiful text\"," + - "\"items\":[{\"text\":\"Flowers\",\"number\":10,\"boolean\":true}]}"; - - assertEquals(expected, result, "unexpected json data"); - } - + @Test + void test() throws Exception { + + TranslationResult translationResult = + TranslationResult.builder() + .request(mock(TranslationRequest.class)) + .text(new String[] {"Heading", "A beautiful text", "Flowers"}) + .statistic(TranslationResultStatistic.EMPTY) + .build(); + + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); + + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); + + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder().translationProviderFactory(transporterFactory).build(); + + JsonStringTranslator translator = + JsonStringTranslator.builder().translatorConfiguration(translatorConfiguration).build(); + + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); + + TranslationParameter parameter = + TranslationParameter.builder() + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .language(language) + .build(); + + String result = + translator.translate( + parameter, + "{\n" + + " \"headline\":\"Überschrift\",\n" + + " \"text\":\"Ein schöner Text\",\n" + + " \"items\" : [\n" + + " {\n" + + " \"text\" : \"Blumen\",\n" + + " \"number\" : 10,\n" + + " \"boolean\" :true\n" + + " }\n" + + " ]\n" + + "}"); + + String expected = + "{\"headline\":\"Heading\"," + + "\"text\":\"A beautiful text\"," + + "\"items\":[{\"text\":\"Flowers\",\"number\":10,\"boolean\":true}]}"; + + assertEquals(expected, result, "unexpected json data"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/StringArrayTranslatorTest.java b/src/test/java/com/sitepark/translate/translator/StringArrayTranslatorTest.java index 8fb5f0d..5045293 100644 --- a/src/test/java/com/sitepark/translate/translator/StringArrayTranslatorTest.java +++ b/src/test/java/com/sitepark/translate/translator/StringArrayTranslatorTest.java @@ -5,8 +5,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; - import com.sitepark.translate.Format; import com.sitepark.translate.SupportedProvider; import com.sitepark.translate.TranslationConfiguration; @@ -17,53 +15,46 @@ import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; import com.sitepark.translate.TranslationResultStatistic; +import org.junit.jupiter.api.Test; class StringArrayTranslatorTest { - @Test - void test() throws Exception { + @Test + void test() throws Exception { - TranslationResult translationResult = TranslationResult.builder() - .request(mock(TranslationRequest.class)) - .text(new String[] { - "Hello", - "World" - }) - .statistic(TranslationResultStatistic.EMPTY) - .build(); + TranslationResult translationResult = + TranslationResult.builder() + .request(mock(TranslationRequest.class)) + .text(new String[] {"Hello", "World"}) + .statistic(TranslationResultStatistic.EMPTY) + .build(); - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .build(); + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder().translationProviderFactory(transporterFactory).build(); - StringArrayTranslator translator = StringArrayTranslator.builder() - .translatorConfiguration(translatorConfiguration) - .build(); + StringArrayTranslator translator = + StringArrayTranslator.builder().translatorConfiguration(translatorConfiguration).build(); - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); - TranslationParameter parameter = TranslationParameter.builder() - .format(Format.TEXT) - .language(language) - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .build(); + TranslationParameter parameter = + TranslationParameter.builder() + .format(Format.TEXT) + .language(language) + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .build(); - TranslationRequest req = TranslationRequest.builder() - .parameter(parameter) - .sourceText("Hallo", "Welt") - .build(); + TranslationRequest req = + TranslationRequest.builder().parameter(parameter).sourceText("Hallo", "Welt").build(); - TranslationResult result = translator.translate(req); + TranslationResult result = translator.translate(req); - assertArrayEquals(new String[] {"Hello", "World"}, result.getText(), "wrong translation"); - } + assertArrayEquals(new String[] {"Hello", "World"}, result.getText(), "wrong translation"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/StringTranslatorTest.java b/src/test/java/com/sitepark/translate/translator/StringTranslatorTest.java index 06e6531..83a64c3 100644 --- a/src/test/java/com/sitepark/translate/translator/StringTranslatorTest.java +++ b/src/test/java/com/sitepark/translate/translator/StringTranslatorTest.java @@ -5,8 +5,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; - import com.sitepark.translate.Format; import com.sitepark.translate.SupportedProvider; import com.sitepark.translate.TranslationConfiguration; @@ -17,49 +15,43 @@ import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; import com.sitepark.translate.TranslationResultStatistic; +import org.junit.jupiter.api.Test; class StringTranslatorTest { - @Test - void test() throws Exception { + @Test + void test() throws Exception { - TranslationResult translationResult = TranslationResult.builder() - .request(mock(TranslationRequest.class)) - .text(new String[] { - "Hello" - }) - .statistic(TranslationResultStatistic.EMPTY) - .build(); + TranslationResult translationResult = + TranslationResult.builder() + .request(mock(TranslationRequest.class)) + .text(new String[] {"Hello"}) + .statistic(TranslationResultStatistic.EMPTY) + .build(); + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder().translationProviderFactory(transporterFactory).build(); - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .build(); + StringTranslator translator = + StringTranslator.builder().translatorConfiguration(translatorConfiguration).build(); - StringTranslator translator = StringTranslator.builder() - .translatorConfiguration(translatorConfiguration) - .build(); + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); + TranslationParameter parameter = + TranslationParameter.builder() + .format(Format.TEXT) + .language(language) + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .build(); - TranslationParameter parameter = TranslationParameter.builder() - .format(Format.TEXT) - .language(language) - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .build(); + String result = translator.translate(parameter, "Hallo"); - String result = translator.translate(parameter, "Hallo"); - - assertEquals("Hello", result, "wrong translation"); - } + assertEquals("Hello", result, "wrong translation"); + } } - diff --git a/src/test/java/com/sitepark/translate/translator/TranslatableTextListTranslatorTest.java b/src/test/java/com/sitepark/translate/translator/TranslatableTextListTranslatorTest.java index db3e4ff..151cbd9 100644 --- a/src/test/java/com/sitepark/translate/translator/TranslatableTextListTranslatorTest.java +++ b/src/test/java/com/sitepark/translate/translator/TranslatableTextListTranslatorTest.java @@ -5,12 +5,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import org.junit.jupiter.api.Test; - import com.sitepark.translate.SupportedProvider; import com.sitepark.translate.TranslationCache; import com.sitepark.translate.TranslationConfiguration; @@ -21,107 +15,103 @@ import com.sitepark.translate.TranslationRequest; import com.sitepark.translate.TranslationResult; import com.sitepark.translate.TranslationResultStatistic; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; class TranslatableTextListTranslatorTest { - @Test - @SuppressWarnings("PMD.AvoidDuplicateLiterals") - void test() throws Exception { - - TranslationResult translationResult = TranslationResult.builder() - .request(mock(TranslationRequest.class)) - .text(new String[] { - "Flowers", - "Blue" - }) - .statistic(TranslationResultStatistic.EMPTY) - .build(); - - - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); + @Test + @SuppressWarnings("PMD.AvoidDuplicateLiterals") + void test() throws Exception { - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); + TranslationResult translationResult = + TranslationResult.builder() + .request(mock(TranslationRequest.class)) + .text(new String[] {"Flowers", "Blue"}) + .statistic(TranslationResultStatistic.EMPTY) + .build(); - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .build(); + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); - List translatableTextList = new ArrayList<>(); - translatableTextList.add(new TranslatableText("Blume")); - translatableTextList.add(new TranslatableText("Blau")); + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); - TranslatableTextListTranslator translator = TranslatableTextListTranslator.builder() - .translatorConfiguration(translatorConfiguration) - .build(); + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder().translationProviderFactory(transporterFactory).build(); - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); + List translatableTextList = new ArrayList<>(); + translatableTextList.add(new TranslatableText("Blume")); + translatableTextList.add(new TranslatableText("Blau")); - TranslationParameter parameter = TranslationParameter.builder() - .language(language) - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .build(); + TranslatableTextListTranslator translator = + TranslatableTextListTranslator.builder() + .translatorConfiguration(translatorConfiguration) + .build(); - translator.translate(parameter, translatableTextList); + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); - assertEquals("Flowers", translatableTextList.get(0).getTargetText(), "unexpected translation"); - assertEquals("Blue", translatableTextList.get(1).getTargetText(), "unexpected translation"); - } + TranslationParameter parameter = + TranslationParameter.builder() + .language(language) + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .build(); - @Test - void testWithCache() throws Exception { + translator.translate(parameter, translatableTextList); - TranslationResult translationResult = TranslationResult.builder() - .request(mock(TranslationRequest.class)) - .text(new String[] { - "Blue" - }) - .statistic(TranslationResultStatistic.EMPTY) - .build(); + assertEquals("Flowers", translatableTextList.get(0).getTargetText(), "unexpected translation"); + assertEquals("Blue", translatableTextList.get(1).getTargetText(), "unexpected translation"); + } + @Test + void testWithCache() throws Exception { - TranslationProvider transporter = mock(TranslationProvider.class); - when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); + TranslationResult translationResult = + TranslationResult.builder() + .request(mock(TranslationRequest.class)) + .text(new String[] {"Blue"}) + .statistic(TranslationResultStatistic.EMPTY) + .build(); - TranslationCache translationCache = mock(TranslationCache.class); - // last match wins - when(translationCache.translate(any())).thenReturn(Optional.empty()); - when(translationCache.translate("Blume")).thenReturn(Optional.of("Flowers")); + TranslationProvider transporter = mock(TranslationProvider.class); + when(transporter.translate(any(TranslationRequest.class))).thenReturn(translationResult); - TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); - when(transporterFactory.create(any())).thenReturn(transporter); + TranslationCache translationCache = mock(TranslationCache.class); + // last match wins + when(translationCache.translate(any())).thenReturn(Optional.empty()); + when(translationCache.translate("Blume")).thenReturn(Optional.of("Flowers")); - TranslationConfiguration translatorConfiguration = TranslationConfiguration.builder() - .translationProviderFactory(transporterFactory) - .translationCache(translationCache) - .build(); + TranslationProviderFactory transporterFactory = mock(TranslationProviderFactory.class); + when(transporterFactory.create(any())).thenReturn(transporter); + TranslationConfiguration translatorConfiguration = + TranslationConfiguration.builder() + .translationProviderFactory(transporterFactory) + .translationCache(translationCache) + .build(); - List translatableTextList = new ArrayList<>(); - translatableTextList.add(new TranslatableText("Blume")); - translatableTextList.add(new TranslatableText("Blau")); + List translatableTextList = new ArrayList<>(); + translatableTextList.add(new TranslatableText("Blume")); + translatableTextList.add(new TranslatableText("Blau")); - TranslatableTextListTranslator translator = TranslatableTextListTranslator.builder() - .translatorConfiguration(translatorConfiguration) - .build(); + TranslatableTextListTranslator translator = + TranslatableTextListTranslator.builder() + .translatorConfiguration(translatorConfiguration) + .build(); - TranslationLanguage language = TranslationLanguage.builder() - .source("de") - .target("en") - .build(); + TranslationLanguage language = TranslationLanguage.builder().source("de").target("en").build(); - TranslationParameter parameter = TranslationParameter.builder() - .language(language) - .providerType(SupportedProvider.LIBRE_TRANSLATE) - .build(); + TranslationParameter parameter = + TranslationParameter.builder() + .language(language) + .providerType(SupportedProvider.LIBRE_TRANSLATE) + .build(); - translator.translate(parameter, translatableTextList); + translator.translate(parameter, translatableTextList); - assertEquals("Flowers", translatableTextList.get(0).getTargetText(), "unexpected translation"); - assertEquals("Blue", translatableTextList.get(1).getTargetText(), "unexpected translation"); - } + assertEquals("Flowers", translatableTextList.get(0).getTargetText(), "unexpected translation"); + assertEquals("Blue", translatableTextList.get(1).getTargetText(), "unexpected translation"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/TranslatableTextNodeTest.java b/src/test/java/com/sitepark/translate/translator/TranslatableTextNodeTest.java index d244d22..52d3feb 100644 --- a/src/test/java/com/sitepark/translate/translator/TranslatableTextNodeTest.java +++ b/src/test/java/com/sitepark/translate/translator/TranslatableTextNodeTest.java @@ -5,75 +5,79 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; class TranslatableTextNodeTest { - @Test - void testCreateWithNullParent() { - TextNode textNode = Mockito.mock(TextNode.class); - assertThrows(NullPointerException.class, () -> { - TranslatableTextNode.create(null, "key", textNode); - }); - } + @Test + void testCreateWithNullParent() { + TextNode textNode = Mockito.mock(TextNode.class); + assertThrows( + NullPointerException.class, + () -> { + TranslatableTextNode.create(null, "key", textNode); + }); + } - @Test - void testCreateWithNullKey() { - JsonNode jsonNode = Mockito.mock(JsonNode.class); - TextNode textNode = Mockito.mock(TextNode.class); - assertThrows(NullPointerException.class, () -> { - TranslatableTextNode.create(jsonNode, null, textNode); - }); - } + @Test + void testCreateWithNullKey() { + JsonNode jsonNode = Mockito.mock(JsonNode.class); + TextNode textNode = Mockito.mock(TextNode.class); + assertThrows( + NullPointerException.class, + () -> { + TranslatableTextNode.create(jsonNode, null, textNode); + }); + } - @Test - void testCreateWithNullNode() { - JsonNode jsonNode = Mockito.mock(JsonNode.class); - assertThrows(NullPointerException.class, () -> { - TranslatableTextNode.create(jsonNode, "key", null); - }); - } + @Test + void testCreateWithNullNode() { + JsonNode jsonNode = Mockito.mock(JsonNode.class); + assertThrows( + NullPointerException.class, + () -> { + TranslatableTextNode.create(jsonNode, "key", null); + }); + } - @Test - void testWithObjectNodet() { - JsonNode jsonNode = Mockito.mock(ObjectNode.class); - TextNode textNode = Mockito.mock(TextNode.class); - when(textNode.asText()).thenReturn("Text"); - TranslatableTextNode translatableTextNode = - TranslatableTextNode.create(jsonNode, "key", textNode); + @Test + void testWithObjectNodet() { + JsonNode jsonNode = Mockito.mock(ObjectNode.class); + TextNode textNode = Mockito.mock(TextNode.class); + when(textNode.asText()).thenReturn("Text"); + TranslatableTextNode translatableTextNode = + TranslatableTextNode.create(jsonNode, "key", textNode); - assertThat( - "unexpected instance", - translatableTextNode, - instanceOf(TranslatableTextNodeInObject.class)); - } + assertThat( + "unexpected instance", + translatableTextNode, + instanceOf(TranslatableTextNodeInObject.class)); + } - @Test - void testWithArrayNode() { - JsonNode jsonNode = Mockito.mock(ArrayNode.class); - TextNode textNode = Mockito.mock(TextNode.class); - when(textNode.asText()).thenReturn("Text"); - TranslatableTextNode translatableTextNode = - TranslatableTextNode.create(jsonNode, 1, textNode); + @Test + void testWithArrayNode() { + JsonNode jsonNode = Mockito.mock(ArrayNode.class); + TextNode textNode = Mockito.mock(TextNode.class); + when(textNode.asText()).thenReturn("Text"); + TranslatableTextNode translatableTextNode = TranslatableTextNode.create(jsonNode, 1, textNode); - assertThat( - "unexpected instance", - translatableTextNode, - instanceOf(TranslatableTextNodeOfArray.class)); - } + assertThat( + "unexpected instance", translatableTextNode, instanceOf(TranslatableTextNodeOfArray.class)); + } - @Test - void testWithInvalidNode() { - JsonNode jsonNode = Mockito.mock(JsonNode.class); - TextNode textNode = Mockito.mock(TextNode.class); - assertThrows(IllegalArgumentException.class, () -> { - TranslatableTextNode.create(jsonNode, 1, textNode); - }); - } + @Test + void testWithInvalidNode() { + JsonNode jsonNode = Mockito.mock(JsonNode.class); + TextNode textNode = Mockito.mock(TextNode.class); + assertThrows( + IllegalArgumentException.class, + () -> { + TranslatableTextNode.create(jsonNode, 1, textNode); + }); + } } diff --git a/src/test/java/com/sitepark/translate/translator/TranslatableTextTest.java b/src/test/java/com/sitepark/translate/translator/TranslatableTextTest.java index 6134c64..9c0a40b 100644 --- a/src/test/java/com/sitepark/translate/translator/TranslatableTextTest.java +++ b/src/test/java/com/sitepark/translate/translator/TranslatableTextTest.java @@ -2,39 +2,37 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.Test; - import com.sitepark.translate.Format; +import org.junit.jupiter.api.Test; class TranslatableTextTest { - @Test - void testAutoDetectPlainTextConstructor() { - TranslatableText text = new TranslatableText("plain text"); - assertEquals(Format.TEXT, text.getFormat(), "format should be plain text"); - } - - @Test - void testAutoDetectHtmlConstructor() { - TranslatableText text = new TranslatableText("html text"); - assertEquals(Format.HTML, text.getFormat(), "format should be html"); - } - - @Test - void testAutoDetectPlaceholderConstructor() { - TranslatableText text = new TranslatableText("text with placeholder ${name}"); - assertEquals(Format.HTML, text.getFormat(), "format should be html"); - } - - @Test - void testToHash() { - String hash = TranslatableText.toHash( - "Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem."); - assertEquals( - "06e89dcd3a965b8b6c1267fbe1daf3054424f882747aed7a56ebbb5999f8e165", - hash, - "unexprected hash"); - } - - + @Test + void testAutoDetectPlainTextConstructor() { + TranslatableText text = new TranslatableText("plain text"); + assertEquals(Format.TEXT, text.getFormat(), "format should be plain text"); + } + + @Test + void testAutoDetectHtmlConstructor() { + TranslatableText text = new TranslatableText("html text"); + assertEquals(Format.HTML, text.getFormat(), "format should be html"); + } + + @Test + void testAutoDetectPlaceholderConstructor() { + TranslatableText text = new TranslatableText("text with placeholder ${name}"); + assertEquals(Format.HTML, text.getFormat(), "format should be html"); + } + + @Test + void testToHash() { + String hash = + TranslatableText.toHash( + "Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem."); + assertEquals( + "06e89dcd3a965b8b6c1267fbe1daf3054424f882747aed7a56ebbb5999f8e165", + hash, + "unexprected hash"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/TranslationFileCacheTest.java b/src/test/java/com/sitepark/translate/translator/TranslationFileCacheTest.java index 590513b..e5030ad 100644 --- a/src/test/java/com/sitepark/translate/translator/TranslationFileCacheTest.java +++ b/src/test/java/com/sitepark/translate/translator/TranslationFileCacheTest.java @@ -2,38 +2,34 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; - import org.junit.jupiter.api.Test; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") class TranslationFileCacheTest { - @Test - void test() throws Exception { - Path file = Paths.get("target/test/lang/en/.cache-file"); - Files.createDirectories(file.getParent()); - TranslationFileCache cache = new TranslationFileCache(file); + @Test + void test() throws Exception { + Path file = Paths.get("target/test/lang/en/.cache-file"); + Files.createDirectories(file.getParent()); + TranslationFileCache cache = new TranslationFileCache(file); - List list = new ArrayList<>(); - TranslatableText text = new TranslatableText("Hallo Welt"); - text.setTargetText("Hello World"); - list.add(text); + List list = new ArrayList<>(); + TranslatableText text = new TranslatableText("Hallo Welt"); + text.setTargetText("Hello World"); + list.add(text); - cache.update(list); - cache.store(); + cache.update(list); + cache.store(); - String expected = "{\"-972308576\":\"Hello World\"}"; - assertEquals( - expected, - Files.readString(file, StandardCharsets.UTF_8), - "unexpected file content"); - } + String expected = "{\"-972308576\":\"Hello World\"}"; + assertEquals( + expected, Files.readString(file, StandardCharsets.UTF_8), "unexpected file content"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/UnifiedSourceTextTest.java b/src/test/java/com/sitepark/translate/translator/UnifiedSourceTextTest.java index 460d183..57e74cf 100644 --- a/src/test/java/com/sitepark/translate/translator/UnifiedSourceTextTest.java +++ b/src/test/java/com/sitepark/translate/translator/UnifiedSourceTextTest.java @@ -7,77 +7,52 @@ @SuppressWarnings("PMD.AvoidDuplicateLiterals") class UnifiedSourceTextTest { - @Test - void testGetSourceTextOnlyWithDifferentText() { - String[] sourceText = new String[] {"Hallo", "Welt", "ich", "grüße", "dich"}; - UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); - assertArrayEquals( - new String[] {"Hallo", "Welt", "ich", "grüße", "dich"}, - unifiedSourceText.getSourceText(), - "should have no changes" - ); - } - - @Test - void testExpandTranslationOnlyWithDifferentText() { - String[] sourceText = new String[] {"Hallo", "Welt", "ich", "grüße", "dich"}; - UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); - - String[] translationText = new String[] {"Hello", "world", "i", "greet", "you"}; - assertArrayEquals( - translationText, - unifiedSourceText.expandTranslation(translationText), - "wrong expanded"); - } - - @Test - void testGetSourceTextWithEqualsText() { - String[] sourceText = new String[] {"Hallo", "Welt", "Hallo", "Welt"}; - UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); - assertArrayEquals( - new String[] {"Hallo", "Welt"}, - unifiedSourceText.getSourceText(), - "should be unified"); - } - - @Test - void testExpandTranslationWithEqualsText() { - String[] sourceText = new String[] { - "Eins", - "Eins", - "Zwei", - "Eins", - "Zwei", - "Zwei", - "Drei", - "Vier", - "Fünf", - "Zwei", - "Fünf", - "Drei", - }; - UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); - - String[] translationText = new String[] {"One", "Two", "Three", "Four", "Five"}; - String[] expectedTranslationText = new String[] { - "One", - "One", - "Two", - "One", - "Two", - "Two", - "Three", - "Four", - "Five", - "Two", - "Five", - "Three", - }; - - assertArrayEquals( - expectedTranslationText, - unifiedSourceText.expandTranslation(translationText), - "wrong expanded"); - } - -} \ No newline at end of file + @Test + void testGetSourceTextOnlyWithDifferentText() { + String[] sourceText = new String[] {"Hallo", "Welt", "ich", "grüße", "dich"}; + UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); + assertArrayEquals( + new String[] {"Hallo", "Welt", "ich", "grüße", "dich"}, + unifiedSourceText.getSourceText(), + "should have no changes"); + } + + @Test + void testExpandTranslationOnlyWithDifferentText() { + String[] sourceText = new String[] {"Hallo", "Welt", "ich", "grüße", "dich"}; + UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); + + String[] translationText = new String[] {"Hello", "world", "i", "greet", "you"}; + assertArrayEquals( + translationText, unifiedSourceText.expandTranslation(translationText), "wrong expanded"); + } + + @Test + void testGetSourceTextWithEqualsText() { + String[] sourceText = new String[] {"Hallo", "Welt", "Hallo", "Welt"}; + UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); + assertArrayEquals( + new String[] {"Hallo", "Welt"}, unifiedSourceText.getSourceText(), "should be unified"); + } + + @Test + void testExpandTranslationWithEqualsText() { + String[] sourceText = + new String[] { + "Eins", "Eins", "Zwei", "Eins", "Zwei", "Zwei", "Drei", "Vier", "Fünf", "Zwei", "Fünf", + "Drei", + }; + UnifiedSourceText unifiedSourceText = new UnifiedSourceText(sourceText); + + String[] translationText = new String[] {"One", "Two", "Three", "Four", "Five"}; + String[] expectedTranslationText = + new String[] { + "One", "One", "Two", "One", "Two", "Two", "Three", "Four", "Five", "Two", "Five", "Three", + }; + + assertArrayEquals( + expectedTranslationText, + unifiedSourceText.expandTranslation(translationText), + "wrong expanded"); + } +} diff --git a/src/test/java/com/sitepark/translate/translator/entity/DecoderTest.java b/src/test/java/com/sitepark/translate/translator/entity/DecoderTest.java index 314ebb4..d2a5799 100644 --- a/src/test/java/com/sitepark/translate/translator/entity/DecoderTest.java +++ b/src/test/java/com/sitepark/translate/translator/entity/DecoderTest.java @@ -6,10 +6,11 @@ class DecoderTest { - @Test - void test() { - String s = Decoder.decode("Ein Text mit ${text}."); - assertEquals("Ein Text mit ${text}.", s, "Unexpected text"); - } - + @Test + void test() { + String s = + Decoder.decode( + "Ein Text mit ${text}."); + assertEquals("Ein Text mit ${text}.", s, "Unexpected text"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/entity/EncoderTest.java b/src/test/java/com/sitepark/translate/translator/entity/EncoderTest.java index e33443e..556618a 100644 --- a/src/test/java/com/sitepark/translate/translator/entity/EncoderTest.java +++ b/src/test/java/com/sitepark/translate/translator/entity/EncoderTest.java @@ -6,13 +6,12 @@ class EncoderTest { - @Test - void test() { - String s = Encoder.encode("Ein Text mit ${text}."); - assertEquals( - "Ein Text mit ${text}.", - s, - "Unexpected encoding"); - } - + @Test + void test() { + String s = Encoder.encode("Ein Text mit ${text}."); + assertEquals( + "Ein Text mit ${text}.", + s, + "Unexpected encoding"); + } } diff --git a/src/test/java/com/sitepark/translate/translator/entity/ScannerTest.java b/src/test/java/com/sitepark/translate/translator/entity/ScannerTest.java index 8366323..312aaa3 100644 --- a/src/test/java/com/sitepark/translate/translator/entity/ScannerTest.java +++ b/src/test/java/com/sitepark/translate/translator/entity/ScannerTest.java @@ -3,114 +3,112 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @SuppressWarnings({ - "PMD.JUnitTestContainsTooManyAsserts", - "PMD.JUnitAssertionsShouldIncludeMessage", + "PMD.JUnitTestContainsTooManyAsserts", + "PMD.JUnitAssertionsShouldIncludeMessage", }) class ScannerTest { - @Test - void testText() { - Scanner scanner = new Scanner("abc"); - List token = scanner.scanTokens(); - - Token t1 = token.get(0); - Token t2 = token.get(1); - - assertEquals(TokenType.STRING, t1.type); - assertEquals("abc", t1.lexeme); - assertEquals(TokenType.EOF, t2.type); - } - - @Test - void testStartEntity() { - Scanner scanner = new Scanner("${{"); - List token = scanner.scanTokens(); - - Token t1 = token.get(0); - Token t2 = token.get(1); - Token t3 = token.get(2); - - assertEquals(TokenType.STRING, t1.type); - assertEquals("${", t1.lexeme); - assertEquals(TokenType.STRING, t2.type); - assertEquals("{", t2.lexeme); - assertEquals(TokenType.EOF, t3.type); - } - - @Test - void testEndEntity() { - Scanner scanner = new Scanner("}}"); - List token = scanner.scanTokens(); - - Token t1 = token.get(0); - Token t2 = token.get(1); - assertEquals(TokenType.STRING, t1.type); - assertEquals("}}", t1.lexeme); - assertEquals(TokenType.EOF, t2.type); - } - - @Test - void testString() { - Scanner scanner = new Scanner("Ein String"); - List token = scanner.scanTokens(); - - Token t1 = token.get(0); - Token t2 = token.get(1); - assertEquals(TokenType.STRING, t1.type); - assertEquals("Ein String", t1.lexeme); - assertEquals(TokenType.EOF, t2.type); - } - - @Test - @Disabled - void testStringWithEntitiesWithAmp() { - Scanner scanner = new Scanner("Ein String & ${a} {0}"); - List token = scanner.scanTokens(); - - Token t1 = token.get(0); - Token t2 = token.get(1); - Token t3 = token.get(2); - Token t4 = token.get(3); - Token t5 = token.get(4); - Token t6 = token.get(5); - - assertEquals(TokenType.STRING, t1.type); - assertEquals("Ein String ", t1.lexeme); - assertEquals(TokenType.ENTITY, t2.type); - assertEquals("&", t2.lexeme); - assertEquals(TokenType.STRING, t3.type); - assertEquals(" ", t3.lexeme); - assertEquals(TokenType.ENTITY, t4.type); - assertEquals("${a}", t4.lexeme); - assertEquals(TokenType.STRING, t5.type); - assertEquals(" ", t5.lexeme); - assertEquals(TokenType.ENTITY, t6.type); - assertEquals("{0}", t6.lexeme); - } - - @Test - void testStringWithEntities() { - Scanner scanner = new Scanner("Ein String & ${a} {0}"); - List token = scanner.scanTokens(); - - Token t1 = token.get(0); - Token t2 = token.get(1); - Token t3 = token.get(2); - Token t4 = token.get(3); - - assertEquals(TokenType.STRING, t1.type); - assertEquals("Ein String & ", t1.lexeme); - assertEquals(TokenType.ENTITY, t2.type); - assertEquals("${a}", t2.lexeme); - assertEquals(TokenType.STRING, t3.type); - assertEquals(" ", t3.lexeme); - assertEquals(TokenType.ENTITY, t4.type); - assertEquals("{0}", t4.lexeme); - } - + @Test + void testText() { + Scanner scanner = new Scanner("abc"); + List token = scanner.scanTokens(); + + Token t1 = token.get(0); + Token t2 = token.get(1); + + assertEquals(TokenType.STRING, t1.type); + assertEquals("abc", t1.lexeme); + assertEquals(TokenType.EOF, t2.type); + } + + @Test + void testStartEntity() { + Scanner scanner = new Scanner("${{"); + List token = scanner.scanTokens(); + + Token t1 = token.get(0); + Token t2 = token.get(1); + Token t3 = token.get(2); + + assertEquals(TokenType.STRING, t1.type); + assertEquals("${", t1.lexeme); + assertEquals(TokenType.STRING, t2.type); + assertEquals("{", t2.lexeme); + assertEquals(TokenType.EOF, t3.type); + } + + @Test + void testEndEntity() { + Scanner scanner = new Scanner("}}"); + List token = scanner.scanTokens(); + + Token t1 = token.get(0); + Token t2 = token.get(1); + assertEquals(TokenType.STRING, t1.type); + assertEquals("}}", t1.lexeme); + assertEquals(TokenType.EOF, t2.type); + } + + @Test + void testString() { + Scanner scanner = new Scanner("Ein String"); + List token = scanner.scanTokens(); + + Token t1 = token.get(0); + Token t2 = token.get(1); + assertEquals(TokenType.STRING, t1.type); + assertEquals("Ein String", t1.lexeme); + assertEquals(TokenType.EOF, t2.type); + } + + @Test + @Disabled + void testStringWithEntitiesWithAmp() { + Scanner scanner = new Scanner("Ein String & ${a} {0}"); + List token = scanner.scanTokens(); + + Token t1 = token.get(0); + Token t2 = token.get(1); + Token t3 = token.get(2); + Token t4 = token.get(3); + Token t5 = token.get(4); + Token t6 = token.get(5); + + assertEquals(TokenType.STRING, t1.type); + assertEquals("Ein String ", t1.lexeme); + assertEquals(TokenType.ENTITY, t2.type); + assertEquals("&", t2.lexeme); + assertEquals(TokenType.STRING, t3.type); + assertEquals(" ", t3.lexeme); + assertEquals(TokenType.ENTITY, t4.type); + assertEquals("${a}", t4.lexeme); + assertEquals(TokenType.STRING, t5.type); + assertEquals(" ", t5.lexeme); + assertEquals(TokenType.ENTITY, t6.type); + assertEquals("{0}", t6.lexeme); + } + + @Test + void testStringWithEntities() { + Scanner scanner = new Scanner("Ein String & ${a} {0}"); + List token = scanner.scanTokens(); + + Token t1 = token.get(0); + Token t2 = token.get(1); + Token t3 = token.get(2); + Token t4 = token.get(3); + + assertEquals(TokenType.STRING, t1.type); + assertEquals("Ein String & ", t1.lexeme); + assertEquals(TokenType.ENTITY, t2.type); + assertEquals("${a}", t2.lexeme); + assertEquals(TokenType.STRING, t3.type); + assertEquals(" ", t3.lexeme); + assertEquals(TokenType.ENTITY, t4.type); + assertEquals("{0}", t4.lexeme); + } }