use of javax.ws.rs.WebApplicationException in project druid by druid-io.
the class RulesResourceFilter method filter.
@Override
public ContainerRequest filter(ContainerRequest request) {
if (getAuthConfig().isEnabled()) {
// This is an experimental feature, see - https://github.com/druid-io/druid/pull/2424
final String dataSourceName = request.getPathSegments().get(Iterables.indexOf(request.getPathSegments(), new Predicate<PathSegment>() {
@Override
public boolean apply(PathSegment input) {
return input.getPath().equals("rules");
}
}) + 1).getPath();
Preconditions.checkNotNull(dataSourceName);
final AuthorizationInfo authorizationInfo = (AuthorizationInfo) getReq().getAttribute(AuthConfig.DRUID_AUTH_TOKEN);
Preconditions.checkNotNull(authorizationInfo, "Security is enabled but no authorization info found in the request");
final Access authResult = authorizationInfo.isAuthorized(new Resource(dataSourceName, ResourceType.DATASOURCE), getAction(request));
if (!authResult.isAllowed()) {
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(String.format("Access-Check-Result: %s", authResult.toString())).build());
}
}
return request;
}
use of javax.ws.rs.WebApplicationException in project druid by druid-io.
the class SqlResource method doPost.
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response doPost(final SqlQuery sqlQuery) throws SQLException, IOException {
// This is not integrated with the experimental authorization framework.
// (Non-trivial since we don't know the dataSources up-front)
final PlannerResult plannerResult;
final DateTimeZone timeZone;
try (final DruidPlanner planner = plannerFactory.createPlanner(sqlQuery.getContext())) {
plannerResult = planner.plan(sqlQuery.getQuery());
timeZone = planner.getPlannerContext().getTimeZone();
// Remember which columns are time-typed, so we can emit ISO8601 instead of millis values.
final List<RelDataTypeField> fieldList = plannerResult.rowType().getFieldList();
final boolean[] timeColumns = new boolean[fieldList.size()];
final boolean[] dateColumns = new boolean[fieldList.size()];
for (int i = 0; i < fieldList.size(); i++) {
final SqlTypeName sqlTypeName = fieldList.get(i).getType().getSqlTypeName();
timeColumns[i] = sqlTypeName == SqlTypeName.TIMESTAMP;
dateColumns[i] = sqlTypeName == SqlTypeName.DATE;
}
final Yielder<Object[]> yielder0 = Yielders.each(plannerResult.run());
try {
return Response.ok(new StreamingOutput() {
@Override
public void write(final OutputStream outputStream) throws IOException, WebApplicationException {
Yielder<Object[]> yielder = yielder0;
try (final JsonGenerator jsonGenerator = jsonMapper.getFactory().createGenerator(outputStream)) {
jsonGenerator.writeStartArray();
while (!yielder.isDone()) {
final Object[] row = yielder.get();
jsonGenerator.writeStartObject();
for (int i = 0; i < fieldList.size(); i++) {
final Object value;
if (timeColumns[i]) {
value = ISODateTimeFormat.dateTime().print(Calcites.calciteTimestampToJoda((long) row[i], timeZone));
} else if (dateColumns[i]) {
value = ISODateTimeFormat.dateTime().print(Calcites.calciteDateToJoda((int) row[i], timeZone));
} else {
value = row[i];
}
jsonGenerator.writeObjectField(fieldList.get(i).getName(), value);
}
jsonGenerator.writeEndObject();
yielder = yielder.next(null);
}
jsonGenerator.writeEndArray();
jsonGenerator.flush();
// End with CRLF
outputStream.write('\r');
outputStream.write('\n');
} finally {
yielder.close();
}
}
}).build();
} catch (Throwable e) {
// make sure to close yielder if anything happened before starting to serialize the response.
yielder0.close();
throw Throwables.propagate(e);
}
} catch (Exception e) {
log.warn(e, "Failed to handle query: %s", sqlQuery);
final Exception exceptionToReport;
if (e instanceof RelOptPlanner.CannotPlanException) {
exceptionToReport = new ISE("Cannot build plan for query: %s", sqlQuery.getQuery());
} else {
exceptionToReport = e;
}
return Response.serverError().type(MediaType.APPLICATION_JSON_TYPE).entity(jsonMapper.writeValueAsBytes(QueryInterruptedException.wrapIfNeeded(exceptionToReport))).build();
}
}
use of javax.ws.rs.WebApplicationException in project druid by druid-io.
the class OverlordResource method securedTaskRunnerWorkItem.
private Collection<? extends TaskRunnerWorkItem> securedTaskRunnerWorkItem(Collection<? extends TaskRunnerWorkItem> collectionToFilter, HttpServletRequest req) {
final Map<Pair<Resource, Action>, Access> resourceAccessMap = new HashMap<>();
final AuthorizationInfo authorizationInfo = (AuthorizationInfo) req.getAttribute(AuthConfig.DRUID_AUTH_TOKEN);
return Collections2.filter(collectionToFilter, new Predicate<TaskRunnerWorkItem>() {
@Override
public boolean apply(TaskRunnerWorkItem input) {
final String taskId = input.getTaskId();
final Optional<Task> optionalTask = taskStorageQueryAdapter.getTask(taskId);
if (!optionalTask.isPresent()) {
throw new WebApplicationException(Response.serverError().entity(String.format("No task information found for task with id: [%s]", taskId)).build());
}
Resource resource = new Resource(optionalTask.get().getDataSource(), ResourceType.DATASOURCE);
Action action = Action.READ;
Pair<Resource, Action> key = new Pair<>(resource, action);
if (resourceAccessMap.containsKey(key)) {
return resourceAccessMap.get(key).isAllowed();
} else {
Access access = authorizationInfo.isAuthorized(key.lhs, key.rhs);
resourceAccessMap.put(key, access);
return access.isAllowed();
}
}
});
}
use of javax.ws.rs.WebApplicationException in project dropwizard by dropwizard.
the class AbstractParamConverterProvider method getConverter.
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
if (AbstractParam.class.isAssignableFrom(rawType)) {
final String parameterName = JerseyParameterNameProvider.getParameterNameFromAnnotations(annotations).orElse("Parameter");
final Constructor<T> constructor;
try {
constructor = rawType.getConstructor(String.class, String.class);
} catch (NoSuchMethodException ignored) {
// leaving Jersey to handle these parameters as it normally would.
return null;
}
return new ParamConverter<T>() {
@Override
@SuppressWarnings("unchecked")
public T fromString(String value) {
if (rawType != NonEmptyStringParam.class && Strings.isNullOrEmpty(value)) {
return null;
}
try {
return _fromString(value);
} catch (InvocationTargetException ex) {
final Throwable cause = ex.getCause();
if (cause instanceof WebApplicationException) {
throw (WebApplicationException) cause;
} else {
throw new ExtractorException(cause);
}
} catch (final Exception ex) {
throw new ProcessingException(ex);
}
}
protected T _fromString(String value) throws Exception {
return constructor.newInstance(value, parameterName);
}
@Override
public String toString(T value) throws IllegalArgumentException {
if (value == null) {
throw new IllegalArgumentException(LocalizationMessages.METHOD_PARAMETER_CANNOT_BE_NULL("value"));
}
return value.toString();
}
};
}
return null;
}
use of javax.ws.rs.WebApplicationException in project dropwizard by dropwizard.
the class DropwizardConfiguredValidator method getGroup.
/**
* If the request entity is annotated with {@link Validated} then run
* validations in the specified constraint group else validate with the
* {@link Default} group
*/
private Class<?>[] getGroup(Invocable invocable) {
final ImmutableList.Builder<Class<?>[]> builder = ImmutableList.builder();
for (Parameter parameter : invocable.getParameters()) {
if (parameter.isAnnotationPresent(Validated.class)) {
builder.add(parameter.getAnnotation(Validated.class).value());
}
}
final ImmutableList<Class<?>[]> groups = builder.build();
switch(groups.size()) {
// No parameters were annotated with Validated, so validate under the default group
case 0:
return new Class<?>[] { Default.class };
// A single parameter was annotated with Validated, so use their group
case 1:
return groups.get(0);
// group.
default:
for (int i = 0; i < groups.size(); i++) {
for (int j = i; j < groups.size(); j++) {
if (!Arrays.deepEquals(groups.get(i), groups.get(j))) {
throw new WebApplicationException("Parameters must have the same validation groups in " + invocable.getHandlingMethod().getName(), 500);
}
}
}
return groups.get(0);
}
}
Aggregations