Example usage for org.springframework.http HttpStatus FORBIDDEN

List of usage examples for org.springframework.http HttpStatus FORBIDDEN

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FORBIDDEN.

Prototype

HttpStatus FORBIDDEN

To view the source code for org.springframework.http HttpStatus FORBIDDEN.

Click Source Link

Document

403 Forbidden .

Usage

From source file:it.smartcommunitylab.carpooling.managers.CarPoolingManager.java

/**
 * Update Booking of Recurrent Travel + Instances.
 * //from w ww.  j ava  2s .c  o m
 * @param recurrentTravel
 * @param reqBooking
 * @param userId
 * @return
 * @throws CarPoolingCustomException
 */
private RecurrentTravel updateRecurrentTravelBooking(RecurrentTravel recurrentTravel,
        RecurrentBooking reqBooking, String userId) throws CarPoolingCustomException {

    List<Travel> tranistInstances = travelRepository.findFutureInstanceOfRecurrTravel(recurrentTravel.getId());

    if (tranistInstances != null && !tranistInstances.isEmpty()) {

        // booking instance to replicate.
        Booking instanceBooking = new Booking();
        instanceBooking.setAccepted(0);
        instanceBooking.setTraveller(reqBooking.getTraveller());
        instanceBooking.setRecurrent(true);
        instanceBooking.setDate(new java.util.Date(System.currentTimeMillis()));

        for (Travel instance : tranistInstances) {

            List<Booking> transitStateBooking = instance.getBookings();

            int availability = instance.getPlaces();

            if (transitStateBooking.isEmpty()) {
                // add new booking to instance.
                transitStateBooking.add(instanceBooking);

            } else {

                List<Booking> temp = new ArrayList<Booking>();
                temp.addAll(transitStateBooking);

                boolean updatedNewBooking = false;
                for (Booking uBooking : temp) {

                    if (uBooking.getTraveller().getUserId().equalsIgnoreCase(userId)) {
                        // 1. check if user is present with recurrent
                        // booking -> throw exception [USER ALREADY
                        // BOOKED].
                        if (uBooking.isRecurrent()) {
                            throw new CarPoolingCustomException(HttpStatus.FORBIDDEN.value(),
                                    "user has already booked.");
                        }
                        // 2. if user is present with non recurrent booking
                        // -> override it.
                        if (!uBooking.isRecurrent()) {
                            transitStateBooking.remove(uBooking);
                            uBooking.setRecurrent(true);
                            uBooking.setAccepted(0);
                            transitStateBooking.add(uBooking);
                            updatedNewBooking = true;
                            break;
                        }
                    } else if (uBooking.getAccepted() != -1) {
                        availability--; // 3. if not present check for
                        // availability
                    }
                }
                if (availability < 1) {
                    throw new CarPoolingCustomException(HttpStatus.PRECONDITION_FAILED.value(),
                            "travel not bookable.");
                }
                if (!updatedNewBooking) {
                    // add new booking to instance.
                    transitStateBooking.add(instanceBooking);
                }
            }
        }

        // update recurrent travel.
        reqBooking.getTraveller().setUserId(userId);
        reqBooking.setAccepted(0);

        boolean alreadyBooked = false;
        List<RecurrentBooking> tmpList = new ArrayList<RecurrentBooking>();
        if (recurrentTravel.getBookings() != null)
            tmpList.addAll(recurrentTravel.getBookings());
        for (RecurrentBooking uBooking : tmpList) {
            if (userId.equals(uBooking.getTraveller().getUserId())) {
                alreadyBooked = true;
                // if in the past was rejected, allow for being re-booked
                // again? consider rejecting
                if (uBooking.getAccepted() == -1) {
                    uBooking.setAccepted(0);
                    reccurrentTravelRepository.save(recurrentTravel);
                }
                break;
            }
        }
        if (!alreadyBooked) {
            recurrentTravel.getBookings().add(reqBooking);
            reccurrentTravelRepository.save(recurrentTravel);
        }

        // update travel instances of recurrent travel.
        travelRepository.save(tranistInstances);

        // create notification.
        String targetUserId = recurrentTravel.getUserId();
        Map<String, String> data = new HashMap<String, String>();
        data.put("senderId", userId);
        User user = userRepository.findOne(userId);
        data.put("senderFullName", user.fullName());
        // always notify with instance of recurrent travel.
        Notification bookingNotification = new Notification(targetUserId, CarPoolingUtils.NOTIFICATION_BOOKING,
                data, false, tranistInstances.get(0).getId(), System.currentTimeMillis());
        notificationRepository.save(bookingNotification);
        // notify via parse.
        try {
            sendPushNotification.sendNotification(targetUserId, bookingNotification);
        } catch (JSONException e) {
            throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }

    } else {
        throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "no instance found for reccurrent travel.");
    }

    return recurrentTravel;

}

