Example usage for org.springframework.http HttpStatus CONFLICT

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

Introduction

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

Prototype

HttpStatus CONFLICT

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

Click Source Link

Document

409 Conflict .

Usage

From source file:io.openvidu.server.recording.service.RecordingManager.java

public HttpStatus deleteRecordingFromHost(String recordingId, boolean force) {

    if (!force && (this.startedRecordings.containsKey(recordingId)
            || this.startingRecordings.containsKey(recordingId))) {
        // Cannot delete an active recording
        return HttpStatus.CONFLICT;
    }// ww  w. ja  v a 2 s . co  m

    Recording recording = getRecordingFromHost(recordingId);
    if (recording == null) {
        return HttpStatus.NOT_FOUND;
    }

    File folder = new File(this.openviduConfig.getOpenViduRecordingPath());
    File[] files = folder.listFiles();
    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory() && files[i].getName().equals(recordingId)) {
            // Correct folder. Delete it
            try {
                FileUtils.deleteDirectory(files[i]);
            } catch (IOException e) {
                log.error("Couldn't delete folder {}", files[i].getAbsolutePath());
            }
            break;
        }
    }

    return HttpStatus.NO_CONTENT;
}

From source file:it.infn.mw.iam.api.scim.controller.ScimExceptionHandler.java

@ResponseStatus(code = HttpStatus.CONFLICT)
@ExceptionHandler(ScimResourceExistsException.class)
@ResponseBody//from   ww w .  j  a v  a 2 s.  co  m
public ScimErrorResponse handleResourceExists(ScimResourceExistsException e) {
    return buildErrorResponse(HttpStatus.CONFLICT, e.getMessage());
}

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();/*w  w w .j  a  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();

        // 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.ambraproject.wombat.controller.MediaCurationController.java

/**
 * Serves as a POST endpoint to submit media curation requests
 *
 * @param model data passed in from the view
 * @param site  current site//www.j a v  a  2s.c om
 * @return path to the template
 * @throws IOException
 */
@RequestMapping(name = "submitMediaCurationRequest", value = "/article/submitMediaCurationRequest", method = RequestMethod.POST)
@ResponseBody
public String submitMediaCurationRequest(HttpServletRequest request, Model model, @SiteParam Site site,
        @RequestParam("doi") String doi, @RequestParam("link") String link,
        @RequestParam("comment") String comment, @RequestParam("title") String title,
        @RequestParam("publishedOn") String publishedOn, @RequestParam("name") String name,
        @RequestParam("email") String email, @RequestParam("consent") String consent) throws IOException {
    requireNonemptyParameter(doi);

    if (!link.matches("^\\w+://.*")) {
        link = "http://" + link;
    }

    if (!validateMediaCurationInput(model, link, name, email, title, publishedOn, consent)) {
        //return model for error reporting
        return jsonService.serialize(model);
    }

    String linkComment = name + ", " + email + "\n" + comment;

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("doi", doi.replaceFirst("info:doi/", "")));
    params.add(new BasicNameValuePair("link", link));
    params.add(new BasicNameValuePair("comment", linkComment));
    params.add(new BasicNameValuePair("title", title));
    params.add(new BasicNameValuePair("publishedOn", publishedOn));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");

    String mediaCurationUrl = (String) site.getTheme().getConfigMap("mediaCuration").get("mediaCurationUrl");
    if (mediaCurationUrl == null) {
        throw new RuntimeException("Media curation URL is not configured");
    }

    HttpPost httpPost = new HttpPost(mediaCurationUrl);
    httpPost.setEntity(entity);
    StatusLine statusLine = null;
    try (CloseableHttpResponse response = cachedRemoteReader.getResponse(httpPost)) {
        statusLine = response.getStatusLine();
    } catch (ServiceRequestException e) {
        //This exception is thrown when the submitted link is already present for the article.
        if (e.getStatusCode() == HttpStatus.CONFLICT.value()
                && e.getResponseBody().equals("The link already exists")) {
            model.addAttribute("formError",
                    "This link has already been submitted. Please submit a different link");
            model.addAttribute("isValid", false);
        } else {
            throw new RuntimeException(e);
        }
    } finally {
        httpPost.releaseConnection();
    }

    if (statusLine != null && statusLine.getStatusCode() != HttpStatus.CREATED.value()) {
        throw new RuntimeException("bad response from media curation server: " + statusLine);
    }

    return jsonService.serialize(model);
}

From source file:org.cloudfoundry.identity.uaa.client.ClientAdminEndpoints.java

