From b7bf3548730cfe8278147189127197b62b4be16e Mon Sep 17 00:00:00 2001 From: jyotsna-tarento Date: Tue, 3 Apr 2018 15:33:46 +0530 Subject: [PATCH] Issue #131, #134 removing unused files, adding middleware --- .circleci/config.yml | 43 ----- .../test/RegistryIntegrationSteps.java | 2 +- .../registry/middleware/util/Constants.java | 2 +- .../jsonld-conversion/pom.xml | 67 ++++++-- .../middleware/impl/JSONLDConverter.java | 62 +++++++ .../middleware/impl/RdfToJsonldConverter.java | 55 ------ .../middleware/impl/JSONLDConversionTest.java | 71 ++++++++ .../src/test/resources/teacher.jsonld | 162 ++++++++++++++++++ .../middleware/impl/JsonldToRdfConverter.java | 83 --------- .../java/io/opensaber/pojos/Response.java | 1 + java/registry-interceptor/pom.xml | 6 + ....java => JSONLDConversionInterceptor.java} | 26 +-- .../interceptor/JsonldToRdfInterceptor.java | 63 ------- .../handler/BaseResponseHandler.java | 24 ++- .../interceptor/handler/ResponseWrapper.java | 9 +- .../registry/config/GenericConfiguration.java | 17 +- .../registry/controller/BaseController.java | 1 + .../controller/RegistryController.java | 8 +- java/utils/converters/jsonldToRDF/pom.xml | 16 -- .../converters/JsonLdToRdfConverter.java | 47 ----- 20 files changed, 414 insertions(+), 351 deletions(-) delete mode 100644 .circleci/config.yml create mode 100644 java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/JSONLDConverter.java delete mode 100644 java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/RdfToJsonldConverter.java create mode 100644 java/middleware/registry-middleware/jsonld-conversion/src/test/java/io/opensaber/registry/middleware/impl/JSONLDConversionTest.java create mode 100644 java/middleware/registry-middleware/jsonld-conversion/src/test/resources/teacher.jsonld delete mode 100644 java/middleware/registry-middleware/rdf-conversion/src/main/java/io/opensaber/registry/middleware/impl/JsonldToRdfConverter.java rename java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/{RdfToJsonldInterceptor.java => JSONLDConversionInterceptor.java} (56%) delete mode 100644 java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JsonldToRdfInterceptor.java delete mode 100644 java/utils/converters/jsonldToRDF/pom.xml delete mode 100644 java/utils/converters/jsonldToRDF/src/main/java/io/opensaber/utils/converters/JsonLdToRdfConverter.java diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 010de9686..000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,43 +0,0 @@ -# Java Maven CircleCI 2.0 configuration file -# -# Check https://circleci.com/docs/2.0/language-java/ for more details -# -version: 2 -jobs: - build: - docker: - # specify the version you desire here - - image: circleci/openjdk:9-jdk - - # Specify service dependencies here if necessary - # CircleCI maintains a library of pre-built images - # documented at https://circleci.com/docs/2.0/circleci-images/ - # - image: circleci/postgres:9.4 - - working_directory: ~/open-saber/java - - environment: - # Customize the JVM maximum heap limit - MAVEN_OPTS: -Xmx3200m - - steps: - - checkout - - # Download and cache dependencies - - restore_cache: - keys: - - v1-dependencies-{{ checksum "pom.xml" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - - run: mvn dependency:go-offline - - - save_cache: - paths: - - ~/.m2 - key: v1-dependencies-{{ checksum "pom.xml" }} - - # run tests! - - run: mvn test - - diff --git a/java/cukes/src/test/java/io/opensaber/registry/test/RegistryIntegrationSteps.java b/java/cukes/src/test/java/io/opensaber/registry/test/RegistryIntegrationSteps.java index 55d621ed8..a5aaa2ec4 100644 --- a/java/cukes/src/test/java/io/opensaber/registry/test/RegistryIntegrationSteps.java +++ b/java/cukes/src/test/java/io/opensaber/registry/test/RegistryIntegrationSteps.java @@ -5,7 +5,6 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; -import java.io.InputStreamReader; import java.io.StringReader; import java.util.Map; @@ -38,6 +37,7 @@ import io.opensaber.pojos.Response; import io.opensaber.pojos.Response.Status; + public class RegistryIntegrationSteps extends RegistryTestBase{ diff --git a/java/middleware-commons/src/main/java/io/opensaber/registry/middleware/util/Constants.java b/java/middleware-commons/src/main/java/io/opensaber/registry/middleware/util/Constants.java index efa4656df..d4e1434ba 100644 --- a/java/middleware-commons/src/main/java/io/opensaber/registry/middleware/util/Constants.java +++ b/java/middleware-commons/src/main/java/io/opensaber/registry/middleware/util/Constants.java @@ -3,7 +3,7 @@ public class Constants { public static final String REQUEST_ATTRIBUTE_NAME = "dataObject"; - public static final String RESPONSE_ATTRIBUTE_NAME = "dataObject"; + public static final String RESPONSE_ATTRIBUTE = "responseModel"; public static final String ATTRIBUTE_NAME = "dataObject"; public static final String REQUEST_ATTRIBUTE= "requestModel"; public static final String RDF_OBJECT = "rdf"; diff --git a/java/middleware/registry-middleware/jsonld-conversion/pom.xml b/java/middleware/registry-middleware/jsonld-conversion/pom.xml index 5bca4d5cb..cc7f9f302 100644 --- a/java/middleware/registry-middleware/jsonld-conversion/pom.xml +++ b/java/middleware/registry-middleware/jsonld-conversion/pom.xml @@ -1,22 +1,59 @@ - - 4.0.0 - - io.opensaber - registry-middleware - 0.0.1-SNAPSHOT - - - io.opensaber.middleware - jsonld-conversion - 0.0.1-SNAPSHOT - JSON-LD Conversion - Conversion from rdf to json-ld - - + + 4.0.0 + + io.opensaber + registry-middleware + 0.0.1-SNAPSHOT + + + io.opensaber.middleware + jsonld-conversion + 0.0.1-SNAPSHOT + JSON-LD Conversion + Conversion from rdf to json-ld + + + 4.12 + + + io.opensaber middleware-commons 0.0.1-SNAPSHOT + + org.apache.jena + jena-arq + 3.6.0 + + + org.slf4j + slf4j-log4j12 + + + + + io.open-saber + jenardf4j + 1.0.0-SNAPSHOT + + + org.eclipse.rdf4j + rdf4j-model + 2.2.4 + + + io.open-saber + shaclex + 0.0.1-SNAPSHOT + + + junit + junit + ${junit.version} + test + \ No newline at end of file diff --git a/java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/JSONLDConverter.java b/java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/JSONLDConverter.java new file mode 100644 index 000000000..0e92e958d --- /dev/null +++ b/java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/JSONLDConverter.java @@ -0,0 +1,62 @@ +package io.opensaber.registry.middleware.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import org.apache.jena.ext.com.google.common.io.ByteStreams; +import org.apache.jena.query.DatasetFactory; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.riot.JsonLDWriteContext; +import org.apache.jena.riot.RDFDataMgr; +import org.apache.jena.riot.WriterDatasetRIOT; +import org.apache.jena.riot.system.PrefixMap; +import org.apache.jena.riot.system.RiotLib; +import org.apache.jena.sparql.core.DatasetGraph; + +import io.opensaber.converters.JenaRDF4J; +import io.opensaber.registry.middleware.BaseMiddleware; +import io.opensaber.registry.middleware.MiddlewareHaltException; +import io.opensaber.registry.middleware.util.Constants; + +/** + * + * @author jyotsna + * + */ +public class JSONLDConverter implements BaseMiddleware{ + + private static final String INVALID_RDF_DATA = "RDF data is invalid!"; + + public Map execute(Map mapData) throws IOException, MiddlewareHaltException { + Object responseData = mapData.get(Constants.RESPONSE_ATTRIBUTE); + if(responseData != null){ + if(responseData instanceof org.eclipse.rdf4j.model.Model){ + Model jenaEntityModel = JenaRDF4J.asJenaModel((org.eclipse.rdf4j.model.Model)responseData); + DatasetGraph g = DatasetFactory.create(jenaEntityModel).asDatasetGraph(); + JsonLDWriteContext ctx = new JsonLDWriteContext(); + InputStream is = this.getClass().getClassLoader().getResourceAsStream("frame.json"); + String fileString = new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8); + ctx.setFrame(fileString); + WriterDatasetRIOT w = RDFDataMgr.createDatasetWriter(org.apache.jena.riot.RDFFormat.JSONLD_FRAME_FLAT) ; + PrefixMap pm = RiotLib.prefixMap(g); + String base = null; + StringWriter sWriterJena = new StringWriter(); + w.write(sWriterJena, g, pm, base, ctx) ; + String jenaJSON = sWriterJena.toString(); + mapData.put(Constants.RESPONSE_ATTRIBUTE, jenaJSON); + } else{ + throw new MiddlewareHaltException(INVALID_RDF_DATA); + } + } + + return mapData; + } + + public Map next(Map mapData) throws IOException { + return new HashMap(); + } +} diff --git a/java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/RdfToJsonldConverter.java b/java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/RdfToJsonldConverter.java deleted file mode 100644 index aebcb8c94..000000000 --- a/java/middleware/registry-middleware/jsonld-conversion/src/main/java/io/opensaber/registry/middleware/impl/RdfToJsonldConverter.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.opensaber.registry.middleware.impl; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.util.StringUtils; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.github.jsonldjava.core.JsonLdProcessor; -import com.github.jsonldjava.utils.JsonUtils; - -import io.opensaber.registry.middleware.BaseMiddleware; -import io.opensaber.registry.middleware.util.Constants; - -/** - * - * @author jyotsna - * - */ -public class RdfToJsonldConverter implements BaseMiddleware{ - - public Map execute(Map mapData) throws IOException { - String responseData = mapData.get(Constants.ATTRIBUTE_NAME).toString(); - if(!StringUtils.isEmpty(responseData)){ - String rdfStr = convertToJsonld(responseData); - if(!StringUtils.isEmpty(rdfStr)){ - mapData.put(Constants.ATTRIBUTE_NAME, rdfStr); - }else{ - mapData.put(Constants.ATTRIBUTE_NAME, null); - } - } - return mapData; - } - - public Map next(Map mapData) throws IOException { - return new HashMap(); - } - - - public String convertToJsonld(String str){ - String rdfStr = ""; - try{ - Object compact = JsonLdProcessor.fromRDF(str); - rdfStr = JsonUtils.toPrettyString(compact); - }catch(JsonGenerationException e){ - e.printStackTrace(); - } - catch(Exception e){ - e.printStackTrace(); - } - return rdfStr; - } - -} diff --git a/java/middleware/registry-middleware/jsonld-conversion/src/test/java/io/opensaber/registry/middleware/impl/JSONLDConversionTest.java b/java/middleware/registry-middleware/jsonld-conversion/src/test/java/io/opensaber/registry/middleware/impl/JSONLDConversionTest.java new file mode 100644 index 000000000..5efdacb50 --- /dev/null +++ b/java/middleware/registry-middleware/jsonld-conversion/src/test/java/io/opensaber/registry/middleware/impl/JSONLDConversionTest.java @@ -0,0 +1,71 @@ +package io.opensaber.registry.middleware.impl; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.impl.TreeModel; +import org.eclipse.rdf4j.model.util.ModelBuilder; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import io.opensaber.converters.JenaRDF4J; +import io.opensaber.registry.middleware.BaseMiddleware; +import io.opensaber.registry.middleware.MiddlewareHaltException; +import io.opensaber.registry.middleware.util.Constants; +import io.opensaber.validators.shex.shaclex.ShaclexValidator; + +public class JSONLDConversionTest { + + private static final String TEACHER_JSONLD = "teacher.jsonld"; + private static final String FORMAT = "JSON-LD"; + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + Map mapData; + private BaseMiddleware m; + private Model rdfModel; + + private void setup() throws IOException, URISyntaxException{ + m = new JSONLDConverter(); + String jsonLDData = Paths.get(getPath(TEACHER_JSONLD)).toString(); + Path filePath = Paths.get(jsonLDData); + String jsonld = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8); + org.apache.jena.rdf.model.Model model = ShaclexValidator.parse(jsonld, FORMAT); + rdfModel = JenaRDF4J.asRDF4JModel(model); + } + + private URI getPath(String file) throws URISyntaxException { + return this.getClass().getClassLoader().getResource(file).toURI(); + } + + @Test + public void testHaltIfInvalidRdf() throws MiddlewareHaltException, IOException, URISyntaxException{ + expectedEx.expect(MiddlewareHaltException.class); + expectedEx.expectMessage("RDF data is invalid!"); + setup(); + mapData = new HashMap(); + mapData.put(Constants.RESPONSE_ATTRIBUTE, "{}"); + m.execute(mapData); + } + + @Test + public void testValidRdf() throws URISyntaxException, IOException, MiddlewareHaltException{ + setup(); + mapData = new HashMap(); + mapData.put(Constants.RESPONSE_ATTRIBUTE, rdfModel); + m.execute(mapData); + } + +} diff --git a/java/middleware/registry-middleware/jsonld-conversion/src/test/resources/teacher.jsonld b/java/middleware/registry-middleware/jsonld-conversion/src/test/resources/teacher.jsonld new file mode 100644 index 000000000..b5d3cbf42 --- /dev/null +++ b/java/middleware/registry-middleware/jsonld-conversion/src/test/resources/teacher.jsonld @@ -0,0 +1,162 @@ +{ + "@context": + { + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdfs": "http://www.w3.org/2000/01/rdf-schema#", + "teacher": "http://example.com/voc/teacher/1.0.0/", + "xsd": "http://www.w3.org/2001/XMLSchema#", + "@vocab": "http://example.com/voc/teacher/1.0.0/" + }, + + "@id": "teacher:fa7740c185fb247729c7296c36b5c1257b1", + "@type": "Teacher", + "serialNum": "12", + "teacherCode": "12234", + "nationalIdentifier": "1234567890123456", + "teacherName": "Marvin Pande", + "gender": + { + "@id": "teacher:GenderTypeCode-MALE" + }, + + "birthDate": "06-12-1990", + "socialCategory": + { + "@id": "teacher:SocialCategoryTypeCode-GENERAL" + }, + + "highestAcademicQualification": + { + "@id": "teacher:AcademicQualificationTypeCode-PHD" + }, + + "highestTeacherQualification": + { + "@id": "teacher:TeacherQualificationTypeCode-MED" + }, + + "yearOfJoiningService": "2014", + "teachingRole": + { + "@type": "TeachingRole", + "teacherType": + { + "@id": "teacher:TeacherTypeCode-HEAD" + }, + + "appointmentType": + { + "@id": "teacher:TeacherAppointmentTypeCode-REGULAR" + }, + + "classesTaught": + { + "@id": "teacher:ClassTypeCode-SECONDARYANDHIGHERSECONDARY" + }, + + "appointedForSubjects": + { + "@id": "teacher:SubjectCode-MATH" + }, + + "mainSubjectsTaught": + [ + { + "@id": "teacher:SubjectCode-PHYSICS" + }, + + { + "@id": "teacher:SubjectCode-MATH" + } + ], + + "appointmentYear": "2015" + }, + + "inServiceTeacherTrainingFromBRC": + { + "@type": "InServiceTeacherTrainingFromBlockResourceCentre", + "teacher:daysOfInServiceTeacherTraining": "10" + }, + + "inServiceTeacherTrainingFromCRC": + { + "@type": "InServiceTeacherTrainingFromClusterResourceCentre", + "teacher:daysOfInServiceTeacherTraining": "2" + }, + + "inServiceTeacherTrainingFromDIET": + { + "@type": "InServiceTeacherTrainingFromDIET", + "teacher:daysOfInServiceTeacherTraining": "5.5" + }, + + "inServiceTeacherTrainingFromOthers": + { + "@type": "InServiceTeacherTrainingFromOthers", + "teacher:daysOfInServiceTeacherTraining": "3.5" + }, + + "nonTeachingAssignmentsForAcademicCalendar": + { + "@type": "NonTeachingAssignmentsForAcademicCalendar", + "teacher:daysOfNonTeachingAssignments": "6" + }, + + "basicProficiencyLevel": + [ + { + "@type": "BasicProficiencyLevel", + "proficiencySubject": + { + "@id": "teacher:SubjectCode-MATH" + }, + + "proficiencyAcademicQualification": + { + "@id": "teacher:AcademicQualificationTypeCode-PHD" + } + }, + + { + "@type": "BasicProficiencyLevel", + "proficiencySubject": + { + "@id": "teacher:SubjectCode-ENGLISH" + }, + + "proficiencyAcademicQualification": + { + "@id": "teacher:AcademicQualificationTypeCode-HIGHERSECONDARY" + } + }, + + { + "@type": "BasicProficiencyLevel", + "proficiencySubject": + { + "@id": "teacher:SubjectCode-SOCIALSTUDIES" + }, + + "proficiencyAcademicQualification": + { + "@id": "teacher:AcademicQualificationTypeCode-SECONDARY" + } + } + ], + + "disabilityType": + { + "@id": "teacher:DisabilityCode-NA" + }, + + "trainedForChildrenSpecialNeeds": + { + "@id": "teacher:YesNoCode-YES" + }, + + "teacher:trainedinUseOfComputer": + { + "@id": "teacher:YesNoCode-YES" + } +} \ No newline at end of file diff --git a/java/middleware/registry-middleware/rdf-conversion/src/main/java/io/opensaber/registry/middleware/impl/JsonldToRdfConverter.java b/java/middleware/registry-middleware/rdf-conversion/src/main/java/io/opensaber/registry/middleware/impl/JsonldToRdfConverter.java deleted file mode 100644 index 7858d8d07..000000000 --- a/java/middleware/registry-middleware/rdf-conversion/src/main/java/io/opensaber/registry/middleware/impl/JsonldToRdfConverter.java +++ /dev/null @@ -1,83 +0,0 @@ -/*package io.opensaber.registry.middleware.impl; - - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.springframework.util.StringUtils; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.github.jsonldjava.core.JsonLdConsts; -import com.github.jsonldjava.core.JsonLdOptions; -import com.github.jsonldjava.core.JsonLdProcessor; -import com.github.jsonldjava.utils.JsonUtils; - - - -import io.opensaber.registry.middleware.BaseMiddleware; -import io.opensaber.registry.middleware.util.Constants; - -*//** - * - * @author jyotsna - * - *//* -public class JsonldToRdfConverter implements BaseMiddleware{ - - //public static String rdfVar = ""; - - public Map execute(Map mapData) throws IOException{ - return getRdf(mapData.get(Constants.ATTRIBUTE_NAME)); - } - - public Map next(Map mapData) throws IOException{ - return new HashMap(); - - } - - public Map getRdf(Object obj) throws IOException{ - Map attributeMap = new HashMap(); - if(!StringUtils.isEmpty(obj.toString())){ - String rdf = convertToRdf(obj.toString()); - - //attributeMap.put(Constants.ATTRIBUTE_NAME, rdfModel); - } - return attributeMap; - - } - - - public String convertToRdf(String body){ - String rdf = null; - try{ - JsonLdOptions options = new JsonLdOptions(); - options.format = JsonLdConsts.APPLICATION_NQUADS; - //final JsonLdTripleCallback callback = new RDF4JJSONLDTripleCallback(Rio.createWriter(sesameOutputFormat, System.out)); - //final JenaTripleCallback callback = new JenaTripleCallback(); - Object rdfObj = JsonLdProcessor.toRDF(JsonUtils.fromString(body), options); - System.out.println(rdfObj.toString()); - return rdfObj.toString(); - }catch(JsonGenerationException e){ - e.printStackTrace(); - } - catch(Exception e){ - e.printStackTrace(); - } - return rdf; - } - - public static void main(String args[]){ - JsonldToRdfConverter jsonldToRdfConverter= new JsonldToRdfConverter(); - jsonldToRdfConverter.convertToRdf(getJsonString()); - } - - public static String getJsonString(){ - return "{\"@context\": {\"schema\": \"http:schema.org/\",\"opensaber\": \"http:open-saber.org/vocab/core/#\"},\"@type\": " - + "[\"schema:Person\",\"opensabre:Teacher\"],\"schema:identifier\": \"b6ad2941-fac3-4c72-94b7-eb638538f55f\",\"schema:image\": null," - + "\"schema:nationality\": \"Indian\",\"schema:birthDate\": \"2011-12-06\",\"schema:name\": \"Marvin\",\"schema:gender\": \"male\"," - + "\"schema:familyName\":\"Pande\",\"opensaber:languagesKnownISO\": [\"en\",\"hi\"]}"; - } - -} -*/ \ No newline at end of file diff --git a/java/pojos/src/main/java/io/opensaber/pojos/Response.java b/java/pojos/src/main/java/io/opensaber/pojos/Response.java index 9e5fdaf9a..fe3b38fe4 100644 --- a/java/pojos/src/main/java/io/opensaber/pojos/Response.java +++ b/java/pojos/src/main/java/io/opensaber/pojos/Response.java @@ -81,4 +81,5 @@ public void setResult(Map result) { public String getResponseCode() { return responseCode; } + } diff --git a/java/registry-interceptor/pom.xml b/java/registry-interceptor/pom.xml index fd470dd20..4b085acb4 100644 --- a/java/registry-interceptor/pom.xml +++ b/java/registry-interceptor/pom.xml @@ -104,6 +104,12 @@ 5.0.2.RELEASE + + org.json + json + 20180130 + + org.springframework.boot spring-boot-starter-test diff --git a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/RdfToJsonldInterceptor.java b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JSONLDConversionInterceptor.java similarity index 56% rename from java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/RdfToJsonldInterceptor.java rename to java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JSONLDConversionInterceptor.java index 6f99e03d5..1b5957f3d 100644 --- a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/RdfToJsonldInterceptor.java +++ b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JSONLDConversionInterceptor.java @@ -1,28 +1,31 @@ package io.opensaber.registry.interceptor; -import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import io.opensaber.registry.interceptor.handler.BaseResponseHandler; -import io.opensaber.registry.middleware.impl.RdfToJsonldConverter; +import io.opensaber.registry.middleware.impl.JSONLDConverter; import io.opensaber.registry.middleware.util.Constants; @Component -public class RdfToJsonldInterceptor extends BaseResponseHandler implements HandlerInterceptor{ +public class JSONLDConversionInterceptor extends BaseResponseHandler implements HandlerInterceptor{ - private RdfToJsonldConverter rdfToJsonldConverter; + private static Logger logger = LoggerFactory.getLogger(JSONLDConversionInterceptor.class); + + private JSONLDConverter jsonldConverter; @Autowired - public RdfToJsonldInterceptor(RdfToJsonldConverter rdfToJsonldConverter){ - this.rdfToJsonldConverter = rdfToJsonldConverter; + public JSONLDConversionInterceptor(JSONLDConverter jsonldConverter){ + this.jsonldConverter = jsonldConverter; } @Override @@ -34,13 +37,12 @@ public boolean preHandle(HttpServletRequest request, @Override public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + logger.info("RESPONSE COMMITTED:"+response.isCommitted()); setResponse(response); - String responseBody = getResponseContent(); - Map responseMap = new HashMap(); - responseMap.put(Constants.RESPONSE_ATTRIBUTE_NAME, responseBody); - responseMap = rdfToJsonldConverter.execute(responseMap); - if(responseMap.get(Constants.RESPONSE_ATTRIBUTE_NAME)!=null){ - writeResponseBody(responseMap.get(Constants.RESPONSE_ATTRIBUTE_NAME).toString()); + Map responseMap = jsonldConverter.execute(getResponseBodyMap()); + if(responseMap.get(Constants.RESPONSE_ATTRIBUTE)!=null){ + setFormattedResponse(responseMap.get(Constants.RESPONSE_ATTRIBUTE).toString()); + writeResponseBody(getFormattedResponse()); } response = getResponse(); } diff --git a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JsonldToRdfInterceptor.java b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JsonldToRdfInterceptor.java deleted file mode 100644 index d1a345293..000000000 --- a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/JsonldToRdfInterceptor.java +++ /dev/null @@ -1,63 +0,0 @@ -/*package io.opensaber.registry.interceptor; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.HandlerInterceptor; -import org.springframework.web.servlet.ModelAndView; - -import io.opensaber.registry.interceptor.handler.BaseRequestHandler; -import io.opensaber.registry.interceptor.handler.RequestWrapper; -import io.opensaber.registry.middleware.impl.JsonldToRdfConverter; -import io.opensaber.registry.middleware.util.Constants; - - -*//** - * - * @author jyotsna - * - *//* -@Component -public class JsonldToRdfInterceptor extends BaseRequestHandler implements HandlerInterceptor{ - - private JsonldToRdfConverter jsonldToRdfConverter; - - @Autowired - public JsonldToRdfInterceptor(JsonldToRdfConverter jsonldToRdfConverter){ - this.jsonldToRdfConverter=jsonldToRdfConverter; - } - - @Override - public boolean preHandle(HttpServletRequest request, - HttpServletResponse response, Object object) throws Exception { - setRequest(request); - Map attributeMap = jsonldToRdfConverter.execute(getRequestBodyMap()); - setRequestAttributes(attributeMap); - request = getRequest(); - requestWrapper = new RequestWrapper(request); - System.out.println("Request body after interceptor:"+requestWrapper.getBody()); - if(request.getAttribute(Constants.REQUEST_ATTRIBUTE_NAME)!=null){ - return true; - } - return false; - } - - @Override - public void postHandle(HttpServletRequest request,HttpServletResponse response, - Object handler, ModelAndView modelAndView) throws Exception { - - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, - Object handler, Exception ex) { - - } - - -} -*/ \ No newline at end of file diff --git a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/BaseResponseHandler.java b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/BaseResponseHandler.java index 5b4cbad9c..16f54170f 100644 --- a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/BaseResponseHandler.java +++ b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/BaseResponseHandler.java @@ -9,9 +9,13 @@ import javax.servlet.http.HttpServletResponse; import com.google.gson.GsonBuilder; +import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import io.opensaber.pojos.ValidationResponse; import io.opensaber.pojos.ValidationResponseSerializer; +import io.opensaber.registry.middleware.util.Constants; + +import org.json.JSONObject; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -29,6 +33,7 @@ public class BaseResponseHandler { protected HttpServletResponse response; protected ResponseWrapper responseWrapper; + protected Response formattedResponse; public void setResponse(HttpServletResponse response) throws IOException { this.response = response; @@ -50,9 +55,26 @@ public HttpServletResponse getResponse(){ } public String getResponseContent() throws IOException { - //setResponseWrapper(); + setResponseWrapper(); return responseWrapper.getResponseContent(); } + + public void setFormattedResponse(String json){ + JSONObject jsonObj = new JSONObject(json); + formattedResponse.setResult(jsonObj.toMap()); + } + + public String getFormattedResponse(){ + Gson gson = new Gson(); + return gson.toJson(formattedResponse); + } + + public Map getResponseBodyMap() throws IOException { + Gson gson = new Gson(); + String responseBody = getResponseContent(); + formattedResponse = gson.fromJson(responseBody, Response.class); + return formattedResponse.getResult(); + } public Map getResponseHeaderMap() throws IOException { //setResponseWrapper(); diff --git a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/ResponseWrapper.java b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/ResponseWrapper.java index 97c5db096..b33e1dc8c 100644 --- a/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/ResponseWrapper.java +++ b/java/registry-interceptor/src/main/java/io/opensaber/registry/interceptor/handler/ResponseWrapper.java @@ -2,15 +2,17 @@ import java.io.BufferedWriter; +import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; - import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.util.ContentCachingResponseWrapper; +import static java.nio.charset.StandardCharsets.UTF_8; /** * @@ -59,8 +61,9 @@ public void writeResponseBody(String content) { * * @return */ - public String getResponseContent() { - return new String(this.getContentAsByteArray()); + public String getResponseContent() throws IOException{ + //return new String(this.getContentAsByteArray()); + return IOUtils.toString(this.getContentInputStream(), UTF_8); } diff --git a/java/registry/src/main/java/io/opensaber/registry/config/GenericConfiguration.java b/java/registry/src/main/java/io/opensaber/registry/config/GenericConfiguration.java index af79272df..31786e2a3 100644 --- a/java/registry/src/main/java/io/opensaber/registry/config/GenericConfiguration.java +++ b/java/registry/src/main/java/io/opensaber/registry/config/GenericConfiguration.java @@ -29,13 +29,14 @@ import io.opensaber.registry.authorization.AuthorizationFilter; import io.opensaber.registry.exception.CustomExceptionHandler; import io.opensaber.registry.interceptor.AuthorizationInterceptor; +import io.opensaber.registry.interceptor.JSONLDConversionInterceptor; import io.opensaber.registry.interceptor.RDFConversionInterceptor; import io.opensaber.registry.interceptor.RDFValidationInterceptor; import io.opensaber.registry.interceptor.RDFValidationMappingInterceptor; import io.opensaber.registry.middleware.impl.RDFConverter; import io.opensaber.registry.middleware.impl.RDFValidationMapper; import io.opensaber.registry.middleware.impl.RDFValidator; -import io.opensaber.registry.middleware.impl.RdfToJsonldConverter; +import io.opensaber.registry.middleware.impl.JSONLDConverter; import io.opensaber.registry.middleware.util.Constants; import io.opensaber.registry.schema.config.SchemaConfigurator; @@ -77,8 +78,8 @@ public Gson gson(){ } @Bean - public RdfToJsonldConverter rdfToJsonldConverter(){ - return new RdfToJsonldConverter(); + public JSONLDConverter jsonldConverter(){ + return new JSONLDConverter(); } @Bean @@ -147,13 +148,15 @@ public RDFValidationMapper rdfValidationMapper(){ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AuthorizationInterceptor(authorizationFilter(), gson())) - .addPathPatterns("/**").excludePathPatterns("/health","/error").order(1); + .addPathPatterns("/**").excludePathPatterns("/health","/error").order(1); registry.addInterceptor(new RDFConversionInterceptor(rdfConverter(), gson())) - .addPathPatterns("/create", "/update/{id}").order(2); + .addPathPatterns("/create", "/update/{id}").order(2); registry.addInterceptor(new RDFValidationMappingInterceptor(rdfValidationMapper(), gson())) - .addPathPatterns("/create", "/update/{id}").order(3); + .addPathPatterns("/create", "/update/{id}").order(3); registry.addInterceptor(new RDFValidationInterceptor(rdfValidator(), gson())) - .addPathPatterns("/create", "/update/{id}").order(4); + .addPathPatterns("/create", "/update/{id}").order(4); + /*registry.addInterceptor(new JSONLDConversionInterceptor(jsonldConverter())) + .addPathPatterns("/read/{id}").order(2);*/ } @Override diff --git a/java/registry/src/main/java/io/opensaber/registry/controller/BaseController.java b/java/registry/src/main/java/io/opensaber/registry/controller/BaseController.java index e6d023f63..50c37d35e 100644 --- a/java/registry/src/main/java/io/opensaber/registry/controller/BaseController.java +++ b/java/registry/src/main/java/io/opensaber/registry/controller/BaseController.java @@ -1,6 +1,7 @@ package io.opensaber.registry.controller; import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/java/registry/src/main/java/io/opensaber/registry/controller/RegistryController.java b/java/registry/src/main/java/io/opensaber/registry/controller/RegistryController.java index 23117e4b5..158b2173b 100644 --- a/java/registry/src/main/java/io/opensaber/registry/controller/RegistryController.java +++ b/java/registry/src/main/java/io/opensaber/registry/controller/RegistryController.java @@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; @@ -40,8 +41,6 @@ public class RegistryController { @Value("${registry.context.base}") private String registryContext; - - @ResponseBody @RequestMapping(value = "/create", method = RequestMethod.POST) public ResponseEntity addEntity(@RequestAttribute Request requestModel) { @@ -75,9 +74,11 @@ public ResponseEntity getEntity(@PathVariable("id") String id) { try { org.eclipse.rdf4j.model.Model entityModel = registryService.getEntityById(id); - logger.debug("FETCHED " + entityModel); + logger.debug("FETCHED: " + entityModel); String jenaJSON = registryService.frameEntity(entityModel); JSONObject jenaObj = new JSONObject(jenaJSON); + /*Map resultMap = new HashMap(); + resultMap.put(Constants.RESPONSE_ATTRIBUTE, entityModel);*/ response.setResult(jenaObj.toMap()); responseParams.setStatus(Response.Status.SUCCCESSFUL); } catch (RecordNotFoundException e) { @@ -119,7 +120,6 @@ public ResponseEntity updateEntity(@RequestAttribute Request requestMo return new ResponseEntity<>(response, HttpStatus.OK); } - @ResponseBody @RequestMapping(value = "/health", method = RequestMethod.GET) public ResponseEntity health() { diff --git a/java/utils/converters/jsonldToRDF/pom.xml b/java/utils/converters/jsonldToRDF/pom.xml deleted file mode 100644 index 8e0dedfa0..000000000 --- a/java/utils/converters/jsonldToRDF/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - 4.0.0 - io.opensaber - jsonldToRDF - 0.0.1-SNAPSHOT - jsonldToRDF - Utility to convert Jsonld to RDF format - - - com.github.jsonld-java - jsonld-java - 0.11.1 - - - \ No newline at end of file diff --git a/java/utils/converters/jsonldToRDF/src/main/java/io/opensaber/utils/converters/JsonLdToRdfConverter.java b/java/utils/converters/jsonldToRDF/src/main/java/io/opensaber/utils/converters/JsonLdToRdfConverter.java deleted file mode 100644 index b1295ef3c..000000000 --- a/java/utils/converters/jsonldToRDF/src/main/java/io/opensaber/utils/converters/JsonLdToRdfConverter.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.opensaber.utils.converters; - -import java.io.InputStream; -import java.io.Reader; - -import com.github.jsonldjava.core.JsonLdProcessor; -import com.github.jsonldjava.utils.JsonUtils; - - -public class JsonLdToRdfConverter { - - public static String jsonldToRDFConvertor(InputStream inputStream){ - String rdfStr = ""; - try{ - Object compact = JsonLdProcessor.toRDF(JsonUtils.fromInputStream(inputStream)); - rdfStr = JsonUtils.toPrettyString(compact); - } - catch(Exception e){ - e.printStackTrace(); - } - return rdfStr; - } - - public static String jsonldToRDFConvertor(Reader reader){ - String rdfStr = ""; - try{ - Object compact = JsonLdProcessor.toRDF(JsonUtils.fromReader(reader)); - rdfStr = JsonUtils.toPrettyString(compact); - } - catch(Exception e){ - e.printStackTrace(); - } - return rdfStr; - } - - public static String jsonldToRDFConvertor(String jsonString){ - String rdfStr = ""; - try{ - Object compact = JsonLdProcessor.toRDF(JsonUtils.fromString(jsonString)); - rdfStr = JsonUtils.toPrettyString(compact); - } - catch(Exception e){ - e.printStackTrace(); - } - return rdfStr; - } -}