root/SPARQLBuilderWWW/src/java/org/biohackathon/SPARQLBuilder/www/SPServlet.java @ 168

リビジョン 165, 12.5 KB (コミッタ: wu, 10 年 前)

pathはjsonに変更しました

行番号 
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6
7package org.biohackathon.SPARQLBuilder.www;
8
9import java.io.IOException;
10import java.io.PrintWriter;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Iterator;
14import java.util.List;
15import java.util.logging.Level;
16import java.util.logging.Logger;
17import javax.servlet.ServletException;
18import javax.servlet.annotation.WebServlet;
19import javax.servlet.http.HttpServlet;
20import javax.servlet.http.HttpServletRequest;
21import javax.servlet.http.HttpServletResponse;
22import org.biohackathon.SPARQLBuilder.OWL.*;
23import org.json.JSONArray;
24import org.json.JSONException;
25import org.json.JSONObject;
26
27//import javax.json.Json;
28
29/**
30 *
31 * @author atsuko
32 */
33@WebServlet(name = "SPServlet", urlPatterns = {"/sparql"})
34public class SPServlet extends HttpServlet {
35
36    /**
37     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
38     * methods.
39     *
40     * @param request servlet request
41     * @param response servlet response
42     * @throws ServletException if a servlet-specific error occurs
43     * @throws IOException if an I/O error occurs
44     */
45    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
46            throws ServletException, IOException {
47        response.setContentType("text/html;charset=UTF-8");
48        try (PrintWriter out = response.getWriter()) {
49            /* TODO output your page here. You may use following sample code. */
50            out.println("<!DOCTYPE html>");
51            out.println("<html>");
52            out.println("<head>");
53            out.println("<title>Servlet SPServlet</title>");           
54            out.println("</head>");
55            out.println("<body>");
56            out.println("<h1>Servlet SPServlet at " + request.getContextPath() + "</h1>");
57            out.println("</body>");
58            out.println("</html>");
59        }
60    }
61
62    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
63    /**
64     * Handles the HTTP <code>GET</code> method.
65     *
66     * @param request servlet request
67     * @param response servlet response
68     * @throws ServletException if a servlet-specific error occurs
69     * @throws IOException if an I/O error occurs
70     */
71    @Override
72/*    protected void doGet(HttpServletRequest request, HttpServletResponse response)
73            throws ServletException, IOException {
74        processRequest(request, response);
75    }*/
76        protected void doGet(HttpServletRequest request, HttpServletResponse response)
77            throws ServletException, IOException {
78        //processRequest(request, response);
79        response.setContentType("application/json;charset=UTF-8");
80        PrintWriter out = response.getWriter();
81        String jpath = request.getParameter("jsonpath");
82        Path path = null;
83        try {
84            path = convertJ2Path(jpath);
85        } catch (JSONException ex) {
86            Logger.getLogger(SPServlet.class.getName()).log(Level.SEVERE, null, ex);
87        }
88        String query = null;
89        try {
90           query = convertPath2SPARQL(path);
91        } catch (Exception ex) {
92            Logger.getLogger(SPServlet.class.getName()).log(Level.SEVERE, null, ex);
93        }
94        out.print(query);
95    }
96
97   
98
99    /**
100     * Handles the HTTP <code>POST</code> method.
101     *
102     * @param request servlet request
103     * @param response servlet response
104     * @throws ServletException if a servlet-specific error occurs
105     * @throws IOException if an I/O error occurs
106     */
107    @Override
108    protected void doPost(HttpServletRequest request, HttpServletResponse response)
109            throws ServletException, IOException {
110        processRequest(request, response);
111    }
112
113    /**
114     * Returns a short description of the servlet.
115     *
116     * @return a String containing servlet description
117     */
118    @Override
119    public String getServletInfo() {
120        return "Short description";
121    }// </editor-fold>
122
123    private Path convertJ2Path(String jpath) throws JSONException{
124 
125       JSONObject object = new JSONObject(jpath);
126   
127    //   int width = Integer.parseInt(object.getJSONObject("width").toString());
128       JSONArray classLinks = object.getJSONArray("classLinks");
129        JSONObject jsonObject;
130        List <ClassLink> list = new ArrayList<ClassLink>();
131       
132       for (int i=0;i<classLinks.length();i++)
133       {
134            jsonObject = classLinks.getJSONObject(i); 
135               
136             String direction=jsonObject.getString("direction");
137             Direction myDirection = null;
138             if (direction.equals(Direction.forward.toString()))
139                     myDirection=Direction.forward;
140             else if (direction.equals(Direction.reverse.toString()))
141                 myDirection=Direction.reverse;
142                 else if (direction.equals(Direction.both.toString()))                 
143                  myDirection=Direction.both;
144           
145                 
146            String linkedLiteralDatatypeURI=null;
147               linkedLiteralDatatypeURI = jsonObject.getString("linkedLiteralDatatypeURI");
148               String linkedClassURI = jsonObject.getString("linkedClassURI");
149                  String propertyURI = jsonObject.getString("propertyURI");
150             
151        //    int numOfLinks = Integer.parseInt(jsonObject.getJSONObject("numOfLinks").toString());
152        //    int numOfLinkedInstances = Integer.parseInt(jsonObject.getJSONObject("numOfLinkedInstances").toString());
153        //    int numOfOriginInstances = Integer.parseInt(jsonObject.getJSONObject("numOfOriginInstances").toString());
154        //    int numOfOriginClassInstances = Integer.parseInt(jsonObject.getJSONObject("numOfOriginInstances").toString());           
155        //    int numOfLinkedClassInstances = Integer.parseInt(jsonObject.getJSONObject("numOfLinkedClassInstances").toString());
156             
157        //    ClassLink classLink =new ClassLink(propertyURI, linkedClassURI, linkedLiteralDatatypeURI, null,
158        //                       numOfLinks,  numOfOriginInstances,  numOfLinkedInstances,
159        //                       numOfOriginClassInstances,  numOfLinkedClassInstances,
160        //                      false, false);
161             ClassLink classLink =new ClassLink(propertyURI, linkedClassURI, linkedLiteralDatatypeURI, myDirection,
162                                 0,  0,  0,
163                                 0,  0,
164                                false, false);
165             
166           list.add(classLink);
167    }
168           String startClass = object.getString("startClassURI");
169          Path path = new Path(startClass,  list,  0);
170          return path;
171    }
172   
173    private String convertPath2SPARQL(Path path) throws Exception{
174        if( path == null ){
175                        throw new Exception("Path is null.");
176                }
177                String startClass = path.getStartClass();
178                List<ClassLink> classLinks = path.getClassLinks();
179       
180                StringBuffer queryStr = new StringBuffer();
181                StringBuffer selStr = new StringBuffer();
182                StringBuffer whereStr = new StringBuffer();
183        //      if(num==0){
184                        int num = classLinks.size();
185        //      }
186                       
187                queryStr.append("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n");
188                queryStr.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n");
189                               
190                selStr.append("SELECT ");
191                whereStr.append("WHERE { \n");
192
193                String properties = null;
194                String objectClasses = null;
195                String subjectClasses = null;
196                Direction direction = null;
197                int i = 0;
198                int k = 0;
199                for (ClassLink link :classLinks )
200                {
201                        properties = link.getPropertyURI();
202                        objectClasses = link.getLinkedClassURI();
203                        direction = link.getDirection();
204                       
205                        if (i==0)
206                    subjectClasses = startClass;
207                       
208                        selStr.append("?c").append(i).append(" ");
209                        selStr.append("?l").append(i).append(" ");
210                       
211                        if(i == classLinks.size())
212                                selStr.append("\n");
213                       
214                       
215                        whereStr.append("?c").append(i).
216                        append(" rdf:type ").
217                        append("<").
218                        append(subjectClasses).
219                        append(">").
220                        append(".\n");
221                       
222                        whereStr.append("OPTIONAL{\n?c"+i+" rdfs:label ?l"+i+".}\n");
223
224                                               
225                        if(direction == Direction.forward)
226                        {
227                        whereStr.append("?c").append(i).append(" ");
228                        whereStr.append("<").append(properties).append("> ");                   
229                        whereStr.append("?c").append(i+1).append(".\n");                       
230                        }
231                        else
232                        {
233                                whereStr.append("?c").append(i+1).append(" ");
234                                whereStr.append("<").append(properties).append("> ");
235                                whereStr.append("?c").append(i).append(".\n");
236                        }
237                       
238                        subjectClasses = objectClasses;
239                        i++;
240                        k++;
241                        if(k>=num){
242                                break;
243                        }
244                }
245               
246                selStr.append("?c").append(i).append(" \n");
247                selStr.append("?l").append(i).append(" \n");
248                whereStr.append("?c").append(i).append(" rdf:type ").
249                    append("<").
250                    append(subjectClasses).
251                    append(">").
252                        append(".\n");
253                whereStr.append("OPTIONAL{\n?c"+i+" rdfs:label ?l"+i+".}\n");
254       
255                                       
256                queryStr.append(selStr).append(whereStr);
257               
258                queryStr.append("}");
259                //OPTIONAL
260                queryStr.append("LIMIT 100\n");;
261               
262                //System.out.println(queryStr);
263                return queryStr.toString();
264       
265   
266    }
267        private static List<String> convertJ2Path2(String jpath) throws JSONException{
268         List <String> list = null;
269           String temp =(String) jpath.subSequence(2, jpath.length()-2);
270      //  if (temp.contains(",""))
271             list =Arrays.asList(temp.split("\",\""));
272             return list;
273 
274     /*  JSONArray classLinks=new JSONArray(jpath);
275       String string;
276       
277       for (int i=0;i<classLinks.length();i++)
278       {
279            string = classLinks.getJSONObject(i).toString();
280            if (string.contains(",")) {
281             list =Arrays.asList(string.split(","));
282             
283       } else
284          throw new IllegalArgumentException("path error");
285               
286         }*/
287       
288       //   return list;   
289    }
290   
291    private static String convertPath2SPARQL2(List<String> path) throws Exception{
292        if( path == null ){
293                        throw new Exception("Path is null.");
294                }
295       
296                             
297                //List<String> classLinks = path.getClassLinks();
298               
299                StringBuffer queryStr = new StringBuffer();
300                StringBuffer selStr = new StringBuffer();
301                StringBuffer whereStr = new StringBuffer();
302        //      if(num==0){
303                //      int num = classLinks.size();
304        //      }
305                       
306                queryStr.append("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n");
307                queryStr.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n");
308                               
309                selStr.append("SELECT ");
310                whereStr.append("WHERE { \n");
311
312                String properties = null;
313                String objectClasses = null;
314                String subjectClasses = null;
315                Direction direction = null;
316                int i = 0;
317                int k = 0;
318               
319                String startClass = path.get(path.size()-1);
320                List<String> classLinks = null;
321         //      ArrayList<String> array= (String[])path.toArray();
322             
323            //    classLinks.add(path.get(i));
324               
325                int num =(path.size()-1)/2;
326               
327                 for(int j=path.size()-2;j>0;j=j-2)
328                {
329                //      properties = link.getPropertyURI();
330                //      objectClasses = link.getLinkedClassURI();
331                //      direction = link.getDirection();
332                   properties =  path.get(j);
333                   objectClasses = path.get(j-1);
334                   direction = Direction.forward;
335                       
336                        if (i==0)
337                    subjectClasses = startClass;
338                       
339                        selStr.append("?c").append(i).append(" ");
340                        selStr.append("?l").append(i).append(" ");
341                       
342                //      if(i == path.size())
343                //              selStr.append("\n");
344                       
345                       
346                        whereStr.append("?c").append(i).
347                        append(" rdf:type ").
348                        append("<").
349                        append(subjectClasses).
350                        append(">").
351                        append(".\n");
352                       
353                        whereStr.append("OPTIONAL{\n?c"+i+" rdfs:label ?l"+i+".}\n");
354
355                                               
356                        if(direction == Direction.forward)
357                        {
358                        whereStr.append("?c").append(i).append(" ");
359                        whereStr.append("<").append(properties).append("> ");                   
360                        whereStr.append("?c").append(i+1).append(".\n");                       
361                        }
362                        else
363                        {
364                                whereStr.append("?c").append(i+1).append(" ");
365                                whereStr.append("<").append(properties).append("> ");
366                                whereStr.append("?c").append(i).append(".\n");
367                        }
368                       
369                        subjectClasses = objectClasses;
370                        i++;
371                        k++;
372                        if(k>=num){
373                                break;
374                        }
375                }
376               
377                selStr.append("?c").append(i).append(" \n");
378                selStr.append("?l").append(i).append(" \n");
379                whereStr.append("?c").append(i).append(" rdf:type ").
380                    append("<").
381                    append(subjectClasses).
382                    append(">").
383                        append(".\n");
384                whereStr.append("OPTIONAL{\n?c"+i+" rdfs:label ?l"+i+".}\n");
385       
386                                       
387                queryStr.append(selStr).append(whereStr);
388               
389                queryStr.append("}");
390                //OPTIONAL
391                queryStr.append("LIMIT 100\n");;
392               
393                System.out.println(queryStr);
394                return queryStr.toString();
395       
396   
397    }
398   
399}
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。