Skip to content

Commit

Permalink
Issue #139 API restructuring
Browse files Browse the repository at this point in the history
  • Loading branch information
jyotsnaraveendran committed Apr 26, 2018
1 parent 433b972 commit f435bb4
Show file tree
Hide file tree
Showing 21 changed files with 199 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class RegistryIntegrationSteps extends RegistryTestBase{
private static final String VALID_NEWJSONLD= "teacher.jsonld";
private static final String INVALID_LABEL_JSONLD = "invalid-label.jsonld";
private static final String INVALID_NEWJSONLD= "invalid-teacher.jsonld";
private static final String ADD_ENTITY = "create";
private static final String ADD_ENTITY = "add";
private static final String READ_ENTITY = "read";
private static final String AUTH_HEADER_NAME = "x-authenticated-user-token";

Expand Down Expand Up @@ -180,7 +180,6 @@ private void setInvalidAuthHeader(){
public void issueRecordInRegistry(String qualifier) throws JsonParseException, JsonMappingException, IOException{
jsonldData();
updateId = id;
System.out.println("Id getting inserted into db:"+id);
setValidAuthToken();
addEntity();
checkSuccessfulResponse();
Expand Down Expand Up @@ -213,7 +212,7 @@ public void retrieving_the_record_from_the_registry(){

private ResponseEntity<Response> callRegistryReadAPI() {
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Response> response = restTemplate.exchange(baseUrl+READ_ENTITY+"/"+id, HttpMethod.GET,entity,Response.class);
ResponseEntity<Response> response = restTemplate.exchange(baseUrl+"/"+id, HttpMethod.GET,entity,Response.class);
return response;

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public class RegistryTestBase {
private static final String REPLACING_SUBJECT_LABEL = "<@id>";
private static final String EMPTY_STRING = "";
private static final String CONTEXT_CONSTANT = "teacher:";
private static final String CONTEXT_URL = "http://example.com/voc/teacher/1.0.0/";
protected RestTemplate restTemplate;

public void setJsonld(String filename) {
Expand Down Expand Up @@ -85,7 +84,7 @@ public void setJsonldWithNewRootLabel(String id) {

public static String extractIdWithoutContext(String label) {
String extractedId = label;
Pattern pattern = Pattern.compile("^" + Pattern.quote(CONTEXT_URL) + "(.*?)$");
Pattern pattern = Pattern.compile("^" + Pattern.quote(Constants.INTEGRATION_TEST_BASE_URL) + "(.*?)$");
Matcher matcher = pattern.matcher(label);
if(matcher.find()) {
extractedId = matcher.group(1);
Expand Down Expand Up @@ -115,16 +114,16 @@ public ResponseEntity<Response> fetchEntity(String url, HttpHeaders headers) {
return response;
}

/*public ResponseEntity<Response> addEntity(String jsonldData, String url, HttpHeaders headers) {
public ResponseEntity<Response> addEntity(String jsonldData, String url, HttpHeaders headers) {
HttpEntity<String> entity = new HttpEntity<>(jsonldData, headers);
ResponseEntity<Response> response = restTemplate.postForEntity(url, entity, Response.class);
return response;
}

public ResponseEntity<Response> update(String jsonldData, String url, HttpHeaders headers) {
HttpEntity<String> entity = new HttpEntity<>(jsonldData, headers);
Response response = restTemplate.patchForObject(url, entity, Response.class);
return new ResponseEntity(response, HttpStatus.OK);
ResponseEntity<Response> response = restTemplate.postForEntity(url, entity, Response.class);
return response;
}

public ResponseEntity<Response> readEntity(String url, HttpHeaders headers, String id) {
Expand All @@ -133,6 +132,6 @@ public ResponseEntity<Response> readEntity(String url, HttpHeaders headers, Stri
queryParams.put("id", id);
ResponseEntity<Response> response = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class,queryParams);
return response;
}*/
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public class UpdateIntegrationTestSteps extends RegistryTestBase implements En {
private static final String VALID_UPDATE_JSONLD_FILE = "update_teacher.jsonld";
private static final String UPDATE_JSONLD__AUDIT_FILE = "update_teacher_audit.jsonld";
private static final String INVALID_UPDATE_JSONLD = "invalid-teacher.jsonld";
private static final String CREATE_REST_ENDPOINT = "create";
private static final String CREATE_REST_ENDPOINT = "add";
private static final String UPDATE_REST_ENDPOINT = "update";
private static final String READ_REST_ENDPOINT = "read";
private static final String CONTEXT_CONSTANT = "sample:";
Expand Down Expand Up @@ -87,8 +87,9 @@ private void initializeCommonSteps() {

When("^updating the record in the registry$", () -> {
StringBuilder url = new StringBuilder();
url.append(baseUrl).append(UPDATE_REST_ENDPOINT).append("/").append(extractIdWithoutContext(id));
response = updateEntity(jsonld, url.toString(), headers);
//url.append(baseUrl).append(UPDATE_REST_ENDPOINT).append("/").append(extractIdWithoutContext(id));
url.append(baseUrl).append(UPDATE_REST_ENDPOINT);
response = update(jsonld, url.toString(), headers);
});

Then("^updating the record should be unsuccessful$", () -> checkUnsuccessfulResponse());
Expand All @@ -99,14 +100,16 @@ private void initializeCommonSteps() {

Given("^valid data for updating a record$", () -> {
StringBuilder url = new StringBuilder();
url.append(baseUrl).append(READ_REST_ENDPOINT).append("/").append(extractIdWithoutContext(id));
//url.append(baseUrl).append(READ_REST_ENDPOINT).append("/").append(extractIdWithoutContext(id));
url.append(id);
response = fetchEntity(url.toString(), headers);
jsonld = updateInputJsonldRootNodeId(response, "update_teacher.jsonld");
});

Given("^input for updating single record$", () -> {
StringBuilder url = new StringBuilder();
url.append(baseUrl).append(READ_REST_ENDPOINT).append("/").append(extractIdWithoutContext(id));
//url.append(baseUrl).append(READ_REST_ENDPOINT).append("/").append(extractIdWithoutContext(id));
url.append(id);
response = fetchEntity(url.toString(), headers);
jsonld = updateInputJsonldRootNodeId(response, "update_teacher_audit.jsonld");
});
Expand Down Expand Up @@ -193,7 +196,7 @@ private void verifyUnsuccessfulMessage(String message) {
private void verifyValidationErrorMessage(String message) {
Map<String, Object> result = response.getBody().getResult();
Map<String, String> validationErrorData = (Map<String, String>) result.get("data");
String validationError = validationErrorData.get("http://example.com/voc/teacher/1.0.0/serialNum");
String validationError = validationErrorData.get(Constants.INTEGRATION_TEST_BASE_URL+"serialNum");
assertEquals(message, validationError);
}

Expand Down
4 changes: 2 additions & 2 deletions java/cukes/src/test/resources/create_teacher.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
"@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/",
"teacher":"http://localhost:8080/",
"xsd":"http://www.w3.org/2001/XMLSchema#",
"@vocab":"http://example.com/voc/teacher/1.0.0/"
"@vocab":"http://localhost:8080/"
},
"@type":"Teacher",
"serialNum":12,
Expand Down
4 changes: 2 additions & 2 deletions java/cukes/src/test/resources/invalid-teacher.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
"@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/",
"teacher":"http://localhost:8080/",
"xsd":"http://www.w3.org/2001/XMLSchema#",
"@vocab":"http://example.com/voc/teacher/1.0.0/"
"@vocab":"http://localhost:8080/"
},
"@id":"<@id>",
"@type":"Teacher",
Expand Down
2 changes: 1 addition & 1 deletion java/cukes/src/test/resources/school.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"sample": "http://example.com/voc/teacher/1.0.0/"
"sample": "http://localhost:8080/"
}
}
4 changes: 2 additions & 2 deletions java/cukes/src/test/resources/teacher.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
{
"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/",
"teacher": "http://localhost:8080/",
"xsd": "http://www.w3.org/2001/XMLSchema#",
"@vocab": "http://example.com/voc/teacher/1.0.0/"
"@vocab": "http://localhost:8080/"
},

"@id": "<@id>",
Expand Down
4 changes: 2 additions & 2 deletions java/cukes/src/test/resources/update_teacher.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
"@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/",
"teacher":"http://localhost:8080/",
"xsd":"http://www.w3.org/2001/XMLSchema#",
"@vocab":"http://example.com/voc/teacher/1.0.0/"
"@vocab":"http://localhost:8080/"
},
"@type":"Teacher",
"serialNum":12,
Expand Down
4 changes: 2 additions & 2 deletions java/cukes/src/test/resources/update_teacher_audit.jsonld
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
"@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/",
"teacher":"http://localhost:8080/",
"xsd":"http://www.w3.org/2001/XMLSchema#",
"@vocab":"http://example.com/voc/teacher/1.0.0/"
"@vocab":"http://localhost:8080/"
},
"@type":"Teacher",
"serialNum":14
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class Constants {
public static final String SHAPE_TYPE = "validations.entity.shape.type";
public static final String FEATURE_TOGGLING = "feature.toggling";
public static final String RDF_VALIDATION_MAPPER_OBJECT = "rdfValidationMapper";
public static final String REGISTRY_CONTEXT_BASE = "registry.context.base";
public static final String REGISTRY_CONTEXT_BASE = "registry.base";
public static final String PRIVACY_PROPERTY = "privateProperties";
public static final String OPENSABER_CONTEXT_BASE = "http://example.com/voc/opensaber/1.0.0/";

Expand All @@ -31,14 +31,14 @@ public class Constants {

public static final String DUPLICATE_RECORD_MESSAGE = "Cannot insert duplicate record";
public static final String FAILED_INSERTION_MESSAGE = "Failed to insert record";
public static final String NO_ENTITY_AVAILABLE_MESSAGE = "No entity to create or update";
public static final String NO_ENTITY_AVAILABLE_MESSAGE = "No entity available";
public static final String ENTITY_NOT_FOUND = "Entity does not exist";
public static final String TOKEN_EXTRACTION_ERROR = "Unable to extract auth token";
public static final String JSONLD_PARSE_ERROR = "Unable to parse JSON-LD";
public static final String RDF_VALIDATION_ERROR = "Unable to validate RDF";
public static final String RDF_VALIDATION_MAPPING_ERROR = "Unable to map validations";
public static final String CUSTOM_EXCEPTION_ERROR = "Something went wrong!! Please try again later";
public static final String ADD_UPDATE_MULTIPLE_ENTITIES_MESSAGE = "Cannot add/update more than one entity";
public static final String ADD_UPDATE_MULTIPLE_ENTITIES_MESSAGE = "Cannot add/update/view more than one entity";

public static final String OPENSABER_REGISTRY_API_NAME = "opensaber-registry-api";
public static final String SUNBIRD_ENCRYPTION_SERVICE_NAME = "sunbird.encryption.service";
Expand Down
5 changes: 5 additions & 0 deletions java/registry/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,11 @@
<artifactId>schema-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>

<!-- Test Dependencies -->

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,22 +154,12 @@ public RDFValidationMapper rdfValidationMapper(){
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthorizationInterceptor(authorizationFilter(), gson()))
.addPathPatterns("/**").excludePathPatterns("/health", "/error").order(1);
boolean featureToggling = Boolean.parseBoolean(environment.getProperty(Constants.FEATURE_TOGGLING));
if(featureToggling){
registry.addInterceptor(new RDFConversionInterceptor(rdfConverter(), gson()))
.addPathPatterns("/add", "/update").order(2);
registry.addInterceptor(new RDFValidationMappingInterceptor(rdfValidationMapper(), gson()))
.addPathPatterns("/add", "/update").order(3);
registry.addInterceptor(new RDFValidationInterceptor(rdfValidator(), gson()))
.addPathPatterns("/add", "/update").order(4);
} else {
registry.addInterceptor(new RDFConversionInterceptor(rdfConverter(), gson()))
.addPathPatterns("/create", "/update/{id}").order(2);
registry.addInterceptor(new RDFValidationMappingInterceptor(rdfValidationMapper(), gson()))
.addPathPatterns("/create", "/update/{id}").order(3);
registry.addInterceptor(new RDFValidationInterceptor(rdfValidator(), gson()))
.addPathPatterns("/create", "/update/{id}").order(4);
}
registry.addInterceptor(new RDFConversionInterceptor(rdfConverter(), gson()))
.addPathPatterns("/create", "/update/{id}","/add", "/update").order(2);
registry.addInterceptor(new RDFValidationMappingInterceptor(rdfValidationMapper(), gson()))
.addPathPatterns("/create", "/update/{id}","/add", "/update").order(3);
registry.addInterceptor(new RDFValidationInterceptor(rdfValidator(), gson()))
.addPathPatterns("/create", "/update/{id}", "/add", "/update").order(4);
/*registry.addInterceptor(new JSONLDConversionInterceptor(jsonldConverter()))
.addPathPatterns("/read/{id}").order(2);*/
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
package io.opensaber.registry.controller;

import java.lang.reflect.Type;
import java.sql.Blob;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import io.opensaber.pojos.HealthCheckResponse;
import io.opensaber.registry.middleware.util.Constants;
import io.opensaber.registry.util.JSONUtil;

import org.apache.jena.atlas.json.JSON;
import org.apache.jena.rdf.model.Model;
import org.json.JSONObject;
import org.slf4j.Logger;
Expand All @@ -21,7 +18,6 @@
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;
Expand All @@ -30,18 +26,12 @@
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import io.opensaber.pojos.Request;
import io.opensaber.pojos.Response;
import io.opensaber.pojos.ResponseParams;
import io.opensaber.pojos.ValidationResponse;
import io.opensaber.pojos.ValidationResponseSerializer;
import io.opensaber.registry.exception.DuplicateRecordException;
import io.opensaber.registry.exception.EntityCreationException;
import io.opensaber.registry.exception.RecordNotFoundException;
Expand All @@ -58,9 +48,6 @@ public class RegistryController {
@Value("${registry.context.base}")
private String registryContext;

@Value("${registry.system.base}")
private String registrySystemContext;

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity<Response> addEntity(@RequestAttribute Request requestModel) {
Model rdf = (Model) requestModel.getRequestMap().get("rdf");
Expand Down Expand Up @@ -88,15 +75,15 @@ public ResponseEntity<Response> addEntity(@RequestAttribute Request requestModel

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<Response> addToExistingEntity(@RequestAttribute Request requestModel,
@RequestParam("id") String id, @RequestParam("prop") String property) {

@RequestParam(value="id", required = false) String id, @RequestParam(value="prop", required = false) String property) {
Model rdf = (Model) requestModel.getRequestMap().get("rdf");
ResponseParams responseParams = new ResponseParams();
Response response = new Response(Response.API_ID.CREATE, "OK", responseParams);
Map<String, Object> result = new HashMap<>();

try {
String label = registryService.addToExistingEntity(rdf, id, property);
String label = registryService.addEntity(rdf, id, property);
result.put("entity", label);
response.setResult(result);
responseParams.setStatus(Response.Status.SUCCCESSFUL);
Expand Down Expand Up @@ -140,6 +127,34 @@ public ResponseEntity<Response> getEntity(@PathVariable("id") String id) {
return new ResponseEntity<>(response, HttpStatus.OK);
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Response> readEntity(@PathVariable("id") String id) {
id = registryContext + id;
ResponseParams responseParams = new ResponseParams();
Response response = new Response(Response.API_ID.READ, "OK", responseParams);

try {
org.eclipse.rdf4j.model.Model entityModel = registryService.getEntityById(id);
logger.debug("FETCHED: " + entityModel);
String jenaJSON = registryService.frameEntity(entityModel);
JSONObject jenaObj = new JSONObject(jenaJSON);
/*Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put(Constants.RESPONSE_ATTRIBUTE, entityModel);*/
response.setResult(jenaObj.toMap());
responseParams.setStatus(Response.Status.SUCCCESSFUL);
} catch (RecordNotFoundException e) {
response.setResult(null);
responseParams.setStatus(Response.Status.UNSUCCESSFUL);
responseParams.setErrmsg(e.getMessage());
} catch (Exception e) {
response.setResult(null);
responseParams.setStatus(Response.Status.UNSUCCESSFUL);
responseParams.setErrmsg("Ding! You encountered an error!");
logger.error("ERROR!", e);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}

@ResponseBody
@RequestMapping(value = "/update/{id}", method = RequestMethod.PATCH)
public ResponseEntity<Response> updateEntity(@RequestAttribute Request requestModel,
Expand Down Expand Up @@ -168,16 +183,14 @@ public ResponseEntity<Response> updateEntity(@RequestAttribute Request requestMo

@ResponseBody
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ResponseEntity<Response> update(@RequestAttribute Request requestModel,
@PathVariable("id") String id) {
public ResponseEntity<Response> update(@RequestAttribute Request requestModel) {

Model rdf = (Model) requestModel.getRequestMap().get("rdf");
id = registryContext + id;
ResponseParams responseParams = new ResponseParams();
Response response = new Response(Response.API_ID.UPDATE, "OK", responseParams);

try {
registryService.updateEntity(rdf, id);
registryService.updateEntity(rdf, null);
responseParams.setErrmsg("");
responseParams.setStatus(Response.Status.SUCCCESSFUL);
} catch (RecordNotFoundException | EntityCreationException e) {
Expand All @@ -186,7 +199,7 @@ public ResponseEntity<Response> update(@RequestAttribute Request requestModel,

} catch (Exception e) {
responseParams.setStatus(Response.Status.UNSUCCESSFUL);
responseParams.setErrmsg(String.format("Error occurred when updating Entity ID %s", id));
responseParams.setErrmsg("Error occurred when updating Entity");
logger.error("ERROR!", e);
}
return new ResponseEntity<>(response, HttpStatus.OK);
Expand Down
Loading

0 comments on commit f435bb4

Please sign in to comment.