Search in sources :

Example 1 with BulkOperation

use of io.jans.scim.model.scim2.bulk.BulkOperation in project oxTrust by GluuFederation.

the class BulkWebService method processBulkOperations.

@javax.ws.rs.POST
@Consumes({ MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON })
@Produces({ MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT })
@HeaderParam("Accept")
@DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi
@ApiOperation(value = "Bulk Operations", notes = "Bulk Operations (https://tools.ietf.org/html/rfc7644#section-3.7)", response = BulkResponse.class)
public Response processBulkOperations(@ApiParam(value = "BulkRequest", required = true) BulkRequest request) {
    Response response = prepareRequest(request, getValueFromHeaders(httpHeaders, "Content-Length"));
    if (response == null) {
        log.debug("Executing web service method. processBulkOperations");
        int i, errors = 0;
        List<BulkOperation> operations = request.getOperations();
        List<BulkOperation> responseOperations = new ArrayList<BulkOperation>();
        Map<String, String> processedBulkIds = new HashMap<String, String>();
        for (i = 0; i < operations.size() && errors < request.getFailOnErrors(); i++) {
            BulkOperation operation = operations.get(i);
            BulkOperation operationResponse = new BulkOperation();
            Response subResponse;
            String method = operation.getMethod();
            String bulkId = operation.getBulkId();
            try {
                String path = operation.getPath();
                BaseScimWebService service = getWSForPath(path);
                String fragment = getFragment(path, service, processedBulkIds);
                Verb verb = Verb.valueOf(method);
                String data = operation.getDataStr();
                if (!verb.equals(DELETE))
                    data = replaceBulkIds(data, processedBulkIds);
                Pair<Response, String> pair = execute(verb, service, data, fragment);
                String idCreated = pair.getSecond();
                subResponse = pair.getFirst();
                int status = subResponse.getStatus();
                if (familyOf(status).equals(SUCCESSFUL)) {
                    if (!verb.equals(DELETE)) {
                        if (verb.equals(POST)) {
                            // Update bulkIds
                            processedBulkIds.put(bulkId, idCreated);
                            fragment = idCreated;
                        }
                        String loc = service.getEndpointUrl() + "/" + fragment;
                        operationResponse.setLocation(loc);
                    }
                } else {
                    operationResponse.setResponse(subResponse.getEntity());
                    errors += familyOf(status).equals(CLIENT_ERROR) || familyOf(status).equals(SERVER_ERROR) ? 1 : 0;
                }
                subResponse.close();
                operationResponse.setStatus(Integer.toString(status));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                subResponse = getErrorResponse(BAD_REQUEST, ErrorScimType.INVALID_SYNTAX, e.getMessage());
                operationResponse.setStatus(Integer.toString(BAD_REQUEST.getStatusCode()));
                operationResponse.setResponse(subResponse.getEntity());
                errors++;
            }
            operationResponse.setBulkId(bulkId);
            operationResponse.setMethod(method);
            responseOperations.add(operationResponse);
            log.debug("Operation {} processed with status {}. Method {}, Accumulated errors {}", i + 1, operationResponse.getStatus(), method, errors);
        }
        try {
            BulkResponse bulkResponse = new BulkResponse();
            bulkResponse.setOperations(responseOperations);
            String json = mapper.writeValueAsString(bulkResponse);
            response = Response.ok(json).build();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response = getErrorResponse(INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    return response;
}
Also used : HashMap(java.util.HashMap) BulkOperation(org.gluu.oxtrust.model.scim2.bulk.BulkOperation) ArrayList(java.util.ArrayList) BulkResponse(org.gluu.oxtrust.model.scim2.bulk.BulkResponse) Response(javax.ws.rs.core.Response) BulkResponse(org.gluu.oxtrust.model.scim2.bulk.BulkResponse) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ProtectedApi(org.gluu.oxtrust.service.filter.ProtectedApi)

Example 2 with BulkOperation

use of io.jans.scim.model.scim2.bulk.BulkOperation in project oxTrust by GluuFederation.

the class BulkWebService method prepareRequest.

private Response prepareRequest(BulkRequest request, String contentLength) {
    Response response = null;
    if (request.getFailOnErrors() == null)
        request.setFailOnErrors(MAX_BULK_OPERATIONS);
    List<BulkOperation> operations = request.getOperations();
    if (operations == null || operations.size() == 0)
        response = getErrorResponse(BAD_REQUEST, ErrorScimType.INVALID_VALUE, "No operations supplied");
    else {
        int contentLen;
        try {
            // log.debug("CONT LEN {}", contentLength);
            contentLen = Integer.valueOf(contentLength);
        } catch (Exception e) {
            contentLen = MAX_BULK_PAYLOAD_SIZE;
        }
        boolean payloadExceeded = contentLen > MAX_BULK_PAYLOAD_SIZE;
        boolean operationsExceeded = operations.size() > MAX_BULK_OPERATIONS;
        StringBuilder sb = new StringBuilder();
        if (payloadExceeded)
            sb.append("The size of the bulk operation exceeds the maxPayloadSize (").append(MAX_BULK_PAYLOAD_SIZE).append(" bytes). ");
        if (operationsExceeded)
            sb.append("The number of operations exceed the maxOperations value (").append(MAX_BULK_OPERATIONS).append("). ");
        if (sb.length() > 0)
            response = getErrorResponse(REQUEST_ENTITY_TOO_LARGE, sb.toString());
    }
    if (response == null) {
        try {
            for (BulkOperation operation : operations) {
                if (operation == null)
                    throw new Exception("An operation passed was found to be null");
                String path = operation.getPath();
                if (StringUtils.isEmpty(path))
                    throw new Exception("path parameter is required");
                path = adjustPath(path);
                operation.setPath(path);
                String method = operation.getMethod();
                if (StringUtils.isNotEmpty(method)) {
                    method = method.toUpperCase();
                    operation.setMethod(method);
                }
                Verb verb = Verb.valueOf(method);
                if (!availableMethods.contains(verb))
                    throw new Exception("method not recognized: " + method);
                // Check if path passed is consistent with respect to method:
                List<String> availableEndpoints = Arrays.asList(usersEndpoint, groupsEndpoint, fidodevicesEndpoint);
                boolean consistent = false;
                for (String endpoint : availableEndpoints) {
                    if (verb.equals(POST))
                        consistent = path.equals(endpoint);
                    else
                        // Checks if there is something after the additional slash
                        consistent = path.startsWith(endpoint + "/") && (path.length() > endpoint.length() + 1);
                    if (consistent)
                        break;
                }
                if (!consistent)
                    throw new Exception("path parameter is not consistent with method " + method);
                // Check if bulkId must be present
                String bulkId = operation.getBulkId();
                if (StringUtils.isEmpty(bulkId) && verb.equals(POST))
                    throw new Exception("bulkId parameter is required for method " + method);
                // Check if data must be present
                String data = operation.getDataStr();
                List<Verb> dataMethods = Arrays.asList(POST, PUT, PATCH);
                if (dataMethods.contains(verb) && StringUtils.isEmpty(data))
                    throw new Exception("data parameter is required for method " + method);
            }
        } catch (Exception e) {
            response = getErrorResponse(BAD_REQUEST, ErrorScimType.INVALID_SYNTAX, e.getMessage());
        }
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) BulkResponse(org.gluu.oxtrust.model.scim2.bulk.BulkResponse) BulkOperation(org.gluu.oxtrust.model.scim2.bulk.BulkOperation)

Example 3 with BulkOperation

use of io.jans.scim.model.scim2.bulk.BulkOperation in project jans by JanssenProject.

the class BulkWebService method prepareRequest.

private Response prepareRequest(BulkRequest request, String contentLength) {
    Response response = null;
    if (request.getFailOnErrors() == null)
        request.setFailOnErrors(MAX_BULK_OPERATIONS);
    List<BulkOperation> operations = request.getOperations();
    if (operations == null || operations.isEmpty())
        response = getErrorResponse(BAD_REQUEST, ErrorScimType.INVALID_VALUE, "No operations supplied");
    else {
        int contentLen;
        try {
            // log.debug("CONT LEN {}", contentLength);
            contentLen = Integer.valueOf(contentLength);
        } catch (Exception e) {
            contentLen = MAX_BULK_PAYLOAD_SIZE;
        }
        boolean payloadExceeded = contentLen > MAX_BULK_PAYLOAD_SIZE;
        boolean operationsExceeded = operations.size() > MAX_BULK_OPERATIONS;
        StringBuilder sb = new StringBuilder();
        if (payloadExceeded)
            sb.append("The size of the bulk operation exceeds the maxPayloadSize (").append(MAX_BULK_PAYLOAD_SIZE).append(" bytes). ");
        if (operationsExceeded)
            sb.append("The number of operations exceed the maxOperations value (").append(MAX_BULK_OPERATIONS).append("). ");
        if (sb.length() > 0)
            response = getErrorResponse(REQUEST_ENTITY_TOO_LARGE, sb.toString());
    }
    if (response == null) {
        try {
            for (BulkOperation operation : operations) {
                if (operation == null)
                    throw new Exception("An operation passed was found to be null");
                String path = operation.getPath();
                if (StringUtils.isEmpty(path))
                    throw new Exception("path parameter is required");
                path = adjustPath(path);
                operation.setPath(path);
                String method = operation.getMethod();
                if (StringUtils.isNotEmpty(method)) {
                    method = method.toUpperCase();
                    operation.setMethod(method);
                }
                Verb verb = Verb.valueOf(method);
                if (!availableMethods.contains(verb))
                    throw new Exception("method not recognized: " + method);
                // Check if path passed is consistent with respect to method:
                List<String> availableEndpoints = Arrays.asList(usersEndpoint, groupsEndpoint, fidodevicesEndpoint, fido2devicesEndpoint);
                boolean consistent = false;
                for (String endpoint : availableEndpoints) {
                    if (verb.equals(POST))
                        consistent = path.equals(endpoint);
                    else
                        // Checks if there is something after the additional slash
                        consistent = path.startsWith(endpoint + "/") && (path.length() > endpoint.length() + 1);
                    if (consistent)
                        break;
                }
                if (!consistent)
                    throw new Exception("path parameter is not consistent with method " + method);
                // Check if bulkId must be present
                String bulkId = operation.getBulkId();
                if (StringUtils.isEmpty(bulkId) && verb.equals(POST))
                    throw new Exception("bulkId parameter is required for method " + method);
                // Check if data must be present
                String data = operation.getDataStr();
                List<Verb> dataMethods = Arrays.asList(POST, PUT, PATCH);
                if (dataMethods.contains(verb) && StringUtils.isEmpty(data))
                    throw new Exception("data parameter is required for method " + method);
            }
        } catch (Exception e) {
            response = getErrorResponse(BAD_REQUEST, ErrorScimType.INVALID_SYNTAX, e.getMessage());
        }
    }
    return response;
}
Also used : BulkResponse(io.jans.scim.model.scim2.bulk.BulkResponse) Response(javax.ws.rs.core.Response) BulkOperation(io.jans.scim.model.scim2.bulk.BulkOperation)

Example 4 with BulkOperation

use of io.jans.scim.model.scim2.bulk.BulkOperation in project jans by JanssenProject.

the class GroupsBulkTest method delete.

@Test(dependsOnMethods = "bulkObject", alwaysRun = true)
public void delete() {
    logger.info("Cleaning...");
    // Prepare a bulk with 2 deletes
    List<BulkOperation> ops = new ArrayList<>();
    BulkOperation op = new BulkOperation();
    op.setMethod("DELETE");
    op.setPath("/Groups/" + groupId);
    ops.add(op);
    op = new BulkOperation();
    op.setMethod("DELETE");
    op.setPath("/Users/" + userId);
    ops.add(op);
    BulkRequest breq = new BulkRequest();
    breq.setOperations(ops);
    // Execute and check success
    Response response = client.processBulkOperations(breq);
    assertEquals(response.getStatus(), Status.OK.getStatusCode());
    BulkResponse bres = response.readEntity(BulkResponse.class);
    ops = bres.getOperations();
    assertTrue(ops.stream().allMatch(oper -> Integer.parseInt(oper.getStatus()) == Status.NO_CONTENT.getStatusCode()));
}
Also used : Response(javax.ws.rs.core.Response) ListResponse(io.jans.scim.model.scim2.ListResponse) BulkResponse(io.jans.scim.model.scim2.bulk.BulkResponse) java.util(java.util) PatchRequest(io.jans.scim.model.scim2.patch.PatchRequest) BulkRequest(io.jans.scim.model.scim2.bulk.BulkRequest) Test(org.testng.annotations.Test) BaseTest(io.jans.scim2.client.BaseTest) Family(javax.ws.rs.core.Response.Status.Family) SearchRequest(io.jans.scim.model.scim2.SearchRequest) Response(javax.ws.rs.core.Response) Assert(org.testng.Assert) ListResponse(io.jans.scim.model.scim2.ListResponse) BulkOperation(io.jans.scim.model.scim2.bulk.BulkOperation) Parameters(org.testng.annotations.Parameters) PatchOperation(io.jans.scim.model.scim2.patch.PatchOperation) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Status(javax.ws.rs.core.Response.Status) BulkResponse(io.jans.scim.model.scim2.bulk.BulkResponse) BulkOperation(io.jans.scim.model.scim2.bulk.BulkOperation) BulkRequest(io.jans.scim.model.scim2.bulk.BulkRequest) BulkResponse(io.jans.scim.model.scim2.bulk.BulkResponse) Test(org.testng.annotations.Test) BaseTest(io.jans.scim2.client.BaseTest)

Example 5 with BulkOperation

use of io.jans.scim.model.scim2.bulk.BulkOperation in project jans by JanssenProject.

the class UsersBulkTest method bulkJson1.

@Parameters("users_bulk1")
@Test
public void bulkJson1(String json) {
    logger.info("Sending a bulk with POST, PUT, and PATCH operations...");
    Response response = client.processBulkOperations(json);
    assertEquals(response.getStatus(), Status.OK.getStatusCode());
    BulkResponse br = response.readEntity(BulkResponse.class);
    List<BulkOperation> ops = br.getOperations();
    assertTrue(ops.size() > 2);
    assertSuccessfulOps(ops);
    String location = ops.get(0).getLocation();
    assertNotNull(location);
    id = location.substring(location.lastIndexOf("/") + 1);
    logger.info("User id is {}", id);
}
Also used : Response(javax.ws.rs.core.Response) BulkResponse(io.jans.scim.model.scim2.bulk.BulkResponse) BulkOperation(io.jans.scim.model.scim2.bulk.BulkOperation) BulkResponse(io.jans.scim.model.scim2.bulk.BulkResponse) Parameters(org.testng.annotations.Parameters) UserBaseTest(io.jans.scim2.client.UserBaseTest) Test(org.testng.annotations.Test)

Aggregations

BulkOperation (io.jans.scim.model.scim2.bulk.BulkOperation)10 Response (javax.ws.rs.core.Response)10 BulkResponse (io.jans.scim.model.scim2.bulk.BulkResponse)8 Test (org.testng.annotations.Test)6 Parameters (org.testng.annotations.Parameters)4 ListResponse (io.jans.scim.model.scim2.ListResponse)3 BulkRequest (io.jans.scim.model.scim2.bulk.BulkRequest)3 BaseTest (io.jans.scim2.client.BaseTest)3 UserBaseTest (io.jans.scim2.client.UserBaseTest)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 PatchOperation (io.jans.scim.model.scim2.patch.PatchOperation)2 PatchRequest (io.jans.scim.model.scim2.patch.PatchRequest)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Consumes (javax.ws.rs.Consumes)2 DefaultValue (javax.ws.rs.DefaultValue)2 HeaderParam (javax.ws.rs.HeaderParam)2 Produces (javax.ws.rs.Produces)2 BulkOperation (org.gluu.oxtrust.model.scim2.bulk.BulkOperation)2 BulkResponse (org.gluu.oxtrust.model.scim2.bulk.BulkResponse)2