All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.crnk.jpa.internal.OptimisticLockExceptionMapper Maven / Gradle / Ivy

package io.crnk.jpa.internal;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.persistence.OptimisticLockException;

import io.crnk.core.engine.document.ErrorData;
import io.crnk.core.engine.error.ErrorResponse;
import io.crnk.core.engine.error.ExceptionMapper;
import io.crnk.core.engine.http.HttpStatus;

public class OptimisticLockExceptionMapper implements ExceptionMapper {

	private static final String META_TYPE_KEY = "type";

	// assign ID do identity among different CONFLICT_409 results
	private static final String JPA_OPTIMISTIC_LOCK_EXCEPTION_TYPE = "OptimisticLockException";

	private static final String ERROR_TYPE = "conflict";

	@Override
	public ErrorResponse toErrorResponse(OptimisticLockException cve) {
		HashMap meta = new HashMap<>();
		meta.put(META_TYPE_KEY, JPA_OPTIMISTIC_LOCK_EXCEPTION_TYPE);

		ErrorData error = ErrorData.builder()
				.setMeta(meta)
				.setCode(ERROR_TYPE)
				.setStatus(Integer.toString(HttpStatus.CONFLICT_409))
				.setDetail(cve.getMessage())
				.build();
		return ErrorResponse.builder().setStatus(HttpStatus.CONFLICT_409).setSingleErrorData(error).build();
	}

	@Override
	public OptimisticLockException fromErrorResponse(ErrorResponse errorResponse) {
		Iterable errors = errorResponse.getErrors();
		ErrorData error = errors.iterator().next();
		String msg = error.getDetail();
		return new OptimisticLockException(msg);
	}

	@Override
	public boolean accepts(ErrorResponse errorResponse) {
		if (errorResponse.getHttpStatus() != HttpStatus.CONFLICT_409) {
			return false;
		}

		Iterable errors = errorResponse.getErrors();
		Iterator iterator = errors.iterator();
		if (!iterator.hasNext()) {
			return false;
		}
		ErrorData errorData = iterator.next();

		Map meta = errorData.getMeta();
		return meta != null && JPA_OPTIMISTIC_LOCK_EXCEPTION_TYPE.equals(meta.get(META_TYPE_KEY));
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy