Search in sources :

Example 6 with CandlepinException

use of org.candlepin.common.exceptions.CandlepinException in project candlepin by candlepin.

the class RuntimeExceptionMapper method toResponse.

@Override
public Response toResponse(RuntimeException exception) {
    MediaType responseMediaType = determineBestMediaType();
    ResponseBuilder bldr = null;
    // Resteasy wraps the actual exception sometimes
    Throwable cause = exception.getCause() == null ? exception : exception.getCause();
    if (cause instanceof CandlepinException) {
        bldr = getBuilder((CandlepinException) cause, responseMediaType);
    } else if (exception instanceof CandlepinException) {
        bldr = getBuilder((CandlepinException) exception, responseMediaType);
    } else {
        bldr = getDefaultBuilder(cause, null, responseMediaType);
    }
    return bldr.build();
}
Also used : CandlepinException(org.candlepin.common.exceptions.CandlepinException) MediaType(javax.ws.rs.core.MediaType) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 7 with CandlepinException

use of org.candlepin.common.exceptions.CandlepinException in project candlepin by candlepin.

the class RuntimeExceptionMapperTest method candlepinException.

@Test
public void candlepinException() {
    CandlepinException ce = mock(CandlepinException.class);
    when(ce.httpReturnCode()).thenReturn(Status.CONFLICT);
    ExceptionMessage em = new ExceptionMessage().setDisplayMessage("you screwed up");
    when(ce.message()).thenReturn(em);
    when(req.getHeader(HttpHeaderNames.ACCEPT)).thenReturn("application/json");
    assertEquals("you screwed up", em.toString());
    Response r = rem.toResponse(ce);
    assertNotNull(r);
    assertEquals(Status.CONFLICT.getStatusCode(), r.getStatus());
    verifyMessage(r, "you screwed up");
}
Also used : Response(javax.ws.rs.core.Response) CandlepinException(org.candlepin.common.exceptions.CandlepinException) ExceptionMessage(org.candlepin.common.exceptions.ExceptionMessage) Test(org.junit.Test)

Example 8 with CandlepinException

use of org.candlepin.common.exceptions.CandlepinException in project candlepin by candlepin.

the class RuntimeExceptionMapperTest method candlepinExceptionWithChildNotCandleping.

@Test
public void candlepinExceptionWithChildNotCandleping() {
    CandlepinException ce = mock(CandlepinException.class);
    when(ce.httpReturnCode()).thenReturn(Status.CONFLICT);
    when(ce.message()).thenReturn(new ExceptionMessage().setDisplayMessage("you screwed up"));
    when(req.getHeader(HttpHeaderNames.ACCEPT)).thenReturn("application/json");
    when(ce.getCause()).thenReturn(new ConflictException("you screwed up"));
    Response r = rem.toResponse(ce);
    assertNotNull(r);
    assertEquals(Status.CONFLICT.getStatusCode(), r.getStatus());
    verifyMessage(r, "you screwed up");
}
Also used : Response(javax.ws.rs.core.Response) CandlepinException(org.candlepin.common.exceptions.CandlepinException) ExceptionMessage(org.candlepin.common.exceptions.ExceptionMessage) ConflictException(org.candlepin.common.exceptions.ConflictException) Test(org.junit.Test)

Example 9 with CandlepinException

use of org.candlepin.common.exceptions.CandlepinException in project candlepin by candlepin.

the class BasicAuth method getPrincipal.