@ExceptionHandler(ClientAlreadyExistsException.class)
public ResponseEntity<InvalidClientDetailsException> handleClientAlreadyExists(ClientAlreadyExistsException e) {
    incrementErrorCounts(e);//w ww.  j  a v  a2  s.  c  o m
    return new ResponseEntity<>(new InvalidClientDetailsException(e.getMessage()), HttpStatus.CONFLICT);
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static ScimGroupExternalMember mapExternalGroup(String token, String zoneId, String url,
        ScimGroupExternalMember scimGroup) {

    RestTemplate template = new RestTemplate();
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", APPLICATION_JSON_VALUE);
    headers.add("Authorization", "bearer " + token);
    headers.add("Content-Type", APPLICATION_JSON_VALUE);
    if (StringUtils.hasText(zoneId)) {
        headers.add(IdentityZoneSwitchingFilter.HEADER, zoneId);
    }/* www . j a  va  2  s  .  co m*/
    ResponseEntity<ScimGroupExternalMember> mapGroup = template.exchange(url + "/Groups/External",
            HttpMethod.POST, new HttpEntity(JsonUtils.writeValueAsBytes(scimGroup), headers),
            ScimGroupExternalMember.class);
    if (HttpStatus.CREATED.equals(mapGroup.getStatusCode())) {
        return mapGroup.getBody();
    } else if (HttpStatus.CONFLICT.equals(mapGroup.getStatusCode())) {
        return scimGroup;
    }
    throw new IllegalArgumentException("Invalid status code:" + mapGroup.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static BaseClientDetails createOrUpdateClient(String adminToken, String url, String switchToZoneId,
        BaseClientDetails client) throws Exception {

    RestTemplate template = new RestTemplate();
    template.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override/*w w  w  . java  2s  .  c  o  m*/
        protected boolean hasError(HttpStatus statusCode) {
            return statusCode.is5xxServerError();
        }
    });
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", APPLICATION_JSON_VALUE);
    headers.add("Authorization", "bearer " + adminToken);
    headers.add("Content-Type", APPLICATION_JSON_VALUE);
    if (StringUtils.hasText(switchToZoneId)) {
        headers.add(IdentityZoneSwitchingFilter.HEADER, switchToZoneId);
    }
    HttpEntity getHeaders = new HttpEntity(JsonUtils.writeValueAsBytes(client), headers);
    ResponseEntity<String> clientCreate = template.exchange(url + "/oauth/clients", HttpMethod.POST, getHeaders,
            String.class);
    if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
        return JsonUtils.readValue(clientCreate.getBody(), BaseClientDetails.class);
    } else if (clientCreate.getStatusCode() == HttpStatus.CONFLICT) {
        HttpEntity putHeaders = new HttpEntity(JsonUtils.writeValueAsBytes(client), headers);
        ResponseEntity<String> clientUpdate = template.exchange(url + "/oauth/clients/" + client.getClientId(),
                HttpMethod.PUT, putHeaders, String.class);
        if (clientUpdate.getStatusCode() == HttpStatus.OK) {
            return JsonUtils.readValue(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException("Invalid update return code:" + clientUpdate.getStatusCode());
        }
    }
    throw new RuntimeException("Invalid crete return code:" + clientCreate.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.login.EmailResetPasswordService.java

@Override
public void forgotPassword(String email) {
    String subject = getSubjectText();
    String htmlContent = null;/*  w w w  . j  ava  2 s.com*/
    String userId = null;
    try {
        ResponseEntity<Map<String, String>> response = passwordResetEndpoints.resetPassword(email);
        if (response.getStatusCode() == HttpStatus.CONFLICT) {
            //TODO - file story to refactor and not swallow all errors below
            htmlContent = getResetUnavailableEmailHtml(email);
            userId = response.getBody().get("user_id");
        } else if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
            //TODO noop - previous implementation just logged an error
        } else {
            userId = response.getBody().get("user_id");
            htmlContent = getCodeSentEmailHtml(response.getBody().get("code"), email);
        }
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.CONFLICT) {
            htmlContent = getResetUnavailableEmailHtml(email);
            try {
                Map<String, String> body = new ObjectMapper().readValue(e.getResponseBodyAsString(),
                        new TypeReference<Map<String, String>>() {
                        });
                userId = body.get("user_id");
            } catch (IOException ioe) {
                logger.error("Bad response from UAA", ioe);
            }

        } else {
            logger.info("Exception raised while creating password reset for " + email, e);
        }
    } catch (IOException e) {
        logger.error("Exception raised while creating password reset for " + email, e);
    }

    if (htmlContent != null && userId != null) {
        messageService.sendMessage(userId, email, MessageType.PASSWORD_RESET, subject, htmlContent);
    }
}

From source file:org.cloudfoundry.identity.uaa.provider.SamlServiceProviderEndpoints.java

@ExceptionHandler(MetadataProviderException.class)
public ResponseEntity<String> handleMetadataProviderException(MetadataProviderException e) {
    if (e.getMessage().contains("Duplicate")) {
        return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
    } else {/*ww w  .j a v  a2  s  .c om*/
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

From source file:org.cloudfoundry.identity.uaa.provider.SamlServiceProviderEndpoints.java

@ExceptionHandler(SamlSpAlreadyExistsException.class)
public ResponseEntity<String> handleDuplicateServiceProvider() {
    return new ResponseEntity<>("SAML SP with the same entity id already exists.", HttpStatus.CONFLICT);
}