Skip to content

Commit

Permalink
Merge pull request #414 from ScorpioBroker/replace-operation
Browse files Browse the repository at this point in the history
Replace operation
  • Loading branch information
ScorpioBroker committed Jul 26, 2023
2 parents 1eddf58 + bbd01dd commit b30f6ae
Show file tree
Hide file tree
Showing 12 changed files with 947 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public class AppConstants {
public static final String NGB_APPLICATION_JSON_PATCH = "application/merge-patch+json";
public static final int ENTITY_CREATE_PAYLOAD = 0;
public static final int MERGE_PATCH_PAYLOAD = 17;
public static final int REPLACE_ENTITY_PAYLOAD = 22;
public static final int ENTITY_UPDATE_PAYLOAD = 1;
public static final int ENTITY_RETRIEVED_PAYLOAD = 2;
public static final int SUBSCRIPTION_CREATE_PAYLOAD = 3;
Expand Down Expand Up @@ -97,6 +98,7 @@ public class AppConstants {
public static final int APPEND_REQUEST = 1;
public static final int UPDATE_REQUEST = 2;
public static final int MERGE_PATCH_REQUEST = 17;
public static final int REPLACE_ENTITY_REQUEST = 22;
public static final int PARTIAL_UPDATE_REQUEST = 21;
public static final int DELETE_REQUEST = 3;
public static final int DELETE_ATTRIBUTE_REQUEST = 4;
Expand All @@ -116,6 +118,8 @@ public class AppConstants {
public static final int UPDATE_SUBSCRIPTION_REQUEST = 15;
public static final int CREATE_SUBSCRIPTION_REQUEST = 16;

public static final int REPLACE_ATTRIBUTE_REQUEST = 23;

public static final String NGB_APPLICATION_GEO_JSON = "application/geo+json";
public static final String INTERNAL_TYPE_REGISTRATION_ID = "scorpio:hosted:types";
public static final String INTERNAL_ATTRS_REGISTRATION_ID = "scorpio:hosted:attrs";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ public interface NGSIConstants {
public static final String ENDPOINT_TEMPORAL_BATCH_DELETE = "/ngsi-ld/v1/temporal/entityOperations/delete";
public static final String ENDPOINT_TEMPORAL_CREATE_DELETE = "/ngsi-ld/v1/temporal/entityOperations/create";
public static final String ENDPOINT_TEMPROAL_BATCH_APPEND = "/ngsi-ld/v1/temporal/entityOperations/append";
public static final String AGGR_METH_TOTAL_COUNT = "totalCount";
public static final String AGGR_METH_TOTAL_COUNT = "totalCount";
public static final String AGGR_METH_DISTINCT_COUNT = "distinctCount";
public static final String AGGR_METH_SUM = "sum";
public static final String AGGR_METH_AVG = "avg";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package eu.neclab.ngsildbroker.commons.datatypes.requests;

import eu.neclab.ngsildbroker.commons.constants.AppConstants;


import java.util.Map;

public class ReplaceAttribRequest extends EntityRequest {

/**
* constructor for serialization
*/


public ReplaceAttribRequest() {

}

public ReplaceAttribRequest(String tenant, Map<String, Object> resolved ,String entityId,String attrId) {
super(tenant,entityId, resolved,
AppConstants.REPLACE_ATTRIBUTE_REQUEST);
this.attribName=attrId;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package eu.neclab.ngsildbroker.commons.datatypes.requests;

import eu.neclab.ngsildbroker.commons.constants.AppConstants;
import eu.neclab.ngsildbroker.commons.constants.NGSIConstants;


import java.util.Map;

public class ReplaceEntityRequest extends EntityRequest {

/**
* constructor for serialization
*/
public ReplaceEntityRequest() {

}

public ReplaceEntityRequest(String tenant, Map<String, Object> resolved ) {
super(tenant, (String) resolved.get(NGSIConstants.JSON_LD_ID), resolved,
AppConstants.REPLACE_ENTITY_REQUEST);

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ private String getOperationType() {
return "Delete Attribute";
case AppConstants.UPSERT_REQUEST:
return "Upsert";
case AppConstants.REPLACE_ENTITY_REQUEST:
return "Replace Entity";
default:
return "Unknown Operation";
}
Expand All @@ -109,6 +111,8 @@ private static int getOperationCode(String operationType) {
return AppConstants.DELETE_ATTRIBUTE_REQUEST;
case "Upsert":
return AppConstants.UPSERT_REQUEST;
case "Replace Entity":
return AppConstants.REPLACE_ENTITY_REQUEST;
default:
return -1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
Expand Down Expand Up @@ -50,7 +51,7 @@ public class EntityController {// implements EntityHandlerInterface {
/**
* Method(POST) for "/ngsi-ld/v1/entities/" rest endpoint.
*
* @param payload jsonld message
* @param body jsonld message
* @return ResponseEntity object
*/
@Path("/entities")
Expand All @@ -73,7 +74,7 @@ public Uni<RestResponse<Object>> createEntity(HttpServerRequest req, Map<String,
* Method(PATCH) for "/ngsi-ld/v1/entities/{entityId}/attrs" rest endpoint.
*
* @param entityId
* @param payload json ld message
* @param body json ld message
* @return ResponseEntity object
*/

Expand All @@ -100,7 +101,7 @@ public Uni<RestResponse<Object>> updateEntity(HttpServerRequest req, @PathParam(
* Method(POST) for "/ngsi-ld/v1/entities/{entityId}/attrs" rest endpoint.
*
* @param entityId
* @param payload jsonld message
* @param body jsonld message
* @return ResponseEntity object
*/

Expand Down Expand Up @@ -129,7 +130,7 @@ public Uni<RestResponse<Object>> appendEntity(HttpServerRequest req, @PathParam(
* endpoint.
*
* @param entityId
* @param payload
* @param body
* @return
*/
@PATCH
Expand Down Expand Up @@ -304,4 +305,52 @@ public Uni<RestResponse<Object>> mergePatch(HttpServerRequest request, @PathPara
}).onFailure().recoverWithItem(HttpUtils::handleControllerExceptions);

}
@Path("/entities/{entityId}")
@PUT
public Uni<RestResponse<Object>> replaceEntity(@PathParam("entityId") String entityId, HttpServerRequest request, Map<String, Object> body) {
logger.debug("replacing entity");
try {
HttpUtils.validateUri(entityId);
} catch (Exception e) {
return Uni.createFrom().item(HttpUtils.handleControllerExceptions(e));
}
noConcise(body);
body.put(NGSIConstants.ID,entityId);
if(!body.containsKey(NGSIConstants.TYPE)){
return Uni.createFrom().item(HttpUtils.handleControllerExceptions(
new ResponseException(ErrorType.BadRequestData, "Type can not be null")));
}
return HttpUtils.expandBody(request, body, AppConstants.REPLACE_ENTITY_PAYLOAD, ldService).onItem()
.transformToUni(tuple -> {

return entityService.replaceEntity(HttpUtils.getTenant(request), tuple.getItem2(), tuple.getItem1()).onItem()
.transform(opResult -> {

logger.debug("Done replacing entity");
return HttpUtils.generateUpdateResultResponse(opResult);
}).onFailure().recoverWithItem(HttpUtils::handleControllerExceptions);
});
}


@Path("/entities/{entityId}/attrs/{attrId}")
@PUT
public Uni<RestResponse<Object>> replaceAttribute(@PathParam("attrId") String attrId,@PathParam("entityId") String entityId, HttpServerRequest request, Map<String, Object> body) {
logger.debug("replacing Attrs");
try {
HttpUtils.validateUri(entityId);
} catch (Exception e) {
return Uni.createFrom().item(HttpUtils.handleControllerExceptions(e));
}
noConcise(body);
return HttpUtils.expandBody(request, body, AppConstants.PARTIAL_UPDATE_REQUEST, ldService).onItem()
.transformToUni(tuple -> {
String finalAttrId = tuple.getItem1().expandIri(attrId, false, true, null, null);
return entityService.replaceAttribute(HttpUtils.getTenant(request), tuple.getItem2(), tuple.getItem1(),entityId,finalAttrId).onItem()
.transform(opResult -> {
logger.debug("Done replacing attribute");
return HttpUtils.generateUpdateResultResponse(opResult);
}).onFailure().recoverWithItem(HttpUtils::handleControllerExceptions);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import eu.neclab.ngsildbroker.commons.datatypes.requests.DeleteAttributeRequest;
import eu.neclab.ngsildbroker.commons.datatypes.requests.DeleteEntityRequest;
import eu.neclab.ngsildbroker.commons.datatypes.requests.MergePatchRequest;
import eu.neclab.ngsildbroker.commons.datatypes.requests.ReplaceAttribRequest;
import eu.neclab.ngsildbroker.commons.datatypes.requests.ReplaceEntityRequest;
import eu.neclab.ngsildbroker.commons.datatypes.requests.UpdateEntityRequest;
import eu.neclab.ngsildbroker.commons.enums.ErrorType;
import eu.neclab.ngsildbroker.commons.exceptions.ResponseException;
Expand Down Expand Up @@ -397,4 +399,49 @@ public Uni<Map<String,Object>> mergePatch(MergePatchRequest request) {
});
});
}
public Uni<Map<String, Object>> replaceEntity(ReplaceEntityRequest request) {
String[] types = ((List<String>) request.getPayload().get(NGSIConstants.JSON_LD_TYPE)).toArray(new String[0]);
return clientManager.getClient(request.getTenant(), false).onItem().transformToUni(client -> {
return client.preparedQuery("""
WITH old_entity AS (
SELECT ENTITY
FROM ENTITY
WHERE id = $3)
update entity set entity = jsonb_build_object('https://uri.etsi.org/ngsi-ld/createdAt' , entity->'https://uri.etsi.org/ngsi-ld/createdAt') || $1::jsonb, e_types = $2 where id = $3
RETURNING (SELECT ENTITY FROM old_entity) AS old_entity""")
.execute(Tuple.of(new JsonObject(request.getPayload()),types,request.getId())).onItem().transformToUni(rows -> {
if (rows.rowCount() == 0) {
return Uni.createFrom().failure(new ResponseException(ErrorType.NotFound));
}
return Uni.createFrom().item(rows.iterator().next().getJsonObject(0).getMap());
});
});
}




public Uni<Map<String, Object>> replaceAttrib(ReplaceAttribRequest request) {
return clientManager.getClient(request.getTenant(), false).onItem().transformToUni(client -> {
return client.preparedQuery("""
WITH old_entity AS (
SELECT ENTITY
FROM ENTITY
WHERE id = $2
)
UPDATE entity
SET entity = entity::jsonb || $1
WHERE id = $2
AND ENTITY ? $3
AND (ENTITY-> $3 )::jsonb->$4 IS NULL
RETURNING (SELECT ENTITY FROM old_entity) AS old_entity;
""")
.execute(Tuple.of(new JsonObject(request.getPayload()),request.getId(),request.getAttribName(),request.getDatasetId())).onItem().transformToUni(rows -> {
if (rows.rowCount() == 0) {
return Uni.createFrom().failure(new ResponseException(ErrorType.NotFound));
}
return Uni.createFrom().item(rows.iterator().next().getJsonObject(0).getMap());
});
});
}
}

0 comments on commit b30f6ae

Please sign in to comment.