Skip to content
SearchUCD.java 7.14 KiB
Newer Older
/* 
 * _____________________________________________________________________________
 * 
 * INAF - OATS National Institute for Astrophysics - Astronomical Observatory of
 * Trieste INAF - IA2 Italian Center for Astronomical Archives
 * _____________________________________________________________________________
 * 
 * Copyright (C) 2016 Istituto Nazionale di Astrofisica
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License Version 3 as published by the
 * Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
import ari.ucidy.UCD;
import ari.ucidy.UCDParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Collection of static methods for accessing to the UCD REST service and
 * validating custom UCD.
 *
 * @author Sonia Zorba {@literal <zorba at oats.inaf.it>}
 */
public class SearchUCD {

    private static final String UCD_SERVICE_URL;
    private static final String UCD_NOT_FOUND = "**** Could not find UCD ****";

    static {
        try {
            Properties prop = new Properties();
            try (InputStream in = SearchUCD.class.getClassLoader().getResourceAsStream("webapp.properties")) {
                prop.load(in);
            }
            UCD_SERVICE_URL = prop.getProperty("ucd_service_url");
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Unable to load UCD service URL from webapp.properties configuration!");
        }
    }

    private static String encodeText(String searchText) throws UCDServiceException {
        try {
            return URLEncoder.encode(searchText, "UTF-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new UCDServiceException("Error while encoding input text");
        }
    }

    public static String assign(String searchText) throws UCDServiceException {
        searchText = encodeText(searchText);
        String urlStr = UCD_SERVICE_URL + "assign?value=" + searchText;

        try {
            URL urlAssign = new URL(urlStr);
            HttpURLConnection connectionAssign = (HttpURLConnection) urlAssign.openConnection();

            int responseCodeAssign = connectionAssign.getResponseCode();
            if (responseCodeAssign == 200) {
                BufferedReader br;
                String line, response = "";

                br = new BufferedReader(new InputStreamReader(connectionAssign.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
                if (response.equals(UCD_NOT_FOUND)) {
                    return null;
                }

                return response;
            }
            throw new UCDServiceException("Server responded with a status of " + responseCodeAssign);
        } catch (MalformedURLException e) {
            throw new UCDServiceException("Malformed url: " + urlStr);
        } catch (IOException e) {
            throw new UCDServiceException("Error while reading server response");
        }
    }

    public static List<UCDInfo> suggest(String searchText) throws UCDServiceException {
        searchText = encodeText(searchText);
        String urlStr = UCD_SERVICE_URL + "suggest?value=" + searchText;

        try {
            URL urlSuggest = new URL(urlStr);

            HttpURLConnection connectionSuggest = (HttpURLConnection) urlSuggest.openConnection();

            int responseCodeSuggest = connectionSuggest.getResponseCode();
            if (responseCodeSuggest == 200) {
                List<UCDInfo> resultList = new ArrayList<>();
                BufferedReader br = new BufferedReader(new InputStreamReader(connectionSuggest.getInputStream()));
                String line;

                while ((line = br.readLine()) != null) {
                    String[] split1 = line.split("\\|");
                    if (split1.length == 2) {
                        String score = split1[0].trim();
                        String[] split2 = split1[1].trim().split(" ");
                        if (split2.length == 2) {
                            String flag = split2[0];
                            String word = split2[1];

                            String definition;
                            // If UCD description is already inside Ucidy library
                            // it is possibile to avoid calling the web service.
                            UCD ucd = UCDParser.parseUCD(word);
                            if (ucd.size() == 1) {
                                definition = ucd.getWord(0).description;
                            } else {
                                definition = getDefinition(word);
                            }

                            resultList.add(new UCDInfo(score, flag, word, definition));
                        }
                    }
                }

                return resultList;
            } else if (responseCodeSuggest == 204) {
                return null;
            }

            throw new UCDServiceException("Server responded with a status of " + responseCodeSuggest);
        } catch (MalformedURLException e) {
            throw new UCDServiceException("Malformed url: " + urlStr);
        } catch (IOException e) {
            throw new UCDServiceException("Error while reading server response");
        }
    }

    public static String getDefinition(String word) throws UCDServiceException {
        String searchText = encodeText(word);
        String urlStr = UCD_SERVICE_URL + "explain?value=" + searchText;

        try {
            URL url = new URL(urlStr);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line, response = "";
                while ((line = br.readLine()) != null) {
                    response += line;
                }

            } else {
                throw new UCDServiceException("Server responded with a status of " + responseCode);
            }
        } catch (MalformedURLException e) {
            throw new UCDServiceException("Malformed url: " + urlStr);
        } catch (IOException e) {
            throw new UCDServiceException("Error while reading server response");
        }
    }
}