Search in sources :

Example 6 with BadRequestException

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

the class ManifestManager method importStoredManifest.

/**
 * Imports a stored manifest file into the target {@link Owner}. The stored file is deleted
 * as soon as the import is complete.
 *
 * @param targetOwner the target owner.
 * @param fileId the manifest file ID.
 * @param overrides the {@link ConflictOverrides} to apply to the import process.
 * @param uploadedFileName the originally uploaded file name.
 * @return the result of the import.
 * @throws BadRequestException if the file is not found in the {@link ManifestFileService}
 * @throws ImporterException if there is an issue importing the file.
 */
@Transactional
public ImportRecord importStoredManifest(Owner targetOwner, String fileId, ConflictOverrides overrides, String uploadedFileName) throws BadRequestException, ImporterException {
    ManifestFile manifest = manifestFileService.get(fileId);
    if (manifest == null) {
        throw new BadRequestException(i18n.tr("The requested manifest file was not found: {0}", fileId));
    }
    ImportRecord importResult = importer.loadStoredExport(manifest, targetOwner, overrides, uploadedFileName);
    deleteStoredManifest(manifest.getId());
    return importResult;
}
Also used : BadRequestException(org.candlepin.common.exceptions.BadRequestException) ImportRecord(org.candlepin.model.ImportRecord) ManifestFile(org.candlepin.sync.file.ManifestFile) Transactional(com.google.inject.persist.Transactional)

Example 7 with BadRequestException

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

the class ManifestManager method writeStoredExportToResponse.

/**
 * Write the stored manifest file to the specified response output stream and update
 * the appropriate response data.
 *
 * @param exportId the id of the manifest file to find.
 * @param exportedConsumerUuid the UUID of the consumer the export was generated for.
 * @param response the response to write the file to.
 * @throws ManifestFileServiceException if there was an issue getting the file from the service
 * @throws NotFoundException if the manifest file is not found
 * @throws BadRequestException if the manifests target consumer does not match the specified
 *                             consumer.
 * @throws IseException if there was an issue writing the file to the response.
 */
@Transactional
public void writeStoredExportToResponse(String exportId, String exportedConsumerUuid, HttpServletResponse response) throws ManifestFileServiceException, NotFoundException, BadRequestException, IseException {
    Consumer exportedConsumer = consumerCurator.verifyAndLookupConsumer(exportedConsumerUuid);
    // In order to stream the results from the DB to the client
    // we write the file contents directly to the response output stream.
    // 
    // NOTE: Passing the database input stream to the response builder seems
    // like it would be a correct approach here, but large object streaming
    // can only be done inside a single transaction, so we have to stream it
    // manually.
    ManifestFile manifest = manifestFileService.get(exportId);
    if (manifest == null) {
        throw new NotFoundException(i18n.tr("Unable to find specified manifest by id: {0}", exportId));
    }
    // The specified consumer must match that of the manifest.
    if (!exportedConsumer.getUuid().equals(manifest.getTargetId())) {
        throw new BadRequestException(i18n.tr("Could not validate export against specifed consumer: {0}", exportedConsumer.getUuid()));
    }
    BufferedOutputStream output = null;
    InputStream input = null;
    try {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + manifest.getName());
        // NOTE: Input and output streams are expected to be closed by their creators.
        input = manifest.getInputStream();
        output = new BufferedOutputStream(response.getOutputStream());
        int data = input.read();
        while (data != -1) {
            output.write(data);
            data = input.read();
        }
        output.flush();
    } catch (Exception e) {
        // Reset the response data so that a json response can be returned,
        // by RestEasy.
        response.setContentType("text/json");
        response.setHeader("Content-Disposition", "");
        throw new IseException(i18n.tr("Unable to download manifest: {0}", exportId), e);
    }
}
Also used : Consumer(org.candlepin.model.Consumer) IseException(org.candlepin.common.exceptions.IseException) InputStream(java.io.InputStream) NotFoundException(org.candlepin.common.exceptions.NotFoundException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) BufferedOutputStream(java.io.BufferedOutputStream) ManifestFile(org.candlepin.sync.file.ManifestFile) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ImporterException(org.candlepin.sync.ImporterException) NotFoundException(org.candlepin.common.exceptions.NotFoundException) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) ExportCreationException(org.candlepin.sync.ExportCreationException) IOException(java.io.IOException) ManifestFileServiceException(org.candlepin.sync.file.ManifestFileServiceException) IseException(org.candlepin.common.exceptions.IseException) Transactional(com.google.inject.persist.Transactional)

Example 8 with BadRequestException

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

the class OAuth method getPrincipal.

/**
 * Attempt to pull a principal off of an oauth signed message.
 *
 * @return the principal if it can be created, null otherwise
 */
