「みんなの自動翻訳API」をJavaで使う

参考:みんなの自動翻訳 WebAPI

参考ソースは下に続きます。

Main.java

package minhon_client;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import minhon.TranslateFile;

public class Main {
    private static final String USERNAME = "";
    private static final String KEY = "";
    private static final String SECRET = "";

    private static int getTranslateState(TranslateFile tf, String pid) {
    		String translate_result;
	    	translate_result = tf.getStatus(pid);
//	    	System.out.println(translate_result);
	
	    	try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
	    	    	InputSource is = new InputSource(new StringReader(translate_result));
	    	    	Document document = builder.parse(is);
	    	    String state_str = "";
	    	    state_str = document.getElementsByTagName("state").item(0).getTextContent();
	    	    int state = Integer.parseInt(state_str);
	    	    return state;
	    	} catch (Exception e) {
	    		return -2;
	    	}
    }
    
	public static void main(String[] args) throws Exception {
		String file_path = args[0];
		String translate_result = "";
		Boolean result = false;


		/* 文字列の翻訳 */
//		TranslateLine tl = new TranslateLine(USERNAME, KEY, SECRET);
//		tl.translate("こんにちわ");

		/* APIライブラリの初期化 */
//		minhon.Client c = new minhon.Client(USERNAME, KEY, SECRET);

		/* ファイルの翻訳 */
//		result = c.registTranslateFile(file_path);
//		System.out.println(result);

//		result = c.listTranslateFile();
//		System.out.println(result);
		
//		translate_result = c.getTranslateFile("66834");
//		System.out.println(translate_result);

		// 翻訳ファイルの登録
		TranslateFile tf = new TranslateFile(USERNAME, KEY, SECRET);
		translate_result = tf.regist(file_path);
		System.out.println(translate_result);
		
		 // DocumentBuilderFactory インスタンスを取得
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        
        // StringReaderを使ってXML文字列を読み込む
        InputSource is = new InputSource(new StringReader(translate_result));
        
        // InputSourceからDocumentオブジェクトを生成
        Document document = builder.parse(is);
        String pid = document.getElementsByTagName("pid").item(0).getTextContent();
        	System.out.println("pid:" + pid);
        
        	
        	// 翻訳ファイルのステータスを取得
        	System.out.println("get state of pid:" + pid);
        	int state = 1;
        	int wait_time_ms = 5000;
        	int count_time = 0;
        	while(state!=2) {
        		if (120000 < count_time) {
        			System.out.println("timeout pid:" + pid);
        			break;
        		}
            	Thread.sleep(wait_time_ms);
            state = getTranslateState(tf, pid);
            GregorianCalendar cal = new GregorianCalendar();
        		System.out.println("state pid:" + pid
        				+ " " + "state:" + state
        				+ " " + cal.get(cal.HOUR_OF_DAY) + ":" + cal.get(cal.MINUTE) + ":" + cal.get(cal.SECOND));
            count_time += wait_time_ms;
        	}
        	
        	System.out.println("complete pid:" + pid);

        	// 翻訳ファイルのダウンロード
        	System.out.println("get the file of pid:" + pid);
        	translate_result = tf.download(pid);
        	System.out.println("\"\"\"\n" + translate_result + "\"\"\"");
        	File file = new File(file_path);
        	String new_path = file.getParent() + "/" + file.getName()+"_translated.txt";
        	BufferedWriter fout = new BufferedWriter(new FileWriter(new_path, true));
        	fout.write(translate_result);
        	fout.close();

        	System.out.println("download the file of pid:" + pid + " " + new_path);
	}
	
}

TranslateFile.java

package minhon;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.oauth.OAuth20Service;

public class TranslateFile {
    private String NAME   = ""; // ログインID
    private String KEY    = ""; // API key
    private String SECRET = ""; // API secret
    private static final String URL    = "https://mt-auto-minhon-mlt.ucri.jgn-x.jp"; // 基底URL (https://xxx.jpまでを入力)

    private static final String API_NAME  = "trans_file"; // API名 (https:#xxx.jp/api/mt/generalNT_ja_en/ の場合は、"mt")
    private static final String API_PARAM = "set"; // API値 (https:#xxx.jp/api/mt/generalNT_ja_en/ の場合は、"generalNT_ja_en")

