Search in sources :

Example 1 with CandlepinException

use of org.candlepin.common.exceptions.CandlepinException 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 2 with CandlepinException

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

the class PinsetterJobListener method updateJob.

@Transactional
private void updateJob(JobExecutionContext ctx, JobExecutionException exc) {
    JobStatus status = curator.find(ctx.getJobDetail().getKey().getName());
    if (status != null) {
        if (exc != null) {
            log.error("Job [" + status.getId() + "] failed.", exc);
            status.setState(JobState.FAILED);
            status.setResult(exc.getMessage());
            if (exc.getCause() instanceof CandlepinException) {
                status.setResultData(((CandlepinException) exc.getCause()).message());
            }
        } else {
            status.update(ctx);
        }
        curator.merge(status);
    } else {
        log.debug("No jobinfo found for job: " + ctx);
    }
}
Also used : JobStatus(org.candlepin.pinsetter.core.model.JobStatus) CandlepinException(org.candlepin.common.exceptions.CandlepinException) Transactional(com.google.inject.persist.Transactional)

Example 3 with CandlepinException

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

the class OwnerResource method importManifestAsync.

/**
 * Initiates an asynchronous manifest import for the given organization. The details of
 * the started job can be obtained via the {@link JobResource}.
 *
 * This will bring in any products, content, and subscriptions that were assigned to
 * the distributor who generated the manifest.
 *
 * @return a JobDetail object representing the newly started {@link ImportJob}.
 * @httpcode 400
 * @httpcode 404
 * @httpcode 500
 * @httpcode 200
 * @httpcode 409
 */
@POST
@Path("{owner_key}/imports/async")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(notes = "Initiates an asynchronous manifest import for the given organization. " + "This will bring in any products, content, and subscriptions that were " + "assigned to the distributor who generated the manifest.", value = "Import Manifest Asynchronously")
@ApiResponses({ @ApiResponse(code = 400, message = ""), @ApiResponse(code = 404, message = "Owner not found"), @ApiResponse(code = 500, message = ""), @ApiResponse(code = 409, message = "") })
public JobDetail importManifestAsync(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @QueryParam("force") String[] overrideConflicts, MultipartInput input) {
    ConflictOverrides overrides = processConflictOverrideParams(overrideConflicts);
    UploadMetadata fileData = new UploadMetadata();
    Owner owner = findOwnerByKey(ownerKey);
    try {
        fileData = getArchiveFromResponse(input);
        String archivePath = fileData.getData().getAbsolutePath();
        log.info("Running async import of archive {} for owner {}", archivePath, owner.getDisplayName());
        return manifestManager.importManifestAsync(owner, fileData.getData(), fileData.getUploadedFilename(), overrides);
    } catch (IOException e) {
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw new IseException(i18n.tr("Error reading export archive"), e);
    } catch (ManifestFileServiceException e) {
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw new IseException(i18n.tr("Error storing uploaded archive for asynchronous processing."), e);
    } catch (CandlepinException e) {
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw e;
    }
}
Also used : ConflictOverrides(org.candlepin.sync.ConflictOverrides) CandlepinException(org.candlepin.common.exceptions.CandlepinException) Owner(org.candlepin.model.Owner) IseException(org.candlepin.common.exceptions.IseException) IOException(java.io.IOException) ManifestFileServiceException(org.candlepin.sync.file.ManifestFileServiceException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 4 with CandlepinException

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

the class OwnerResource method importManifest.

/**
 * Imports a manifest zip file for the given organization.
 *
 * This will bring in any products, content, and subscriptions that were assigned to
 * the distributor who generated the manifest.
 *
 * @deprecated use GET /owners/:owner_key/imports/async
 *
 * @return a ImportRecord object if the import is successful.
 * @httpcode 400
 * @httpcode 404
 * @httpcode 500
 * @httpcode 200
 * @httpcode 409
 */
@POST
@Path("{owner_key}/imports")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(notes = "Imports a manifest zip file for the given organization. " + "This will bring in any products, content, and subscriptions that were " + "assigned to the distributor who generated the manifest.", value = "Import Manifest")
@ApiResponses({ @ApiResponse(code = 400, message = ""), @ApiResponse(code = 404, message = "Owner not found"), @ApiResponse(code = 500, message = ""), @ApiResponse(code = 409, message = "") })
@Deprecated
public ImportRecord importManifest(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @QueryParam("force") String[] overrideConflicts, MultipartInput input) {
    ConflictOverrides overrides = processConflictOverrideParams(overrideConflicts);
    UploadMetadata fileData = new UploadMetadata();
    Owner owner = findOwnerByKey(ownerKey);
    try {
        fileData = getArchiveFromResponse(input);
        return manifestManager.importManifest(owner, fileData.getData(), fileData.getUploadedFilename(), overrides);
    } catch (IOException e) {
        log.error("Reading error during importing", e);
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw new IseException(i18n.tr("Error reading export archive"), e);
    }// These come back with internationalized messages, so we can transfer:
     catch (SyncDataFormatException e) {
        log.error("Format error of the data in a manifest", e);
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw new BadRequestException(e.getMessage(), e);
    } catch (ImporterException e) {
        log.error("Problem with archive", e);
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw new IseException(e.getMessage(), e);
    }// to pass on the http return code
     catch (CandlepinException e) {
        log.error("Recording import failure", e);
        manifestManager.recordImportFailure(owner, e, fileData.getUploadedFilename());
        throw e;
    } finally {
        log.info("Import attempt completed for owner {}", owner.getDisplayName());
    }
}
Also used : ImporterException(org.candlepin.sync.ImporterException) ConflictOverrides(org.candlepin.sync.ConflictOverrides) CandlepinException(org.candlepin.common.exceptions.CandlepinException) Owner(org.candlepin.model.Owner) IseException(org.candlepin.common.exceptions.IseException) SyncDataFormatException(org.candlepin.sync.SyncDataFormatException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) IOException(java.io.IOException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 5 with CandlepinException

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

the class CandlepinExceptionMapper method getDefaultBuilder.

protected ResponseBuilder getDefaultBuilder(Throwable exception, Status status, MediaType responseMediaType) {
    Throwable cause = exception;
    while (cause.getCause() != null) {
        cause = cause.getCause();
    }
    String message = "";
    StackTraceElement[] stes = cause.getStackTrace();
    // happen which breaks things.
    if (stes != null && stes.length > 0) {
        StackTraceElement ele = stes[0];
        int line = ele.getLineNumber();
        String method = ele.getMethodName();
        String clazz = ele.getClassName();
        message = i18n.get().tr("Runtime Error {0} at {1}.{2}:{3}", exception.getMessage(), clazz, method, line);
    } else {
        // just use the exception message
        message = i18n.get().tr("Runtime Error {0}", exception.getMessage());
    }
    if (!(exception instanceof CandlepinException) || ((CandlepinException) exception).isLogException()) {
        log.error(message, exception);
    }
    if (status == null) {
        status = Status.INTERNAL_SERVER_ERROR;
    }
    Map<String, String> map = VersionUtil.getVersionMap();
    return Response.status(status).entity(new ExceptionMessage(message)).type(responseMediaType).header(VersionUtil.VERSION_HEADER, map.get("version") + "-" + map.get("release"));
}
Also used : CandlepinException(org.candlepin.common.exceptions.CandlepinException) ExceptionMessage(org.candlepin.common.exceptions.ExceptionMessage)

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