Search in sources :

Example 1 with IseException

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

the class VerifyAuthorizationFilter method getArguments.

protected Map<Verify, Object> getArguments(HttpRequest request, Method method) {
    ResteasyProviderFactory resourceFactory = ResteasyProviderFactory.getInstance();
    InjectorFactory injectorFactory = resourceFactory.getInjectorFactory();
    ResourceLocator locator = locatorMap.get(method);
    if (null == locator) {
        throw new IseException("Method " + method.getName() + " not registered as RESTful.");
    }
    MethodInjector methodInjector = injectorFactory.createMethodInjector(locator, resourceFactory);
    HttpResponse response = ResteasyProviderFactory.popContextData(HttpResponse.class);
    Object[] args = methodInjector.injectArguments(request, response);
    // LinkedHashMap preserves insertion order
    Map<Verify, Object> argMap = new LinkedHashMap<>();
    Annotation[][] allAnnotations = method.getParameterAnnotations();
    // Any occurrence of the Verify annotation means the method is not superadmin exclusive.
    for (int i = 0; i < allAnnotations.length; i++) {
        for (Annotation a : allAnnotations[i]) {
            if (a instanceof Verify) {
                Verify v = (Verify) a;
                if (!v.nullable() && args[i] == null) {
                    throw new IllegalStateException("Null passed to a non-nullable Verify annotation.");
                } else {
                    argMap.put(v, args[i]);
                }
            }
        }
    }
    return argMap;
}
Also used : HttpResponse(org.jboss.resteasy.spi.HttpResponse) Annotation(java.lang.annotation.Annotation) LinkedHashMap(java.util.LinkedHashMap) MethodInjector(org.jboss.resteasy.spi.MethodInjector) IseException(org.candlepin.common.exceptions.IseException) InjectorFactory(org.jboss.resteasy.spi.InjectorFactory) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) Verify(org.candlepin.auth.Verify) ResourceLocator(org.jboss.resteasy.spi.metadata.ResourceLocator)

Example 2 with IseException

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

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

the class EventBuilder method setEventData.

/**
 * This method is used with any type of event and any target entity.
 * <p>
 * Note: For {@link Type#MODIFIED} events, it can be called twice consecutively
 * to first pass in the original, and then the updated entity. Alternatively,
 * {@link #setEventData(Eventful, Eventful)} can be used in the same use case.
 * </p>
 * @param entity The target entity of the Event
 * @return The builder object
 */
public EventBuilder setEventData(Eventful entity) {
    if (entity != null) {
        // Be careful to check for null before setting so we don't overwrite anything useful
        if (entity instanceof Named && ((Named) entity).getName() != null) {
            event.setTargetName(((Named) entity).getName());
        }
        if (entity instanceof Owned) {
            String ownerId = ((Owned) entity).getOwnerId();
            if (ownerId != null) {
                event.setOwnerId(ownerId);
            }
        }
        if (entity instanceof Entitlement) {
            event.setReferenceType(Event.ReferenceType.POOL);
            Pool referencedPool = ((Entitlement) entity).getPool();
            if (referencedPool != null && referencedPool.getId() != null) {
                event.setReferenceId(referencedPool.getId());
            }
        }
        if (entity.getId() != null) {
            event.setEntityId((String) entity.getId());
            if (entity instanceof ConsumerProperty) {
                Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer();
                if (owningConsumer != null && owningConsumer.getUuid() != null) {
                    event.setConsumerUuid(owningConsumer.getUuid());
                }
            }
        }
        if (event.getTarget().equals(Target.POOL) && event.getType().equals(Type.CREATED)) {
            Map<String, String> eventData = new HashMap<>();
            eventData.put("subscriptionId", ((Pool) entity).getSubscriptionId());
            try {
                event.setEventData(mapper.writeValueAsString(eventData));
            } catch (JsonProcessingException e) {
                log.error("Error while building JSON for pool.created event.", e);
                throw new IseException("Error while building JSON for pool.created event.");
            }
        }
    }
    return this;
}
Also used : Named(org.candlepin.model.Named) Owned(org.candlepin.model.Owned) Consumer(org.candlepin.model.Consumer) IseException(org.candlepin.common.exceptions.IseException) HashMap(java.util.HashMap) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ConsumerProperty(org.candlepin.model.ConsumerProperty)

