Commit 678ffebe authored by Sonia Zorba's avatar Sonia Zorba
Browse files

Added UCD manual insertion and its validation

parent 380cfb92
Loading
Loading
Loading
Loading
+215 −0
Original line number Original line Diff line number Diff line
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");
            }
        }
    }
}
+43 −0
Original line number Original line Diff line number Diff line
package it.inaf.oats.ia2.tapschemamanager.businesslayer;

import java.io.Serializable;

/**
 *
 * @author Sonia Zorba <zorba at oats.inaf.it>
 */
public class UCDInfo implements Serializable {

    private static final long serialVersionUID = 585936072742567972L;

    private final String score;
    private final String flag;
    private final String word;
    private String definition;

    UCDInfo(String score, String flag, String word) {
        this.score = score;
        this.flag = flag;
        this.word = word;
    }

    public String getScore() {
        return score;
    }

    public String getFlag() {
        return flag;
    }

    public String getWord() {
        return word;
    }

    public String getDefinition() {
        return definition;
    }

    public void setDefinition(String definition) {
        this.definition = definition;
    }
}
+14 −0
Original line number Original line Diff line number Diff line
package it.inaf.oats.ia2.tapschemamanager.businesslayer;

/**
 *
 * @author Sonia Zorba <zorba at oats.inaf.it>
 */
public class UCDServiceException extends Exception {

    private static final long serialVersionUID = 5009586704294107944L;

    public UCDServiceException(String message) {
        super(message);
    }
}
+5 −0
Original line number Original line Diff line number Diff line
@@ -65,6 +65,11 @@ public class CustomPartialResponseWriter extends PartialResponseWriter {
        customJSUpdates.put(componentId, updateHandler);
        customJSUpdates.put(componentId, updateHandler);
    }
    }


    public void addCustomJSUpdate(JSUpdateHandler updateHandler) {
        String sourceComponentId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("javax.faces.source");
        addCustomJSUpdate(sourceComponentId, updateHandler);
    }

    public static CustomPartialResponseWriter getCurrentInstance() {
    public static CustomPartialResponseWriter getCurrentInstance() {
        return (CustomPartialResponseWriter) FacesContext.getCurrentInstance().getPartialViewContext().getPartialResponseWriter();
        return (CustomPartialResponseWriter) FacesContext.getCurrentInstance().getPartialViewContext().getPartialResponseWriter();
    }
    }
+87 −108
Original line number Original line Diff line number Diff line
package it.inaf.oats.ia2.tapschemamanager.webapp;
package it.inaf.oats.ia2.tapschemamanager.webapp;


import java.io.BufferedReader;
import it.inaf.oats.ia2.tapschemamanager.businesslayer.SearchUCD;
import java.io.InputStreamReader;
import it.inaf.oats.ia2.tapschemamanager.businesslayer.UCDInfo;
import it.inaf.oats.ia2.tapschemamanager.businesslayer.UCDServiceException;
import java.io.Serializable;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.Dependent;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;


