Skip to content
SearchUCD.java 8.25 KiB
Newer Older
package it.inaf.oats.ia2.tapschemamanager.businesslayer;

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;
import java.util.regex.Pattern;
import javax.naming.InitialContext;
import javax.naming.NamingException;

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

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

    public static final String REG_EXP_UCD;
    public static final String REG_EXP_START_WITH_NAMESPACE;

    private static final Pattern PATTERN_UCD;
    private static final Pattern PATTERN_START_WITH_NAMESPACE;

    static {
        try {
            InitialContext ic = new InitialContext();
            UCD_SERVICE_PATH = (String) ic.lookup("java:comp/env/UCD_SERVICE_PATH");
        } catch (NamingException e) {
            throw new RuntimeException("Unable to find UCD service path in web.xml configuration!");
        }

        String namespaceRegExpPart = "[a-zA-Z]+\\:"; // validate e.g. "mynamespace:"

        String[] ucdCategories = new String[]{"arith", "em", "instr", "meta", "obs", "phot", "phys", "pos", "spect", "src", "stat", "time"};

        StringBuilder sbCategories = new StringBuilder();
        boolean first = true;
        for (String category : ucdCategories) {
            if (!first) {
                sbCategories.append("|");
            }
            first = false;
            sbCategories.append(category);
        }

        String regExpWordPart = String.format("(%s)([\\.][\\-a-zA-Z0-9]+)*", sbCategories.toString()); // validate single word

        REG_EXP_UCD = String.format("^(%s)?%s(;%s)*$", namespaceRegExpPart, regExpWordPart, regExpWordPart);
        REG_EXP_START_WITH_NAMESPACE = String.format("^%s.+$", namespaceRegExpPart);

        PATTERN_UCD = Pattern.compile(REG_EXP_UCD);
        PATTERN_START_WITH_NAMESPACE = Pattern.compile(REG_EXP_START_WITH_NAMESPACE);
    }

    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_PATH + "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_PATH + "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<UCDInfo>();
                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];
                            resultList.add(new UCDInfo(score, flag, word));
                        }
                    }
                }

                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 void explain(UCDInfo ucdInfo) throws UCDServiceException {
        String searchText = encodeText(ucdInfo.getWord());
        String urlStr = UCD_SERVICE_PATH + "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;
                }

                ucdInfo.setDefinition(response);
            } 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");
        }
    }

    public static boolean validateManualUCD(String inputText) throws UCDServiceException {
        if (inputText == null) {
            return false;
        }

        if (!PATTERN_UCD.matcher(inputText).matches()) {
            return false;
        }

        boolean customUCD = PATTERN_START_WITH_NAMESPACE.matcher(inputText).matches();

        if (customUCD) {
            return true;
        } else {
            String searchText = encodeText(inputText);
            String urlStr = UCD_SERVICE_PATH + "validate?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;
                    }

                    return response.equals("0"); // String "0" means valid UCD
                } 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");
            }
        }
    }
}