Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions HomeTaskWeek5.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
79 changes: 79 additions & 0 deletions src/Translator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import source.URLSourceProvider;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
* Provides utilities for translating texts to russian language.<br/>
* Uses Yandex Translate API, more information at <a href="http://api.yandex.ru/translate/">http://api.yandex.ru/translate/</a><br/>
* Depends on {@link URLSourceProvider} for accessing Yandex Translator API service
*/
public class Translator {
private URLSourceProvider urlSourceProvider;
/**
* Yandex Translate API key could be obtained at <a href="http://api.yandex.ru/key/form.xml?service=trnsl">http://api.yandex.ru/key/form.xml?service=trnsl</a>
* to do that you have to be authorized.
*/
private static final String YANDEX_API_KEY = "trnsl.1.1.20151117T201458Z.c036bb87a9e52141.8f17cc056e436711480a5d13ba40f4b0c91ef3e8";
private static final String TRANSLATION_DIRECTION = "ru";

public Translator(URLSourceProvider urlSourceProvider) {
this.urlSourceProvider = urlSourceProvider;
}

/**
* Translates text to russian language
* @param original text to translate
* @return translated text
* @throws IOException
*/
public String translate(String original) throws Exception {
String translated = urlSourceProvider.load(prepareURL(original));
return parseContent(translated);
}

/**
* Prepares URL to invoke Yandex Translate API service for specified text
* @param text to translate
* @return url for translation specified text
*/
private String prepareURL(String text) throws Exception {
return "https://translate.yandex.net/api/v1.5/tr/translate?key=" + YANDEX_API_KEY + "&text=" + encodeText(text) + "&lang=" + TRANSLATION_DIRECTION;
}

/**
* Parses content returned by Yandex Translate API service. Removes all tags and system texts. Keeps only translated text.
* @param content that was received from Yandex Translate API by invoking prepared URL
* @return translated text
*/
private String parseContent(String content){
Pattern pattern = Pattern.compile("<text>(.*)</text>",Pattern.DOTALL);
Matcher matcher = pattern.matcher(content);
matcher.find();
return matcher.group(1);
}

/**
* Encodes text that need to be translated to put it as URL parameter
* @param text to be translated
* @return encoded text
*/
private String encodeText(String text)throws Exception{
try {
return URLEncoder.encode(text, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
throw new Exception();
}
}
34 changes: 34 additions & 0 deletions src/TranslatorController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import source.SourceLoader;
import source.URLSourceProvider;

import java.io.IOException;
import java.util.Scanner;

public class TranslatorController {

public static void main(String[] args) throws IOException {
//initialization
SourceLoader sourceLoader = new SourceLoader();
Translator translator = new Translator(new URLSourceProvider());

Scanner scanner = new Scanner(System.in);
String command = scanner.next();
while(!"exit".equals(command)) {

try {
String source = sourceLoader.loadSource(command);
String translation = translator.translate(source);

System.out.println("Original: " + source);
System.out.println("Translation: " + translation);

command = scanner.next();
}
catch (Exception e) {
System.out.println("Error message: " + e.getMessage());
}

}

}
}
40 changes: 40 additions & 0 deletions src/source/FileSourceProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package source;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
/**
* Implementation for loading content from local file system.
* This implementation supports absolute paths to local file system without specifying file:// protocol.
* Examples c:/1.txt or d:/pathToFile/file.txt
*/
public class FileSourceProvider implements SourceProvider {

@Override
public boolean isAllowed(String pathToSource) {
Path path = Paths.get(pathToSource);
if(Files.exists(path))
if(Files.isReadable(path))
return true;
return false;
}

@Override
public String load(String pathToSource) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(pathToSource));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line !=null) {
sb.append(line + "\n");
line = br.readLine();
}
return sb.toString();
}
finally {
br.close();
}

}
}
26 changes: 26 additions & 0 deletions src/source/SourceLoader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package source;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* SourceLoader should contains all implementations of SourceProviders to be able to load different sources.
*/
public class SourceLoader {
private List<SourceProvider> sourceProviders = new ArrayList<>();

public SourceLoader() {
sourceProviders.add(new FileSourceProvider());
sourceProviders.add(new URLSourceProvider());
}

public String loadSource(String pathToSource) throws IOException {
for(SourceProvider provider : sourceProviders) {
if(provider.isAllowed(pathToSource)) {
return provider.load(pathToSource);
}
}
throw new IOException("Text was not found");
}
}
23 changes: 23 additions & 0 deletions src/source/SourceProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package source;

import java.io.IOException;

/**
* Base interface to access different sources.</br>
* isAllowed method should protect and help to determine can we load resource for specified path ot not.
*/
public interface SourceProvider {
/**
* Determines can current implementation load source by provided pathToSource
* @param pathToSource absolute path to the source
* @return whether current implementation load the source for specified pathToSource
*/
public boolean isAllowed(String pathToSource);

/**
* Loads text from specified path.
* @param pathToSource absolute path to the source
* @return content of the source for specified pathToSource
*/
public String load(String pathToSource) throws IOException;
}
49 changes: 49 additions & 0 deletions src/source/URLSourceProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package source;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* Implementation for loading content from specified URL.<br/>
* Valid paths to load are http://someurl.com, https://secureurl.com, ftp://frpurl.com etc.
*/
public class URLSourceProvider implements SourceProvider {

@Override
public boolean isAllowed(String pathToSource) {
try{
URL url = new URL(pathToSource);
return true;
}catch(MalformedURLException e) {
return false;
}

}

@Override
public String load(String pathToSource) throws IOException {
URL url = new URL(pathToSource);
URLConnection urlConnection = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
try
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line + "\n");
line = br.readLine();
}
return sb.toString();
}
finally {
br.close();
}
}


}