    public TranslateFile(String name, String key, String secret) {
    		this.NAME = name;
    		this.KEY = key;
    		this.SECRET = secret;
    }

    
    public String regist(String file_path) {
        final OAuth20Service service = new ServiceBuilder(KEY)
            .apiSecret(SECRET)
            .build(new DefaultApi20() {
                @Override
                public String getAccessTokenEndpoint() {
                    return URL + "/oauth2/token.php";
                }

                @Override
                protected String getAuthorizationBaseUrl() {
                    return null;
                }
            });

        try {
            final OAuth2AccessToken accessToken = service.getAccessTokenClientCredentialsGrant();

            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();

                builder.addTextBody("access_token", accessToken.getAccessToken(), ContentType.TEXT_PLAIN); // アクセストークン
                builder.addTextBody("key", KEY, ContentType.TEXT_PLAIN);                                   // API key
                builder.addTextBody("name", NAME, ContentType.TEXT_PLAIN);                                 // ログインID
                builder.addTextBody("api_name", API_NAME, ContentType.TEXT_PLAIN);                         // API名
                builder.addTextBody("api_param", "set", ContentType.TEXT_PLAIN);                       // API値
                builder.addTextBody("mt_id", "generalNT_ja_en", ContentType.TEXT_PLAIN);
                // builder.addTextBody("xxx", "xxx", ContentType.TEXT_PLAIN);                              // 以下、APIごとのパラメータ

	    			File file = new File(file_path);
	    			File f = File.createTempFile(file.getName(), ".txt");
	    			BufferedReader in = new BufferedReader(new FileReader(file_path));
	    			BufferedWriter out_tmp = new BufferedWriter(new FileWriter(f));
	    			String str;
	    			while((str=in.readLine())!=null) {
	    				out_tmp.write(str + "\n");
	    			}
	    			in.close();
	    			out_tmp.close();
                builder.addTextBody("title", f.getName(), ContentType.TEXT_PLAIN);
                builder.addBinaryBody("file", f, ContentType.APPLICATION_OCTET_STREAM, f.getName());
                
                HttpEntity entity = builder.build();

                HttpPost httpPost = new HttpPost(URL + "/api/?");
                httpPost.setEntity(entity);
                BufferedInputStream bis = null;

                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
	                	InputStream respBodyStream = response.getEntity().getContent();
	    				int respStatus = response.getStatusLine().getStatusCode();
	    				bis = new BufferedInputStream(respBodyStream);
	    				System.out.println("Http response status: " + respStatus);
	    				String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                    return responseString;
    				}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }
    
    
    public String getStatus(String pid) {
        final OAuth20Service service = new ServiceBuilder(KEY)
            .apiSecret(SECRET)
            .build(new DefaultApi20() {
                @Override
                public String getAccessTokenEndpoint() {
                    return URL + "/oauth2/token.php";
                }

                @Override
                protected String getAuthorizationBaseUrl() {
                    return null;
                }
            });

        try {
            final OAuth2AccessToken accessToken = service.getAccessTokenClientCredentialsGrant();

            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();

                builder.addTextBody("access_token", accessToken.getAccessToken(), ContentType.TEXT_PLAIN); // アクセストークン
                builder.addTextBody("key", KEY, ContentType.TEXT_PLAIN);                                   // API key
                builder.addTextBody("name", NAME, ContentType.TEXT_PLAIN);                                 // ログインID
                builder.addTextBody("api_name", API_NAME, ContentType.TEXT_PLAIN);                         // API名
                builder.addTextBody("api_param", "status", ContentType.TEXT_PLAIN);                       // API値
                builder.addTextBody("pid", pid, ContentType.TEXT_PLAIN);                              // 以下、APIごとのパラメータ

                HttpEntity entity = builder.build();

                HttpPost httpPost = new HttpPost(URL + "/api/?");
                httpPost.setEntity(entity);

                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                    return responseString;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "error";
    }


    public String download(String pid) {
        final OAuth20Service service = new ServiceBuilder(KEY)
            .apiSecret(SECRET)
            .build(new DefaultApi20() {
                @Override
                public String getAccessTokenEndpoint() {
                    return URL + "/oauth2/token.php";
                }

                @Override
                protected String getAuthorizationBaseUrl() {
                    return null;
                }
            });

        try {
            final OAuth2AccessToken accessToken = service.getAccessTokenClientCredentialsGrant();

            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();

                builder.addTextBody("access_token", accessToken.getAccessToken(), ContentType.TEXT_PLAIN); // アクセストークン
                builder.addTextBody("key", KEY, ContentType.TEXT_PLAIN);                                   // API key
                builder.addTextBody("name", NAME, ContentType.TEXT_PLAIN);                                 // ログインID
                builder.addTextBody("api_name", API_NAME, ContentType.TEXT_PLAIN);                         // API名
                builder.addTextBody("api_param", "get", ContentType.TEXT_PLAIN);                       // API値
                builder.addTextBody("pid", pid, ContentType.TEXT_PLAIN);                              // 以下、APIごとのパラメータ

                HttpEntity entity = builder.build();

                HttpPost httpPost = new HttpPost(URL + "/api/?");
                httpPost.setEntity(entity);

                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                    return responseString;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "error";
    }
    
}

コメントをどうぞ

メールアドレスが公開されることはありません。 が付いている欄は必須項目です