Added RDFTranslator code
authorjani <jani@asema.com>
Fri, 2 Aug 2019 19:24:54 +0000 (22:24 +0300)
committerjani <jani@asema.com>
Fri, 2 Aug 2019 19:24:54 +0000 (22:24 +0300)
Examples/Python/AdaptDataService/AdaptDataService.py
Utilities/RDFTranslator/META-INF/MANIFEST.MF [new file with mode: 0644]
Utilities/RDFTranslator/META-INF/context.xml [new file with mode: 0644]
Utilities/RDFTranslator/README [new file with mode: 0644]
Utilities/RDFTranslator/build.sh [new file with mode: 0755]
Utilities/RDFTranslator/client_start.sh [new file with mode: 0644]
Utilities/RDFTranslator/server_start.sh [new file with mode: 0644]
Utilities/RDFTranslator/src/TestClient.java [new file with mode: 0644]
Utilities/RDFTranslator/src/rdftranslator/CmdLineTranslator.java [new file with mode: 0644]
Utilities/RDFTranslator/translate.jsp [new file with mode: 0644]

index e7d51fa372c2bd3c7ebf27397d63ed65f198b8a4..9ad9cb5b99db2f57b564deace4f58c895836ef75 100755 (executable)
@@ -83,6 +83,9 @@ class SampleRegistration(object):
                        power.setUnit(RESOURCE.AMPERE)
                        power.setMaximum(1000.0)
                        power.setMinimum(0.0)
+                       power.setName("Power reading")
+                       power.setDescription("This is the power reading of the unit.");
+                               
 
                        dataSource.addValueObject(power)
 