/**
/**
 *
 *
@@ -19,50 +21,16 @@ public class SearchUCDDialog implements Serializable {


    private static final long serialVersionUID = -3503024742241865133L;
    private static final long serialVersionUID = -3503024742241865133L;


    static final transient String UCD_REST_SERVICE = "http://localhost:8080/ucd/";
    private boolean manualInsertion;
    static final transient String UCD_NOT_FOUND = "**** Could not find UCD ****";


    public static class UCDInfo implements Serializable {
    private String UCDManualText;

        private static final long serialVersionUID = 585936072742567972L;

        private final String score;
        private final String flag;
        private final String word;
        private String definition;

        UCDInfo(String score, String flag, String word) {
            this.score = score;
            this.flag = flag;
            this.word = word;
        }

        public String getScore() {
            return score;
        }

        public String getFlag() {
            return flag;
        }

        public String getWord() {
            return word;
        }

        public String getDefinition() {
            return definition;
        }

        public void setDefinition(String definition) {
            this.definition = definition;
        }
    }


    private String description;
    private String description;
    private boolean UCDnotFound;
    private boolean UCDnotFound;
    private String UCDServiceErrorMessage;
    private String selectedUCD;
    private String selectedUCD;
    private String suggestedUCD;
    private String suggestedUCD;
    private final List<UCDInfo> suggestedUCDs;
    private List<UCDInfo> suggestedUCDs;


    public SearchUCDDialog() {
    public SearchUCDDialog() {
        suggestedUCDs = new ArrayList<UCDInfo>();
        suggestedUCDs = new ArrayList<UCDInfo>();
@@ -93,69 +61,38 @@ public class SearchUCDDialog implements Serializable {
    }
    }


    public void setDefault() {        
    public void setDefault() {        
        UCDManualText = null;
        
        description = null;
        description = null;
        UCDnotFound = false;
        UCDnotFound = false;
        selectedUCD = null;
        selectedUCD = null;
        suggestedUCD = null;
        suggestedUCD = null;
        suggestedUCDs.clear();
        suggestedUCDs.clear();
        
        UCDServiceErrorMessage = null;
    }
    }


    public void search(String description) throws Exception {
    public void search(String description) {
        try {
            setDefault();
            setDefault();
            this.description = description;
            this.description = description;


        String searchText = URLEncoder.encode(this.description, "UTF-8").replace("+", "%20");
            String assignResponse = SearchUCD.assign(description);

            if (assignResponse == null) {
        // Search assign value
        URL urlAssign = new URL(UCD_REST_SERVICE + "assign?value=" + searchText);

        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)) {
                UCDnotFound = true;
                UCDnotFound = true;
            } else {
            } else {
                selectedUCD = response;
                selectedUCD = assignResponse;
                suggestedUCD = response;
                suggestedUCD = assignResponse;


                // Search suggested values
                List<UCDInfo> suggestResponse = SearchUCD.suggest(description);
                URL urlSuggest = new URL(UCD_REST_SERVICE + "suggest?value=" + searchText);
                if (suggestResponse == null) {

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

                int responseCodeSuggest = connectionSuggest.getResponseCode();
                if (responseCodeSuggest == 200) {
                    br = new BufferedReader(new InputStreamReader(connectionSuggest.getInputStream()));
                    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];
                                suggestedUCDs.add(new UCDInfo(score, flag, word));
                            }
                        }
                    }
                } else if (responseCodeSuggest == 204) {
                    UCDnotFound = true;
                    UCDnotFound = true;
                } else {
                } else {
                    throw new Exception("Service error");
                    suggestedUCDs = suggestResponse;
                }
                }
            }
            }
        } else if (responseCodeAssign == 204) {
        } catch (UCDServiceException e) {
            UCDnotFound = true;
            setUCDServiceErrorMessage(e);
        } else {
            throw new Exception("Service error");
        }
        }
    }
    }
    
    
@@ -163,24 +100,66 @@ public class SearchUCDDialog implements Serializable {
        this.selectedUCD = selectedUCD;
        this.selectedUCD = selectedUCD;
    }
    }


    public void explain(UCDInfo ucdInfo) throws Exception {
    public void explain(UCDInfo ucdInfo) {
        System.out.println("explain: " + ucdInfo.getWord());
        try {
        String searchText = URLEncoder.encode(ucdInfo.getWord(), "UTF-8").replace("+", "%20");
            SearchUCD.explain(ucdInfo);
        URL url = new URL(UCD_REST_SERVICE + "explain?value=" + searchText);
        } catch (UCDServiceException e) {
            setUCDServiceErrorMessage(e);
        }
    }


        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    public boolean isManualInsertion() {
        return manualInsertion;
    }


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


            ucdInfo.setDefinition(response);
    public String getUCDServiceErrorMessage() {
        return UCDServiceErrorMessage;
    }

    private void setUCDServiceErrorMessage(UCDServiceException e) {
        setDefault();
        UCDServiceErrorMessage = e.getMessage();
    }

    public String getUCDManualText() {
        return UCDManualText;
    }

    public void setUCDManualText(String UCDManualText) {
        this.UCDManualText = UCDManualText;
    }

    public void validateManualUCD(FacesContext context, UIComponent inputComponent, Object value) {
        String textValue = (String) value;

        String validatorMessage = null;
        if (textValue == null || textValue.isEmpty()) {
            validatorMessage = "UCD can't be null";
        } else {
        } else {
            throw new Exception("Service error");
            try {
                if (!SearchUCD.validateManualUCD(textValue)) {
                    validatorMessage = "Invalid UCD!";
                }
            } catch (UCDServiceException e) {
                setUCDServiceErrorMessage(e);
                FacesContext.getCurrentInstance().validationFailed();
            }
        }
        }

        if (validatorMessage != null) {
            throw new ValidatorException(new FacesMessage(validatorMessage));
        }
    }

    public String getUCDRegExp() {
        return SearchUCD.REG_EXP_UCD;
    }

    public String getNamespaceRegExp() {
        return SearchUCD.REG_EXP_START_WITH_NAMESPACE;
    }
    }
}
}
Loading