Java Code Examples for org.springframework.http.HttpStatus#PRECONDITION_FAILED

The following examples show how to use org.springframework.http.HttpStatus#PRECONDITION_FAILED . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MgmtDownloadArtifactResource.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Handles the GET request for downloading an artifact.
 *
 * @param softwareModuleId
 *            of the parent SoftwareModule
 * @param artifactId
 *            of the related Artifact
 *
 * @return responseEntity with status ok if successful
 */
@Override
public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
        @PathVariable("artifactId") final Long artifactId) {

    final SoftwareModule module = softwareModuleManagement.get(softwareModuleId)
            .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
    final Artifact artifact = module.getArtifact(artifactId)
            .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId));

    final AbstractDbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash())
            .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash()));
    final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest();
    final String ifMatch = request.getHeader(HttpHeaders.IF_MATCH);
    if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
        return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
    }

    return FileStreamingUtil.writeFileResponse(file, artifact.getFilename(), artifact.getCreatedAt(),
            requestResponseContextHolder.getHttpServletResponse(), request, null);
}
 
Example 2
Source File: AdminFolders.java    From fenixedu-cms with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/resolver/{folder}", method = RequestMethod.PUT)
public ResponseEntity<?> saveFolderResolver(@PathVariable CMSFolder folder, @RequestBody String code) {
    CmsSettings.getInstance().ensureCanManageFolders();
    try {
        atomic(() -> {
            if (Strings.isNullOrEmpty(code)) {
                folder.setResolver(null);
            } else {
                folder.setResolver(new NashornStrategy<>(FolderResolver.class, code));
            }
            return null;
        });
    } catch (Exception e) {
        Throwable original = unwrap(e);
        return new ResponseEntity<>(original.getClass().getName() + ": " + original.getMessage(),
                HttpStatus.PRECONDITION_FAILED);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example 3
Source File: GenieExceptionMapper.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Handle {@link GenieCheckedException} instances.
 *
 * @param e The exception to map
 * @return A {@link ResponseEntity} with the exception mapped to a {@link HttpStatus}
 */
@ExceptionHandler(GenieCheckedException.class)
public ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e) {
    this.countExceptionAndLog(e);
    if (e instanceof GenieJobResolutionException) {
        // Mapped to Precondition failed to maintain existing contract with V3
        return new ResponseEntity<>(e, HttpStatus.PRECONDITION_FAILED);
    } else if (e instanceof IdAlreadyExistsException) {
        return new ResponseEntity<>(e, HttpStatus.CONFLICT);
    } else if (e instanceof JobNotFoundException | e instanceof NotFoundException) {
        return new ResponseEntity<>(e, HttpStatus.NOT_FOUND);
    } else if (e instanceof PreconditionFailedException) {
        return new ResponseEntity<>(e, HttpStatus.BAD_REQUEST);
    } else {
        return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 
Example 4
Source File: HeaderUtils.java    From spring-content with Apache License 2.0 5 votes vote down vote up
public static void evaluateHeaderConditions(HttpHeaders headers, String resourceETag, Object resourceLastModified) {
	if (ifMatchPresent(headers)) {
		boolean matches = checkIfMatchCondition(headers, resourceETag);
		if (!matches) {
			throw new ResponseStatusException(HttpStatus.PRECONDITION_FAILED, format("Entity If-Match %s failed", headers.getIfMatch().get(0)));
		}
	} else {
		if (isIfUnmodifiedSincePresent(headers)) {
			if (resourceLastModified != null) {
				Long lastModified = Stream.of(resourceLastModified)
						.filter(it -> it != null)
						.map(it -> conversionService.convert(it, Date.class))//
						.map(it -> conversionService.convert(it, Instant.class))//
						.map(it -> it.toEpochMilli())
						.findFirst().orElse(-1L);
				boolean unmodified = checkIfUnmodifiedSinceCondition(headers, lastModified);
				if (!unmodified) {
					throw new ResponseStatusException(HttpStatus.PRECONDITION_FAILED, format("Entity modified since %s", headers.get("If-Unmodified-Since").get(0)));
				}
			}
		}
	}

	boolean noneMatch = checkIfNoneMatchCondition(headers, resourceETag);
	if (!noneMatch) {
		throw new ResponseStatusException(HttpStatus.PRECONDITION_FAILED, format("Entity If-None-Match %s failed", StringUtils.collectionToCommaDelimitedString(headers.get("If-None-Match"))));
	}
}
 
Example 5
Source File: ExceptionTranslator.java    From ogham with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(MessagingException.class)
@ResponseBody
@ResponseStatus(HttpStatus.PRECONDITION_FAILED)
public ErrorResponse processMessagingException(MessagingException e) {
	LOG.error("Failed to send message", e);
	return new ErrorResponse(e);
}
 
Example 6
Source File: ProfessorshipController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(method = DELETE, value = "{professorship}")
@ResponseBody
public ResponseEntity<String> deleteProfessorship(@PathVariable Professorship professorship) {
    try {
        professorshipService.deleteProfessorship(professorship);
        return new ResponseEntity<String>(HttpStatus.ACCEPTED);
    } catch (Exception e) {
        return new ResponseEntity<String>(e.getLocalizedMessage(), HttpStatus.PRECONDITION_FAILED);
    }
}
 
Example 7
Source File: AccountingEventsPaymentManagerController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "{event}/customPaymentPlan/create", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> customPaymentPlanCreate(@PathVariable Event event, @RequestBody String dataJson, User user) {
    accessControlService.checkPaymentManager(event, user);

    try {
        event.createCustomPaymentPlan(getExemptionDateFromJSON(dataJson), createMapFromJSON(dataJson));
        return new ResponseEntity<>(HttpStatus.ACCEPTED);
    } catch (DomainException de) {
        return new ResponseEntity<>(de.getLocalizedMessage(), HttpStatus.PRECONDITION_FAILED);
    }
}
 
Example 8
Source File: ProgramConclusionController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(method = RequestMethod.DELETE, value = "/{programConclusion}")
public ResponseEntity<String> delete(Model model, @PathVariable ProgramConclusion programConclusion) {
    try {
        service.delete(programConclusion);
        return new ResponseEntity<String>(HttpStatus.ACCEPTED);
    } catch (DomainException de) {
        return new ResponseEntity<String>(de.getLocalizedMessage(), HttpStatus.PRECONDITION_FAILED);
    }
}
 
Example 9
Source File: ManagePaymentMethodsController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "{paymentMethod}", method = RequestMethod.DELETE)
public ResponseEntity<String> delete(Model model, @PathVariable PaymentMethod paymentMethod) {
    try {
        paymentMethodService.deletePaymentMethod(paymentMethod);
        return new ResponseEntity<>(HttpStatus.ACCEPTED);
    } catch (DomainException de) {
        return new ResponseEntity<>(de.getLocalizedMessage(), HttpStatus.PRECONDITION_FAILED);
    }
}
 
Example 10
Source File: GenieExceptionMapper.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Handle constraint violation exceptions.
 *
 * @param cve The exception to handle
 * @return A {@link ResponseEntity} instance
 */
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<GeniePreconditionException> handleConstraintViolation(
    final ConstraintViolationException cve
) {
    this.countExceptionAndLog(cve);
    return new ResponseEntity<>(
        new GeniePreconditionException(cve.getMessage(), cve),
        HttpStatus.PRECONDITION_FAILED
    );
}
 
Example 11
Source File: GenieExceptionMapper.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Handle MethodArgumentNotValid  exceptions.
 *
 * @param e The exception to handle
 * @return A {@link ResponseEntity} instance
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException(
    final MethodArgumentNotValidException e
) {
    this.countExceptionAndLog(e);
    return new ResponseEntity<>(
        new GeniePreconditionException(e.getMessage(), e),
        HttpStatus.PRECONDITION_FAILED
    );
}
 
Example 12
Source File: JLineupController.java    From jlineup with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(InvalidRunStateException.class)
public ResponseEntity<String> exceptionHandler(final InvalidRunStateException exception) {
    return new ResponseEntity<>(String.format("Run with id '%s' has wrong state. was %s but expected %s",
            exception.getId(), exception.getCurrentState(), exception.getExpectedState()), HttpStatus.PRECONDITION_FAILED);
}
 
Example 13
Source File: ErrorController.java    From Showcase with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(value = {PreconditionViolationException.class})
protected ResponseEntity<String> handlePreconditionViolationException(PreconditionViolationException ex, WebRequest request) {
    ResponseEntity<String> response = new ResponseEntity<String>(ex.getMessage(), HttpStatus.PRECONDITION_FAILED);
    return response;
}
 
Example 14
Source File: DdiRootController.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public ResponseEntity<InputStream> downloadArtifact(@PathVariable("tenant") final String tenant,
        @PathVariable("controllerId") final String controllerId,
        @PathVariable("softwareModuleId") final Long softwareModuleId,
        @PathVariable("fileName") final String fileName) {
    final ResponseEntity<InputStream> result;

    final Target target = controllerManagement.getByControllerId(controllerId)
            .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
    final SoftwareModule module = controllerManagement.getSoftwareModule(softwareModuleId)
            .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));

    if (checkModule(fileName, module)) {
        LOG.warn("Softare module with id {} could not be found.", softwareModuleId);
        result = ResponseEntity.notFound().build();
    } else {

        // Exception squid:S3655 - Optional access is checked in checkModule
        // subroutine
        @SuppressWarnings("squid:S3655")
        final Artifact artifact = module.getArtifactByFilename(fileName).get();

        final AbstractDbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash())
                .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash()));

        final String ifMatch = requestResponseContextHolder.getHttpServletRequest().getHeader(HttpHeaders.IF_MATCH);
        if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
            result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
        } else {
            final ActionStatus action = checkAndLogDownload(requestResponseContextHolder.getHttpServletRequest(),
                    target, module.getId());

            final Long statusId = action.getId();

            result = FileStreamingUtil.writeFileResponse(file, artifact.getFilename(), artifact.getCreatedAt(),
                    requestResponseContextHolder.getHttpServletResponse(),
                    requestResponseContextHolder.getHttpServletRequest(),
                    (length, shippedSinceLastEvent,
                            total) -> eventPublisher.publishEvent(new DownloadProgressEvent(
                                    tenantAware.getCurrentTenant(), statusId, shippedSinceLastEvent,
                                    serviceMatcher != null ? serviceMatcher.getServiceId() : bus.getId())));

        }
    }
    return result;
}
 
Example 15
Source File: ServiceBrokerExceptionHandler.java    From spring-cloud-open-service-broker with Apache License 2.0 2 votes vote down vote up
/**
 * Handle a {@link ServiceBrokerApiVersionException}
 *
 * @param ex the exception
 * @return an error message
 */
@ExceptionHandler(ServiceBrokerApiVersionException.class)
@ResponseStatus(HttpStatus.PRECONDITION_FAILED)
public ErrorMessage handleException(ServiceBrokerApiVersionException ex) {
	return getErrorResponse(ex);
}