From source file:it.smartcommunitylab.carpooling.managers.CarPoolingManager.java

public Travel bookNonRecurrent(String travelId, Booking reqBooking, String userId)
        throws CarPoolingCustomException {

    Travel travel = travelRepository.findOne(travelId);

    if (travel != null) {

        if (CarPoolingUtils.isValidUser(travel, userId, reqBooking)) {

            if (CarPoolingUtils.havePlaces(travel, reqBooking, userId)) {
                reqBooking.setRecurrent(false);
                reqBooking.getTraveller().setUserId(userId);
                reqBooking.setAccepted(0);
                reqBooking.setDate(new java.util.Date(System.currentTimeMillis()));
                travel.getBookings().add(reqBooking);
                // save travel.
                travelRepository.save(travel);

            } else {
                throw new CarPoolingCustomException(HttpStatus.PRECONDITION_FAILED.value(),
                        "travel not bookable.");
            }// w w w. j ava2  s . c o m
            // create notification.
            String targetUserId = travel.getUserId();
            Map<String, String> data = new HashMap<String, String>();
            data.put("senderId", userId);
            User user = userRepository.findOne(userId);
            data.put("senderFullName", user.fullName());
            Notification bookingNotification = new Notification(targetUserId,
                    CarPoolingUtils.NOTIFICATION_BOOKING, data, false, travel.getId(),
                    System.currentTimeMillis());
            notificationRepository.save(bookingNotification);
            // notify via parse.
            try {
                sendPushNotification.sendNotification(targetUserId, bookingNotification);
            } catch (JSONException e) {
                throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }

        } else {
            throw new CarPoolingCustomException(HttpStatus.FORBIDDEN.value(), "user has already booked.");
        }
    } else {
        throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "travel not found.");
    }

    return travel;
}

From source file:it.smartcommunitylab.carpooling.managers.CarPoolingManager.java

public Map<String, String> ratePassenger(String userId, String passengerId, int rating) {

    Map<String, String> errorMap = new HashMap<String, String>();

    if (userId.equalsIgnoreCase(passengerId)) {

        errorMap.put(CarPoolingUtils.ERROR_CODE, String.valueOf(HttpStatus.FORBIDDEN.value()));
        errorMap.put(CarPoolingUtils.ERROR_MSG, "passenger cannot self rate.");

        return errorMap;

    }//from   w  w  w .j av  a2 s.  c  o  m

    User passenger = userRepository.findOne(passengerId);

    if (passenger != null) {

        GameProfile gameProfile = passenger.getGameProfile();

        if (gameProfile != null) {
            gameProfile.getPassengerRatings().put(userId, rating);
            recalculateRatings(passenger);
        } else {
            errorMap.put(CarPoolingUtils.ERROR_CODE, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
            errorMap.put(CarPoolingUtils.ERROR_MSG, "passenger has null game profile.");
        }
    } else {

        errorMap.put(CarPoolingUtils.ERROR_CODE, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
        errorMap.put(CarPoolingUtils.ERROR_MSG, "passenger does not exist.");

    }

    return errorMap;

}

From source file:it.smartcommunitylab.carpooling.managers.CarPoolingManager.java

public Map<String, String> rateDriver(String userId, String driverId, int rating) {

    Map<String, String> errorMap = new HashMap<String, String>();

    if (userId.equalsIgnoreCase(driverId)) {

        errorMap.put(CarPoolingUtils.ERROR_CODE, String.valueOf(HttpStatus.FORBIDDEN.value()));
        errorMap.put(CarPoolingUtils.ERROR_MSG, "driver cannot self rate.");

        return errorMap;
    }/* w  w w. ja v  a  2  s . c o  m*/

    User driver = userRepository.findOne(driverId);

    if (driver != null) {
        GameProfile gameProfile = driver.getGameProfile();

        if (gameProfile != null) {

            gameProfile.getDriverRatings().put(userId, rating);
            recalculateRatings(driver);

        } else {

            errorMap.put(CarPoolingUtils.ERROR_CODE, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
            errorMap.put(CarPoolingUtils.ERROR_MSG, "driver has null game profile.");

        }

    } else {

        errorMap.put(CarPoolingUtils.ERROR_CODE, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
        errorMap.put(CarPoolingUtils.ERROR_MSG, "driver does not exist.");

    }

    return errorMap;
}

From source file:it.smartcommunitylab.weliveplayer.managers.WeLivePlayerManager.java

public Map<String, String> updateUserProfile(String userId, Profile profile) {

    Map<String, String> status = new HashMap<String, String>();

    String url = env.getProperty("welive.cdv.updateUserprofile.uri");

    try {//  w  w w.j  a v a 2  s . c o  m

        if (profile != null) {

            // check if passed in token user has same id as the one in
            // profile body.
            if (profile.getCcUserID().equalsIgnoreCase(userId)) {

                String response = weLivePlayerUtils.sendPOST(url, null, "application/json", authHeader,
                        profile.updateProfileBody(), true);

                if (response != null && !response.isEmpty()) {

                    JSONObject root = new JSONObject(response.toString());

                    if (root.has("text")) {
                        if (!root.getString("response").equalsIgnoreCase("0")) {
                            status.put(WeLivePlayerUtils.ERROR_CODE,
                                    String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
                            status.put(WeLivePlayerUtils.ERROR_MSG, root.toString());
                        }
                    }
                }
            } else {
                status.put(WeLivePlayerUtils.ERROR_CODE, String.valueOf(HttpStatus.FORBIDDEN.value()));
                status.put(WeLivePlayerUtils.ERROR_MSG, "user not authorized");
            }

        } else {
            status.put(WeLivePlayerUtils.ERROR_CODE, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
            status.put(WeLivePlayerUtils.ERROR_MSG, "null profile sent");
        }

    } catch (Exception e) {
        logger.error("WLP: Calling[" + url + "] " + e.getMessage());
        status.put(WeLivePlayerUtils.ERROR_CODE, String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
        status.put(WeLivePlayerUtils.ERROR_MSG, e.getMessage());
    }

    return status;
}

From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java

@Test
public void testGetTaskByIdAuthorization() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();

    String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId())
            .getId();//from w ww. ja va 2 s  .c o m

    // Start process by one user and try to access the task as the task assignee instead of the process
    // initiator to see if the assignee is authorized to get the task
    ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        TasksClient tasksClient = publicApiClient.tasksClient();

        // Try accessing task when NOT involved in the task
        try {
            tasksClient.findTaskById(task.getId());
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }

        // Set assignee, task should be accessible now
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser());
        JSONObject jsonObject = tasksClient.findTaskById(task.getId());
        assertNotNull(jsonObject);

        // Fetching task as admin should be possible
        String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));
        jsonObject = tasksClient.findTaskById(task.getId());
        assertNotNull(jsonObject);

        // Fetching the task as a admin from another tenant shouldn't be possible
        TestNetwork anotherNetwork = getOtherNetwork(requestContext.getNetworkId());
        tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + anotherNetwork.getId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));
        try {
            tasksClient.findTaskById(task.getId());
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }
    } finally {
        cleanupProcessInstance(processInstance);
    }
}

From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java

@Test
@SuppressWarnings("unchecked")
public void testUpdateTaskMnt13276() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String initiatorId = requestContext.getRunAsUser();
    ProcessInfo processInfo = startReviewPooledProcess(requestContext);

    // create test users
    final List<TestPerson> persons = transactionHelper
            .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<List<TestPerson>>() {
                @SuppressWarnings("synthetic-access")
                public List<TestPerson> execute() throws Throwable {
                    ArrayList<TestPerson> persons = new ArrayList<TestPerson>();
                    String temp = "_" + System.currentTimeMillis();
                    persons.add(currentNetwork.createUser(new PersonInfo("user0", "user0", "user0" + temp,
                            "password", null, "skype", "location", "telephone", "mob", "instant", "google")));
                    persons.add(currentNetwork.createUser(new PersonInfo("user1", "user1", "user1" + temp,
                            "password", null, "skype", "location", "telephone", "mob", "instant", "google")));
                    persons.add(currentNetwork.createUser(new PersonInfo("user2", "user2", "user2" + temp,
                            "password", null, "skype", "location", "telephone", "mob", "instant", "google")));
                    return persons;
                }/* w w  w  .  jav  a2s .co m*/
            }, false, true);

    final MemberOfSite memberOfSite = currentNetwork.getSiteMemberships(initiatorId).get(0);

    // startReviewPooledProcess() uses initiator's site id and role name for construct bpm_groupAssignee, thus we need appropriate things for created users
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>() {
        public Void execute() throws Throwable {
            TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                @Override
                public Void doWork() throws Exception {
                    TestSite initiatorSite = (TestSite) memberOfSite.getSite();
                    initiatorSite.inviteToSite(persons.get(0).getId(), memberOfSite.getRole());
                    initiatorSite.inviteToSite(persons.get(1).getId(), memberOfSite.getRole());
                    // this user wouldn't be in group
                    initiatorSite.inviteToSite(persons.get(2).getId(),
                            SiteRole.SiteConsumer == memberOfSite.getRole() ? SiteRole.SiteCollaborator
                                    : SiteRole.SiteConsumer);
                    return null;
                }
            }, AuthenticationUtil.getAdminUserName(), currentNetwork.getId());
            return null;
        }
    }, false, true);

    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInfo.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();

        // Updating the task by user in group
        JSONObject taskBody = new JSONObject();
        taskBody.put("name", "Updated name by user in group");
        List<String> selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "name" }));
        requestContext.setRunAsUser(persons.get(0).getId());
        JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name by user in group", result.get("name"));
        task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInfo.getId())
                .singleResult();
        assertNotNull(task);
        assertEquals("Updated name by user in group", task.getName());

        // Updating the task by user not in group
        try {
            taskBody.put("name", "Updated name by user not in group");
            requestContext.setRunAsUser(persons.get(2).getId());
            tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("User not from group should not see items.");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }

        // claim task
        TaskService taskService = activitiProcessEngine.getTaskService();
        task = taskService.createTaskQuery().processInstanceId(processInfo.getId()).singleResult();
        taskService.setAssignee(task.getId(), persons.get(1).getId());
        // Updating by user in group for claimed task by another user
        try {
            taskBody = new JSONObject();
            taskBody.put("name", "Updated name by user in group for claimed task");
            selectedFields.addAll(Arrays.asList(new String[] { "name" }));
            requestContext.setRunAsUser(persons.get(0).getId());
            result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("User from group should not see items for claimed task by another user.");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }
    } finally {
        cleanupProcessInstance(processInfo.getId());
    }
}

From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java

@Test
@SuppressWarnings("unchecked")
public void testUpdateTaskAuthorization() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId())
            .getId();/*from  ww  w  .ja  va 2  s  .c  om*/

    ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();

        // Updating the task when NOT assignee/owner or initiator results in an error
        JSONObject taskBody = new JSONObject();
        taskBody.put("name", "Updated name");
        List<String> selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "name" }));
        try {
            tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }

        // Set assignee to current user, update should succeed
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), requestContext.getRunAsUser());
        taskBody.put("name", "Updated name by assignee");

        JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name by assignee", result.get("name"));
        task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        assertEquals("Updated name by assignee", task.getName());

        // Set owner to current user, update should succeed
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
        activitiProcessEngine.getTaskService().setOwner(task.getId(), requestContext.getRunAsUser());
        taskBody.put("name", "Updated name by owner");

        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name by owner", result.get("name"));
        task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        assertEquals("Updated name by owner", task.getName());

        // Update as process initiator
        taskBody.put("name", "Updated name by initiator");
        requestContext.setRunAsUser(initiator);
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name by initiator", result.get("name"));
        task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        assertEquals("Updated name by initiator", task.getName());

        // Update as administrator
        String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));

        taskBody.put("name", "Updated name by admin");
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name by admin", result.get("name"));
        task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        assertNotNull(task);
        assertEquals("Updated name by admin", task.getName());
    } finally {
        cleanupProcessInstance(processInstance);
    }
}

From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java