Example 4 with IseException

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

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

the class OwnerResourceTest method testImportManifestFailure.

@Test
public void testImportManifestFailure() throws IOException, ImporterException {
    ManifestManager manifestManager = mock(ManifestManager.class);
    EventSink es = mock(EventSink.class);
    OwnerResource thisOwnerResource = new OwnerResource(ownerCurator, productCurator, null, null, i18n, es, eventFactory, null, null, manifestManager, null, null, null, null, importRecordCurator, null, null, null, null, null, null, null, contentOverrideValidator, serviceLevelValidator, null, null, null, null, null, this.modelTranslator);
    MultipartInput input = mock(MultipartInput.class);
    InputPart part = mock(InputPart.class);
    File archive = mock(File.class);
    List<InputPart> parts = new ArrayList<>();
    parts.add(part);
    MultivaluedMap<String, String> mm = new MultivaluedMapImpl<>();
    List<String> contDis = new ArrayList<>();
    contDis.add("form-data; name=\"upload\"; filename=\"test_file.zip\"");
    mm.put("Content-Disposition", contDis);
    when(input.getParts()).thenReturn(parts);
    when(part.getHeaders()).thenReturn(mm);
    when(part.getBody(any(GenericType.class))).thenReturn(archive);
    ImporterException expectedException = new ImporterException("Bad import");
    when(manifestManager.importManifest(eq(owner), any(File.class), any(String.class), any(ConflictOverrides.class))).thenThrow(expectedException);
    try {
        thisOwnerResource.importManifest(owner.getKey(), new String[] {}, input);
        fail("Expected IseException was not thrown");
    } catch (IseException ise) {
    // expected, so we catch and go on.
    }
    verify(manifestManager).recordImportFailure(eq(owner), eq(expectedException), eq("test_file.zip"));
}
Also used : ImporterException(org.candlepin.sync.ImporterException) ConflictOverrides(org.candlepin.sync.ConflictOverrides) GenericType(org.jboss.resteasy.util.GenericType) MultipartInput(org.jboss.resteasy.plugins.providers.multipart.MultipartInput) ArrayList(java.util.ArrayList) MultivaluedMapImpl(org.jboss.resteasy.specimpl.MultivaluedMapImpl) Matchers.anyString(org.mockito.Matchers.anyString) ManifestManager(org.candlepin.controller.ManifestManager) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) IseException(org.candlepin.common.exceptions.IseException) EventSink(org.candlepin.audit.EventSink) File(java.io.File) Test(org.junit.Test)

Aggregations

IseException (org.candlepin.common.exceptions.IseException)16 IOException (java.io.IOException)7 ApiOperation (io.swagger.annotations.ApiOperation)6 File (java.io.File)6 Produces (javax.ws.rs.Produces)6 BadRequestException (org.candlepin.common.exceptions.BadRequestException)5 ApiResponses (io.swagger.annotations.ApiResponses)4 Path (javax.ws.rs.Path)4 Consumer (org.candlepin.model.Consumer)4 Owner (org.candlepin.model.Owner)4 ConflictOverrides (org.candlepin.sync.ConflictOverrides)4 ImporterException (org.candlepin.sync.ImporterException)4 ArrayList (java.util.ArrayList)3 GET (javax.ws.rs.GET)3 Verify (org.candlepin.auth.Verify)3 CandlepinException (org.candlepin.common.exceptions.CandlepinException)3 ExportCreationException (org.candlepin.sync.ExportCreationException)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2