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;
}
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);
}
}
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;
}
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;
}
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"));
}
Aggregations