diff --git a/Utilities/RDFTranslator/META-INF/MANIFEST.MF b/Utilities/RDFTranslator/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..f6e3055
--- /dev/null
@@ -0,0 +1,2 @@
+Main-Class: rdftranslator.Translator
+
diff --git a/Utilities/RDFTranslator/META-INF/context.xml b/Utilities/RDFTranslator/META-INF/context.xml
new file mode 100644 (file)
index 0000000..45979b2
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Context allowLinking="true"/>
+
diff --git a/Utilities/RDFTranslator/README b/Utilities/RDFTranslator/README
new file mode 100644 (file)
index 0000000..4a1b977
--- /dev/null
@@ -0,0 +1,90 @@
+RDFTranslator
+-------------
+
+The RDF Translator program can be run as a Web service and as a socket server.
+
+Socket server instructions
+--------------------------
+
+Start the socket server with command:
+ java -cp dist/rdftranslator.jar:lib/* rdftranslator.Translator [port]
+
+See server_start.sh file for an example.
+
+Socket server expects an incoming  message to be in the following format:
+
+input=[input_rdf_format]&output=[output_rdf_format]&[input_rdf]
+
+Accepted input and output formats are:
+
+JSON-LD
+TURTLE
+RDF/XML
+N-TRIPLE
+
+Example incoming message:
+
+input=JSON-LD&output=TURTLE&{
+  "@context": "http://seas.asema.com/webapps/jsonld/context.jsonld",
+  "@type": "ts:Evaluation",
+  "ts:systemOfInterest": {
+      "@id": "http://asema.com/1921681170/C9c2a4576bde9875a57d9875c",
+      "@type": "seas:Device",
+      "seas:registerKey": "outside temp" 
+  },
+  "ts:category": "ts:Request",
+  "seas:temporalContext": { 
+      "seas:start": "2016-01-08T12:15:00+00:00",
+      "seas:end": "2016-01-08T12:19:00+00:00"
+  }, 
+  "seas:timeSeries": {
+     "ts:timeStep": "PT1M"
+  },
+  "ts:generatedAt": "2016-01-08T12:20:02+00:00",
+  "ts:generatedBy": 
+"http://requestercompany.com/reqservice/C9c2a4576bde9875a57d9875c"
+}
+
+Web service instructions
+------------------------
+
+To set up the service, copy following files/folder into Tomcat webapps folder:
+
+translate.jsp
+META-INF/
+WEB-INF/
+
+Web service expects to be connected using HTTP POST messages and given two url-parameters, 
+input and output. These are used to define the RDF serializations. Message body should
+contain the RDF to be translated.
+
+Example:
+
+HTTP POST
+
+http://<domain>/webapps/translator/translate.jsp?input=json-ld&output=turtle
+
+Body:
+
+{
+  "@context": "http://seas.asema.com/webapps/jsonld/context.jsonld",
+  "@type": "ts:Evaluation",
+  "ts:systemOfInterest": {
+      "@id": "http://asema.com/1921681170/C9c2a4576bde9875a57d9875c",
+      "@type": "seas:Device",
+      "seas:registerKey": "outside temp" 
+  },
+  "ts:category": "ts:Request",
+  "seas:temporalContext": { 
+      "seas:start": "2016-01-08T12:15:00+00:00",
+      "seas:end": "2016-01-08T12:19:00+00:00"
+  }, 
+  "seas:timeSeries": {
+     "ts:timeStep": "PT1M"
+  },
+  "ts:generatedAt": "2016-01-08T12:20:02+00:00",
+  "ts:generatedBy": 
+"http://requestercompany.com/reqservice/C9c2a4576bde9875a57d9875c"
+}
+
+
diff --git a/Utilities/RDFTranslator/build.sh b/Utilities/RDFTranslator/build.sh
new file mode 100755 (executable)
index 0000000..13523f3
--- /dev/null
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+mkdir sockettranslator
+mkdir pipetranslator
+mkdir cmdlinetranslator
+mkdir rdftranslator
+
+ln -s ../../javalib/ lib
+
+echo "  *** Compile standalone classes ***"
+ant socket
+ant pipe
+ant cmdline
+
+echo "  *** Create tsrequester.jar ***"
+ant servlet
diff --git a/Utilities/RDFTranslator/client_start.sh b/Utilities/RDFTranslator/client_start.sh
new file mode 100644 (file)
index 0000000..71326c9
--- /dev/null
@@ -0,0 +1,2 @@
+cat input.txt | nc localhost 1234
+
diff --git a/Utilities/RDFTranslator/server_start.sh b/Utilities/RDFTranslator/server_start.sh
new file mode 100644 (file)
index 0000000..d329c70
--- /dev/null
@@ -0,0 +1 @@
+java -cp dist/rdftranslator.jar:lib/* rdftranslator.Translator 1234
diff --git a/Utilities/RDFTranslator/src/TestClient.java b/Utilities/RDFTranslator/src/TestClient.java
new file mode 100644 (file)
index 0000000..8de2255
--- /dev/null
@@ -0,0 +1,61 @@
+
+
+import java.net.*;
+import java.io.*;
+
+public class TestClient
+{
+       public static void main(String [] args)
+       {
+               String msg = "input=JSON-LD&output=TURTLE&{\"@context\": \"http://seas.asema.com/webapps/jsonld/context.jsonld\", \"@type\": \"ts:Evaluation\"}"; 
+               //String msg = "helloserver";
+               String serverName = args[0];
+               int port = Integer.parseInt(args[1]);
+               try
+               {
+                       System.out.println("Connecting to " + serverName +
+                                       " on port " + port);
+                       Socket client = new Socket(serverName, port);
+                       System.out.println("Just connected to " 
+                                       + client.getRemoteSocketAddress());
+
+                       //OutputStream outToServer = client.getOutputStream();
+                       //DataOutputStream out = new DataOutputStream(outToServer);
+                       //out.writeUTF(msg);
+                       
+                       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
+                       BufferedReader inStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
+                       out.write(msg);
+                       //out.write("\n");
+                       out.newLine();
+                       out.flush();
+                       client.shutdownOutput();
+                       
+                       // read data in
+                       StringBuffer inputLine = new StringBuffer();
+                       String tmp; 
+                       while ((tmp = inStream.readLine()) != null) {
+                               inputLine.append(tmp);
+                               System.out.println(tmp);
+                       }
+                       String in = inputLine.toString();
+                       inStream.close();
+                       System.out.println("Server says " + in);
+
+                       
+                       //InputStream inFromServer = client.getInputStream();
+                       //DataInputStream in =
+                       //              new DataInputStream(inFromServer);
+                       //System.out.println("Server says " + in.readUTF());
+                       
+                       
+                       client.close();
+
+               }catch(IOException e)
+               {
+                       e.printStackTrace();
+                       System.out.println("Host and port has to be given as arguments. e.g.\n" +
+                                       "java TestClient 127.0.0.1 1234");
+               }
+       }
+}
\ No newline at end of file
diff --git a/Utilities/RDFTranslator/src/rdftranslator/CmdLineTranslator.java b/Utilities/RDFTranslator/src/rdftranslator/CmdLineTranslator.java
new file mode 100644 (file)
index 0000000..f5bd8b4
--- /dev/null
@@ -0,0 +1,65 @@
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.rdf.model.ModelFactory;
+
+public class CmdLineTranslator
+{
+       public static void main(String [] args)
+       {
+               String inputFormat = "";
+               String outputFormat = "";
+
+               if (args.length > 1) {
+                       inputFormat = args[0];
+                       outputFormat = args[1];
+                       
+                       try
+                       {
+                               BufferedReader cmdIn = new BufferedReader(new InputStreamReader(System.in));    
+                               StringBuffer buffer = new StringBuffer();
+                               String tmp; 
+                               while ((tmp = cmdIn.readLine()) != null) {
+                                       buffer.append(tmp);
+                               }
+                       
+                               Model model = ModelFactory.createDefaultModel();
+                               System.out.println("model created " + buffer.toString().getBytes(StandardCharsets.UTF_8));
+                               // Read input RDF
+                               try {
+                                       model.read(new ByteArrayInputStream(buffer.toString().getBytes(StandardCharsets.UTF_8)), null, inputFormat);
+                                       System.out.println("model read");
+                               } catch(Exception e) {
+                                       System.out.println("Error while reading in (parsing) the RDF document: " + e);
+                               }
+
+                               // Write output RDF
+                               try {
+                                       BufferedWriter cmdOut = new BufferedWriter(new OutputStreamWriter(System.out));
+                                       StringWriter writer = new StringWriter();
+
+                                       // write model to writer with given RDF serialization (e.g. TURTLE or JSON-LD)
+                                       model.write(writer, outputFormat);
+                                       
+                                       // and output it
+                                       cmdOut.write(writer.toString());
+                                       cmdOut.flush();
+
+                               } catch(Exception e) {
+                                       System.out.println("Error while writing out (serializing) the RDF document: " + e);
+                               }
+
+                       } catch(IOException e) {
+                               e.printStackTrace();
+                       }
+               }
+       }
+}
diff --git a/Utilities/RDFTranslator/translate.jsp b/Utilities/RDFTranslator/translate.jsp
new file mode 100644 (file)
index 0000000..799254a
--- /dev/null
@@ -0,0 +1,162 @@
+<%@page language="java" contentType="text/json" pageEncoding="UTF-8" import="java.io.*,java.net.*,javax.servlet.http.*,org.json.*,seasRegistration.*,org.apache.commons.codec.digest.DigestUtils,java.util.stream.Collectors,org.apache.jena.rdf.model.*,java.nio.charset.StandardCharsets"%><%
+ if ("OPTIONS".equals(request.getMethod())){
+        doOptions(request, response);
+ } else {
+ if ("POST".equals(request.getMethod())){
+        doPost(request, response);
+ } else
+         doGet(request, response);
+ }
+
+%><%!
+
+        public void jspInit() {
+        System.out.println("SEAS Registration Service (proxy) Servlet Initializing..");
+        
+        // registration service (fuseki) uri
+        String serverUri = "http://seas.asema.com/webapps/fuseki/rs";
+
+        // create new registration client
+        SeasRegistrationClient registration = new SeasRegistrationClient();
+        
+        // create registration model
+        RegistrationModel model = registration.createRegistrationModel();
+
+        // create HTTP client
+        HttpClient httpClient = registration.createHttpClient(serverUri);
+
+        // Set how much output is desired
+        httpClient.setDebugLevel(httpClient.NO_OUTPUT); // options: NO_OUTPUT, INFO, DEBUG
+
+
+        System.out.println( "..SEAS Registration Service (proxy) Servlet Initialized.");
+               }
+
+
+        protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+                response.setHeader("Access-Control-Allow-Origin", "*");
+                response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
+                response.setHeader("Access-Control-Allow-Headers", "X-PROTOTYPE-VERSION, X-REQUESTED-WITH");
+                super.doOptions(request, response);
+        }
+
+        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+                response.setContentType("text/html");
+                PrintWriter out = response.getWriter();
+                out.println("HTTP GET method not supported. Try HTTP POST.");
+        }
+
+        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+                response.setHeader("Access-Control-Allow-Origin", "*");
+                response.setContentType("application/ld+json");
+                PrintWriter out = response.getWriter();
+
+                String charset = "";
+                String contentType = "";
+                String reqBody = "";
+                String ret = "";
+
+                // verify content-type and read charset
+                String contentTypeHeader = request.getContentType();
+                String[] values = contentTypeHeader.split(";");
+
+                // get charset
+                for (String value : values) {
+                    value = value.trim();
+
+                    if (value.toLowerCase().startsWith("charset=")) {
+                        charset = value.substring("charset=".length());
+                    }
+                }
+                contentType = values[0].trim();
+
+                String input = request.getParameter("input").toUpperCase();
+                String output = request.getParameter("output").toUpperCase();
+
+                // read request body
+                try{
+                    reqBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
+                }catch(Exception e){
+                    out.println(parseError(request));
+                    return;
+                }
+
+                if( !input.equalsIgnoreCase("TURTLE") && !input.equalsIgnoreCase("RDF/XML") && 
+                !input.equalsIgnoreCase("JSON-LD") && !input.equalsIgnoreCase("N-TRIPLE") && !input.equalsIgnoreCase("N3")) {
+                    out.println("Format error: only TURTLE, RDF/XML, JSON-LD, N-TRIPLE and N3 input and output serializations are supported.");
+                    return;                    
+                }
+
+                if( !output.equalsIgnoreCase("TURTLE") && !output.equalsIgnoreCase("RDF/XML") && 
+                !output.equalsIgnoreCase("JSON-LD") && !output.equalsIgnoreCase("N-TRIPLE") && !output.equalsIgnoreCase("N3")) {
+                    out.println("Format error: only TURTLE, RDF/XML, JSON-LD, N-TRIPLE and N3 input and output serializations are supported.");
+                    return;                    
+                }
+
+                Model model = ModelFactory.createDefaultModel();
+
+                // read body in as RDF
+                try{
+                    InputStream in = new ByteArrayInputStream(reqBody.getBytes(StandardCharsets.UTF_8));
+                    model.read(in, null, input);
+                }catch(Exception e){
+                    out.println("Error while reading in (parsing) the RDF document.");
+                    return;
+                }
+
+
+                // write response body
+                try{
+                    StringWriter writer = new StringWriter();
+                    // write model to writer with given RDF serialization (e.g. TURTLE or JSON-LD)
+                    model.write( writer, output);
+                    // writer to string
+                    ret = writer.toString();
+                }catch(Exception e){
+                    out.println("Error while writing out (serializing) the RDF document.");
+                    return;
+                }
+
+                // send response
+                out.println(ret);
+        }
+
+        private String invalidRequest(HttpServletRequest request)
+        {
+            return "Invalid request error.";
+        }
+
+        private String parseError(HttpServletRequest request)
+        {
+            return "Parse error.";
+        }
+
+        private String contentTypeToRDFSerialization(String contentType)
+        {
+            return contentType.equalsIgnoreCase("application/ld+json") ? "JSON-LD" : 
+                   contentType.equalsIgnoreCase("text/turtle") ? "TURTLE" :
+                   contentType.equalsIgnoreCase("application/rdf+xml") ? "RDF/XML" :"TURTLE";
+        }
+
+        private String readUrl(String url){
+                String result = "";
+
+                BufferedReader in = null;
+                String inputLine;
+
+                try {
+                        URL u = new URL(url);
+                        in =new BufferedReader(new InputStreamReader(u.openStream()));
+                        while ((inputLine = in.readLine()) != null){
+                                result += inputLine+"\n";
+                        }
+                } catch (Exception exc){
+                        result = "exc.getMessage()";
+                } finally {
+                  try { in.close(); } catch (Exception ex){;}
+                  in = null;
+                }
+                return result;
+        }
+
+%>
\ No newline at end of file