@Override
public Principal getPrincipal(HttpRequest httpRequest) {
    try {
        String auth = AuthUtil.getHeader(httpRequest, "Authorization");
        if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
            String userpassEncoded = auth.substring(6);
            String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":", 2);
            String username = userpass[0];
            String password = null;
            if (userpass.length > 1) {
                password = userpass[1];
            }
            if (log.isDebugEnabled()) {
                Integer length = (password == null) ? 0 : password.length();
                log.debug("check for: {} - password of length {}", username, length);
            }
            if (userServiceAdapter.validateUser(username, password)) {
                Principal principal = createPrincipal(username);
                log.debug("principal created for user '{}'", username);
                return principal;
            } else {
                throw new NotAuthorizedException(i18n.get().tr("Invalid Credentials"));
            }
        }
    } catch (CandlepinException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error getting principal " + e);
        }
        throw e;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error getting principal " + e);
        }
        throw new ServiceUnavailableException(i18n.get().tr("Error contacting user service"));
    }
    return null;
}
Also used : CandlepinException(org.candlepin.common.exceptions.CandlepinException) NotAuthorizedException(org.candlepin.common.exceptions.NotAuthorizedException) ServiceUnavailableException(org.candlepin.common.exceptions.ServiceUnavailableException) CandlepinException(org.candlepin.common.exceptions.CandlepinException) ServiceUnavailableException(org.candlepin.common.exceptions.ServiceUnavailableException) NotAuthorizedException(org.candlepin.common.exceptions.NotAuthorizedException)

Example 10 with CandlepinException

use of org.candlepin.common.exceptions.CandlepinException in project candlepin by candlepin.

the class ConsumerResource method createConsumerFromDTO.

public Consumer createConsumerFromDTO(ConsumerDTO consumer, ConsumerType type, Principal principal, String userName, String ownerKey, String activationKeys, boolean identityCertCreation) throws BadRequestException {
    // API:registerConsumer
    Set<String> keyStrings = splitKeys(activationKeys);
    // Only let NoAuth principals through if there are activation keys to consider:
    if ((principal instanceof NoAuthPrincipal) && keyStrings.isEmpty()) {
        throw new ForbiddenException(i18n.tr("Insufficient permissions"));
    }
    validateOnKeyStrings(keyStrings, ownerKey, userName);
    Owner owner = setupOwner(principal, ownerKey);
    // Raise an exception if none of the keys specified exist for this owner.
    List<ActivationKey> keys = checkActivationKeys(principal, owner, keyStrings);
    userName = setUserName(consumer, principal, userName);
    checkConsumerName(consumer);
    validateViaConsumerType(consumer, type, keys, owner, userName, principal);
    if (type.isType(ConsumerTypeEnum.SHARE)) {
        // Share consumers do not need identity certificates so refuse to create them.
        identityCertCreation = false;
        validateShareConsumer(consumer, principal, keys);
        // if there exists a share consumer between the two orgs, return it.
        Consumer existingShareConsumer = consumerCurator.getSharingConsumer(owner, consumer.getRecipientOwnerKey());
        if (existingShareConsumer != null) {
            return existingShareConsumer;
        }
        consumer.setAutoheal(false);
    } else {
        // this is the default
        consumer.setAutoheal(true);
        if (StringUtils.isNotEmpty(consumer.getRecipientOwnerKey())) {
            throw new BadRequestException(i18n.tr("Only share consumers can specify recipient owners"));
        }
    }
    if (consumer.getServiceLevel() == null) {
        consumer.setServiceLevel("");
    }
    // Sanitize the inbound facts
    this.sanitizeConsumerFacts(consumer);
    // If no service level was specified, and the owner has a default set, use it:
    if (consumer.getServiceLevel().equals("") && owner.getDefaultServiceLevel() != null && !type.isType(ConsumerTypeEnum.SHARE)) {
        consumer.setServiceLevel(owner.getDefaultServiceLevel());
    }
    Consumer consumerToCreate = new Consumer();
    consumerToCreate.setOwner(owner);
    populateEntity(consumerToCreate, consumer);
    consumerToCreate.setType(type);
    if (!type.isType(ConsumerTypeEnum.SHARE)) {
        consumerToCreate.setCanActivate(subAdapter.canActivateSubscription(consumerToCreate));
    }
    HypervisorId hvsrId = consumerToCreate.getHypervisorId();
    if (hvsrId != null && hvsrId.getHypervisorId() != null && !hvsrId.getHypervisorId().isEmpty()) {
        // If a hypervisorId is supplied, make sure the consumer and owner are correct
        hvsrId.setConsumer(consumerToCreate);
        hvsrId.setOwner(owner);
    }
    updateCapabilities(consumerToCreate, null);
    logNewConsumerDebugInfo(consumerToCreate, keys, type);
    validateContentAccessMode(consumerToCreate, owner);
    consumerBindUtil.validateServiceLevel(owner.getId(), consumerToCreate.getServiceLevel());
    try {
        Date createdDate = consumerToCreate.getCreated();
        Date lastCheckIn = consumerToCreate.getLastCheckin();
        // create sets created to current time.
        consumerToCreate = consumerCurator.create(consumerToCreate);
        // If we sent in a created date, we want it persisted at the update below
        if (createdDate != null) {
            consumerToCreate.setCreated(createdDate);
        }
        if (lastCheckIn != null) {
            log.info("Creating with specific last check-in time: {}", lastCheckIn);
            consumerToCreate.setLastCheckin(lastCheckIn);
        }
        if (identityCertCreation) {
            IdentityCertificate idCert = generateIdCert(consumerToCreate, false);
            consumerToCreate.setIdCert(idCert);
        }
        sink.emitConsumerCreated(consumerToCreate);
        if (keys.size() > 0) {
            consumerBindUtil.handleActivationKeys(consumerToCreate, keys, owner.isAutobindDisabled());
        }
        // Don't allow complianceRules to update entitlementStatus, because we're about to perform
        // an update unconditionally.
        complianceRules.getStatus(consumerToCreate, null, false, false);
        consumerCurator.update(consumerToCreate);
        log.info("Consumer {} created in org {}", consumerToCreate.getUuid(), consumerToCreate.getOwnerId());
        return consumerToCreate;
    } catch (CandlepinException ce) {
        // If it is one of ours, rethrow it.
        throw ce;
    } catch (Exception e) {
        log.error("Problem creating unit:", e);
        throw new BadRequestException(i18n.tr("Problem creating unit {0}", consumer));
    }
}
Also used : CandlepinException(org.candlepin.common.exceptions.CandlepinException) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) Owner(org.candlepin.model.Owner) NoAuthPrincipal(org.candlepin.auth.NoAuthPrincipal) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) IseException(org.candlepin.common.exceptions.IseException) AutobindDisabledForOwnerException(org.candlepin.controller.AutobindDisabledForOwnerException) CandlepinException(org.candlepin.common.exceptions.CandlepinException) IOException(java.io.IOException) NotFoundException(org.candlepin.common.exceptions.NotFoundException) ExportCreationException(org.candlepin.sync.ExportCreationException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) PropertyValidationException(org.candlepin.util.PropertyValidationException) DeletedConsumer(org.candlepin.model.DeletedConsumer) Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) HypervisorId(org.candlepin.model.HypervisorId) IdentityCertificate(org.candlepin.model.IdentityCertificate)

Aggregations

CandlepinException (org.candlepin.common.exceptions.CandlepinException)12 IOException (java.io.IOException)5 BadRequestException (org.candlepin.common.exceptions.BadRequestException)5 IseException (org.candlepin.common.exceptions.IseException)5 ApiOperation (io.swagger.annotations.ApiOperation)4 ApiResponses (io.swagger.annotations.ApiResponses)4 Consumes (javax.ws.rs.Consumes)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 Owner (org.candlepin.model.Owner)4 POST (javax.ws.rs.POST)3 ExceptionMessage (org.candlepin.common.exceptions.ExceptionMessage)3 AutobindDisabledForOwnerException (org.candlepin.controller.AutobindDisabledForOwnerException)3 Consumer (org.candlepin.model.Consumer)3 DeletedConsumer (org.candlepin.model.DeletedConsumer)3 Transactional (com.google.inject.persist.Transactional)2 GeneralSecurityException (java.security.GeneralSecurityException)2 Date (java.util.Date)2 Response (javax.ws.rs.core.Response)2 ForbiddenException (org.candlepin.common.exceptions.ForbiddenException)2