@Test
@SuppressWarnings("unchecked")
public void testClaimTask() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId())
            .getId();//from  w w w  .j a  va2 s. c  om

    ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();

        // Claiming the task when NOT part of candidate-group results in an error
        JSONObject taskBody = new JSONObject();
        taskBody.put("state", "claimed");
        List<String> selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "state", "assignee" }));
        try {
            tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }

        // Set candidate for task, but keep assignee
        List<MemberOfSite> memberships = getTestFixture().getNetwork(requestContext.getNetworkId())
                .getSiteMemberships(requestContext.getRunAsUser());
        assertTrue(memberships.size() > 0);
        MemberOfSite memberOfSite = memberships.get(0);
        String group = "GROUP_site_" + memberOfSite.getSiteId() + "_" + memberOfSite.getRole().name();
        activitiProcessEngine.getTaskService().addCandidateGroup(task.getId(), group);

        // Claiming the task when part of candidate-group but another person has this task assigned results in conflict
        try {
            tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.CONFLICT.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("The task is already claimed by another user.", expected.getHttpResponse());
        }

        // Claiming the task when part of candidate-group and NO assignee is currenlty set should work
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
        taskBody = new JSONObject();
        taskBody.put("state", "claimed");
        JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNotNull(result);
        assertEquals(requestContext.getRunAsUser(), result.get("assignee"));
        assertEquals(requestContext.getRunAsUser(), activitiProcessEngine.getTaskService().createTaskQuery()
                .taskId(task.getId()).singleResult().getAssignee());

        // Re-claiming the same task with the current assignee shouldn't be a problem
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNotNull(result);
        assertEquals(requestContext.getRunAsUser(), result.get("assignee"));
        assertEquals(requestContext.getRunAsUser(), activitiProcessEngine.getTaskService().createTaskQuery()
                .taskId(task.getId()).singleResult().getAssignee());

        // Claiming as a candidateUser should also work
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
        activitiProcessEngine.getTaskService().deleteGroupIdentityLink(task.getId(), group,
                IdentityLinkType.CANDIDATE);
        activitiProcessEngine.getTaskService().addCandidateUser(task.getId(), requestContext.getRunAsUser());
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNotNull(result);
        assertEquals(requestContext.getRunAsUser(), result.get("assignee"));
        assertEquals(requestContext.getRunAsUser(), activitiProcessEngine.getTaskService().createTaskQuery()
                .taskId(task.getId()).singleResult().getAssignee());

        // Claiming as a task owner should also work
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
        activitiProcessEngine.getTaskService().setOwner(task.getId(), requestContext.getRunAsUser());
        activitiProcessEngine.getTaskService().deleteUserIdentityLink(task.getId(),
                requestContext.getRunAsUser(), IdentityLinkType.CANDIDATE);
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNotNull(result);
        assertEquals(requestContext.getRunAsUser(), result.get("assignee"));
        assertEquals(requestContext.getRunAsUser(), activitiProcessEngine.getTaskService().createTaskQuery()
                .taskId(task.getId()).singleResult().getAssignee());

        // Claiming as admin should work
        String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));

        activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
        activitiProcessEngine.getTaskService().deleteUserIdentityLink(task.getId(),
                requestContext.getRunAsUser(), IdentityLinkType.CANDIDATE);
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNotNull(result);
        assertEquals(tenantAdmin, result.get("assignee"));
        assertEquals(tenantAdmin, activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId())
                .singleResult().getAssignee());

    } finally {
        cleanupProcessInstance(processInstance);
    }
}

From source file:org.alfresco.rest.workflow.api.tests.TaskWorkflowApiTest.java

@Test
@SuppressWarnings("unchecked")
public void testUnClaimTask() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String user = requestContext.getRunAsUser();
    String initiator = getOtherPersonInNetwork(requestContext.getRunAsUser(), requestContext.getNetworkId())
            .getId();//ww  w  .j  a  va 2s.  c om

    ProcessInstance processInstance = startAdhocProcess(initiator, requestContext.getNetworkId(), null);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();

        // Unclaiming the task when NOT assignee, owner, initiator or admin results in error
        JSONObject taskBody = new JSONObject();
        taskBody.put("state", "unclaimed");
        List<String> selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "state" }));
        try {
            tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("Exception expected");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }

        // Unclaiming as process initiator
        requestContext.setRunAsUser(initiator);
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), null);
        JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNull(result.get("assignee"));
        assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId()).singleResult()
                .getAssignee());

        // Unclaiming as assignee
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), user);
        requestContext.setRunAsUser(user);
        assertNotNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId())
                .singleResult().getAssignee());
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNull(result.get("assignee"));
        assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId()).singleResult()
                .getAssignee());

        // Unclaim as owner
        activitiProcessEngine.getTaskService().setOwner(task.getId(), user);
        activitiProcessEngine.getTaskService().setAssignee(task.getId(), initiator);
        assertNotNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId())
                .singleResult().getAssignee());
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNull(result.get("assignee"));
        assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId()).singleResult()
                .getAssignee());

        // Unclaim as admin
        String tenantAdmin = AuthenticationUtil.getAdminUserName() + "@" + requestContext.getNetworkId();
        publicApiClient.setRequestContext(new RequestContext(TenantUtil.DEFAULT_TENANT, tenantAdmin));

        activitiProcessEngine.getTaskService().setAssignee(task.getId(), initiator);
        activitiProcessEngine.getTaskService().deleteUserIdentityLink(task.getId(),
                requestContext.getRunAsUser(), IdentityLinkType.CANDIDATE);
        assertNotNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId())
                .singleResult().getAssignee());
        result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertNull(result.get("assignee"));
        assertNull(activitiProcessEngine.getTaskService().createTaskQuery().taskId(task.getId()).singleResult()
                .getAssignee());
    } finally {
        cleanupProcessInstance(processInstance);
    }
}