public Principal getPrincipal(HttpRequest httpRequest) {
    Principal principal = null;
    I18n i18n = i18nProvider.get();
    try {
        if (AuthUtil.getHeader(httpRequest, "Authorization").contains("oauth")) {
            OAuthMessage requestMessage = new RestEasyOAuthMessage(httpRequest);
            OAuthAccessor accessor = this.getAccessor(requestMessage);
            // TODO: This is known to be memory intensive.
            VALIDATOR.validateMessage(requestMessage, accessor);
            // If we got here, it is a valid oauth message.
            // Figure out which kind of principal we should create, based on header
            log.debug("Using OAuth");
            if (!AuthUtil.getHeader(httpRequest, TrustedUserAuth.USER_HEADER).equals("")) {
                principal = userAuth.getPrincipal(httpRequest);
            } else if (!AuthUtil.getHeader(httpRequest, TrustedConsumerAuth.CONSUMER_HEADER).equals("")) {
                principal = consumerAuth.getPrincipal(httpRequest);
            } else {
                // The external system is acting on behalf of itself
                principal = systemAuth.getPrincipal(httpRequest);
            }
        }
    } catch (OAuthProblemException e) {
        log.debug("OAuth Problem", e);
        // status code of 200. make it 401 unauthorized instead.
        if (e.getProblem().equals("signature_invalid")) {
            throw new NotAuthorizedException(i18n.tr("Invalid OAuth unit or secret"));
        }
        Response.Status returnCode = Response.Status.fromStatusCode(e.getHttpStatusCode());
        String message = i18n.tr("OAuth problem encountered. Internal message is: {0}", e.getMessage());
        throw new CandlepinException(returnCode, message);
    } catch (OAuthException e) {
        log.debug("OAuth Error", e);
        String message = i18n.tr("OAuth error encountered. Internal message is: {0}", e.getMessage());
        throw new BadRequestException(message);
    } catch (URISyntaxException e) {
        throw new IseException(e.getMessage(), e);
    } catch (IOException e) {
        throw new IseException(e.getMessage(), e);
    }
    return principal;
}
Also used : CandlepinException(org.candlepin.common.exceptions.CandlepinException) RestEasyOAuthMessage(org.candlepin.common.resteasy.auth.RestEasyOAuthMessage) OAuthMessage(net.oauth.OAuthMessage) OAuthException(net.oauth.OAuthException) NotAuthorizedException(org.candlepin.common.exceptions.NotAuthorizedException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) RestEasyOAuthMessage(org.candlepin.common.resteasy.auth.RestEasyOAuthMessage) OAuthAccessor(net.oauth.OAuthAccessor) OAuthProblemException(net.oauth.OAuthProblemException) IseException(org.candlepin.common.exceptions.IseException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) I18n(org.xnap.commons.i18n.I18n)

Example 9 with BadRequestException

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

the class ConsumerBindUtilTest method registerFailWithKeyServiceLevelNotExist.

@Test(expected = BadRequestException.class)
public void registerFailWithKeyServiceLevelNotExist() throws Exception {
    List<ActivationKey> keys = new ArrayList<>();
    ActivationKey key1 = new ActivationKey("key1", owner);
    keys.add(key1);
    key1.setServiceLevel("I don't exist");
    Consumer consumer = new Consumer("sys.example.com", null, null, system);
    doThrow(new BadRequestException("exception")).when(serviceLevelValidator).validate(eq(owner.getId()), eq(key1.getServiceLevel()));
    consumerBindUtil.handleActivationKeys(consumer, keys, false);
}
Also used : Consumer(org.candlepin.model.Consumer) ArrayList(java.util.ArrayList) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) Test(org.junit.Test)

Example 10 with BadRequestException

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

the class ConsumerBindUtilTest method registerPassWithKeyServiceLevelNotExistOtherKeysSucceed.

@Test
public void registerPassWithKeyServiceLevelNotExistOtherKeysSucceed() throws Exception {
    List<ActivationKey> keys = mockActivationKeys();
    ActivationKey key1 = new ActivationKey("key1", owner);
    keys.add(key1);
    key1.setServiceLevel("I don't exist");
    Consumer consumer = new Consumer("sys.example.com", null, null, system);
    doThrow(new BadRequestException("exception")).when(serviceLevelValidator).validate(eq(owner.getId()), eq(key1.getServiceLevel()));
    consumerBindUtil.handleActivationKeys(consumer, keys, false);
}
Also used : Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) Test(org.junit.Test)

Aggregations

BadRequestException (org.candlepin.common.exceptions.BadRequestException)69 ApiOperation (io.swagger.annotations.ApiOperation)38 Produces (javax.ws.rs.Produces)38 ApiResponses (io.swagger.annotations.ApiResponses)36 Owner (org.candlepin.model.Owner)33 Path (javax.ws.rs.Path)28 Consumer (org.candlepin.model.Consumer)27 Consumes (javax.ws.rs.Consumes)24 NotFoundException (org.candlepin.common.exceptions.NotFoundException)21 POST (javax.ws.rs.POST)15 ConsumerType (org.candlepin.model.ConsumerType)15 Transactional (com.google.inject.persist.Transactional)14 DeletedConsumer (org.candlepin.model.DeletedConsumer)14 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 GET (javax.ws.rs.GET)13 ForbiddenException (org.candlepin.common.exceptions.ForbiddenException)11 PUT (javax.ws.rs.PUT)9 IseException (org.candlepin.common.exceptions.IseException)9 ActivationKey (org.candlepin.model.activationkeys.ActivationKey)9