001package org.dllearner.server;
002
003import java.io.BufferedInputStream;
004import java.io.ByteArrayInputStream;
005import java.io.File;
006import java.io.FileInputStream;
007import java.io.IOException;
008import java.io.PrintWriter;
009import java.net.URLDecoder;
010import java.nio.file.Paths;
011import java.util.ArrayList;
012import java.util.HashMap;
013import java.util.Map;
014
015import javax.servlet.ServletException;
016import javax.servlet.http.HttpServlet;
017import javax.servlet.http.HttpServletRequest;
018import javax.servlet.http.HttpServletResponse;
019
020import org.apache.commons.lang.exception.ExceptionUtils;
021import org.dllearner.configuration.IConfiguration;
022import org.dllearner.configuration.spring.ApplicationContextBuilder;
023import org.dllearner.configuration.spring.DefaultApplicationContextBuilder;
024import org.dllearner.confparser.ConfParserConfiguration;
025import org.dllearner.core.ClassExpressionLearningAlgorithm;
026import org.dllearner.core.LearningAlgorithm;
027import org.dllearner.learningproblems.EvaluatedDescriptionPosNeg;
028import org.dllearner.utilities.owl.OWLAPIRenderers;
029import org.dllearner.utilities.owl.OWLClassExpressionToSPARQLConverter;
030import org.json.simple.JSONObject;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033import org.springframework.context.ApplicationContext;
034import org.springframework.core.io.InputStreamResource;
035import org.springframework.core.io.Resource;
036
037public class Rest extends HttpServlet {
038    private static Logger log = LoggerFactory.getLogger(Rest.class);
039
040    @Override
041    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
042        handle(httpServletRequest, httpServletResponse);
043    }
044
045    @Override
046    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
047        handle(httpServletRequest, httpServletResponse);
048    }
049
050    /**
051     * *
052     *
053     * @param httpServletRequest
054     * @param httpServletResponse
055     * @throws ServletException
056     * @throws java.io.IOException
057     */
058    private void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
059        JSONObject result = new JSONObject();
060        JSONObject learningResult = new JSONObject();
061        try {
062            String conf = null;
063            int limit = 5;
064            if (!isSet("conf", httpServletRequest)) {
065//                throw new IllegalArgumentException("Missing parameter: conf is required. ");
066                httpServletRequest.getRequestDispatcher("/WEB-INF/sparqr.html").forward(httpServletRequest, httpServletResponse);
067                return;
068            } else {
069                conf = URLDecoder.decode(httpServletRequest.getParameter("conf"), "UTF-8");
070                if (isSet("limit", httpServletRequest)) {
071                    limit = Integer.parseInt(httpServletRequest.getParameter("limit"));
072                }
073            }
074
075            if (isSet("debug", httpServletRequest) && httpServletRequest.getParameter("debug").equalsIgnoreCase("true")) {
076
077                String manchester = "author some (Artist and Writer)";
078                String sparql = "prefix dbo: <http://dbpedia.org/ontology/>\n" +
079                        "SELECT ?instances WHERE {\n" +
080                        "?instances dbo:author ?o . ?o a dbo:Artist . ?o a dbo:Writer .\n" +
081                        "} ";
082
083                learningResult.put("success", "1");
084                learningResult.put("manchester", manchester); 
085                learningResult.put("kbsyntax", "other syntax");
086                learningResult.put("sparql", sparql);
087                learningResult.put("accuracy", 1.0);
088                learningResult.put("truePositives", "uri1, uri2");
089                learningResult.put("truePositives", "uri1, uri2");
090                learningResult.put("trueNegatives", "uri1, uri2");
091                learningResult.put("falseNegatives", "uri1, uri2");
092            } else {
093
094                EvaluatedDescriptionPosNeg ed = learn(conf);
095
096                OWLClassExpressionToSPARQLConverter sparqlConv = new OWLClassExpressionToSPARQLConverter();
097                               learningResult.put("success", "1");
098                learningResult.put("manchester", OWLAPIRenderers.toManchesterOWLSyntax(ed.getDescription()));
099//                learningResult.put("sparql", sqd.getSparqlQuery(ed.getDescription()));
100                learningResult.put("sparql", " "+ sparqlConv.asQuery("?subject", ed.getDescription())+" ");
101                learningResult.put("accuracy", ed.getAccuracy());
102                learningResult.put("truePositives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getCoveredPositives()));
103                learningResult.put("falsePositives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getNotCoveredPositives()));
104                learningResult.put("trueNegatives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getNotCoveredNegatives()));
105                learningResult.put("falseNegatives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getCoveredNegatives()));
106            }
107
108        } catch (IllegalArgumentException e) {
109            String msg = e.getMessage();// + printParameterMap(httpServletRequest);
110            log.error("", ExceptionUtils.getRootCause(e));
111            learningResult.put("success", "0");
112            learningResult.put("error", msg);
113            learningResult.put("stacktrace", ExceptionUtils.getRootCause(e));
114
115        } catch (Exception e) {
116            String msg = "An error occured: " + e.getMessage(); //+ printParameterMap(httpServletRequest);
117            log.error("", ExceptionUtils.getRootCause(e));
118            learningResult.put("success", "0");
119            learningResult.put("error", msg);
120            learningResult.put("stacktrace", ExceptionUtils.getRootCause(e));
121            result.put("learningresult", learningResult);
122            httpServletResponse.sendError(500, result.toJSONString());
123        }
124
125        result.put("learningresult", learningResult);
126        httpServletResponse.setContentType("text/plain");
127        PrintWriter out = httpServletResponse.getWriter();
128        out.println(result.toJSONString());
129        out.close();
130
131    }
132
133    /**
134     * TODO
135     * This function takes the config string as in a conf file and the returns an EvaluatedDescription
136     *
137     * @param conf the content of a conf file
138     * @return
139     */
140    public EvaluatedDescriptionPosNeg learn(String conf) throws Exception {
141        Resource confFile = new InputStreamResource(new ByteArrayInputStream(conf.getBytes()));
142
143        IConfiguration configuration = new ConfParserConfiguration(confFile);
144
145        ApplicationContextBuilder builder = new DefaultApplicationContextBuilder();
146        ApplicationContext context = builder.buildApplicationContext(configuration, new ArrayList<>());
147
148        LearningAlgorithm algorithm = context.getBean(LearningAlgorithm.class);
149        algorithm.start();
150        if (algorithm instanceof ClassExpressionLearningAlgorithm) {
151            return (EvaluatedDescriptionPosNeg) ((ClassExpressionLearningAlgorithm) algorithm).getCurrentlyBestEvaluatedDescriptions(1).iterator().next();
152        }
153        throw new Exception("only ClassExpressionLearningAlgorithm implemented currently");
154    }
155
156    public static boolean isSet(String parameterName, HttpServletRequest hsr) {
157        boolean retVal = hsr.getParameterValues(parameterName) != null && hsr.getParameterValues(parameterName).length == 1 && hsr.getParameter(parameterName).length() > 0;
158        if (log.isTraceEnabled()) {
159            log.trace("Parameter " + parameterName + " isSet: " + retVal + " with value: " + hsr.getParameter(parameterName) + ")");
160        }
161        return retVal;
162    }
163
164    public static Map<String, String> copyParameterMap(HttpServletRequest httpServletRequest) {
165        Map<String, String> ret = new HashMap<>();
166        for (Object key : httpServletRequest.getParameterMap().keySet()) {
167            ret.put((String) key, httpServletRequest.getParameter((String) key));
168        }
169        return ret;
170    }
171
172    public static void main(String[] args) throws Exception {
173//        String filePath = Paths.get("").toAbsolutePath() + "/../examples/father_remote.conf";
174        String filePath = Paths.get("").toAbsolutePath() + "/../examples/sparql/AristotlePosNeg.conf";
175        
176        byte[] buffer = new byte[(int) new File(filePath).length()];
177        BufferedInputStream f = null;
178        try {
179            f = new BufferedInputStream(new FileInputStream(filePath));
180            f.read(buffer);
181        } finally {
182            if (f != null) try {
183                f.close();
184            } catch (IOException ignored) {
185            }
186        }
187        String confString = new String(buffer);
188
189        Resource confFile = new InputStreamResource(new ByteArrayInputStream(confString.getBytes()));
190
191        IConfiguration configuration = new ConfParserConfiguration(confFile);
192
193        ApplicationContextBuilder builder = new DefaultApplicationContextBuilder();
194        ApplicationContext context = builder.buildApplicationContext(configuration, new ArrayList<>());
195
196        LearningAlgorithm algorithm = context.getBean(LearningAlgorithm.class);
197        algorithm.start();
198    }
199
200}