Search in sources :

Example 11 with WebApplicationException

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;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Access(io.druid.server.security.Access) Resource(io.druid.server.security.Resource) PathSegment(javax.ws.rs.core.PathSegment) AuthorizationInfo(io.druid.server.security.AuthorizationInfo) Predicate(com.google.common.base.Predicate)

Example 12 with WebApplicationException

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();
    }
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) DateTimeZone(org.joda.time.DateTimeZone) QueryInterruptedException(io.druid.query.QueryInterruptedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) DruidPlanner(io.druid.sql.calcite.planner.DruidPlanner) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ISE(io.druid.java.util.common.ISE) PlannerResult(io.druid.sql.calcite.planner.PlannerResult) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 13 with WebApplicationException

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();
            }
        }
    });
}
Also used : Action(io.druid.server.security.Action) TaskRunnerWorkItem(io.druid.indexing.overlord.TaskRunnerWorkItem) Optional(com.google.common.base.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Access(io.druid.server.security.Access) Resource(io.druid.server.security.Resource) AuthorizationInfo(io.druid.server.security.AuthorizationInfo) Pair(io.druid.java.util.common.Pair)

Example 14 with WebApplicationException

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;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ParamConverter(javax.ws.rs.ext.ParamConverter) InvocationTargetException(java.lang.reflect.InvocationTargetException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ExtractorException(org.glassfish.jersey.internal.inject.ExtractorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExtractorException(org.glassfish.jersey.internal.inject.ExtractorException) ProcessingException(javax.ws.rs.ProcessingException)

Example 15 with WebApplicationException

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);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ImmutableList(com.google.common.collect.ImmutableList) Parameter(org.glassfish.jersey.server.model.Parameter) Default(javax.validation.groups.Default)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)276 Produces (javax.ws.rs.Produces)77 GET (javax.ws.rs.GET)71 Path (javax.ws.rs.Path)69 IOException (java.io.IOException)47 POST (javax.ws.rs.POST)47 Consumes (javax.ws.rs.Consumes)44 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)43 Response (javax.ws.rs.core.Response)30 MediaType (javax.ws.rs.core.MediaType)26 URI (java.net.URI)25 HashMap (java.util.HashMap)20 JSONObject (org.codehaus.jettison.json.JSONObject)20 Test (org.junit.Test)19 JSONException (org.codehaus.jettison.json.JSONException)18 ApiOperation (io.swagger.annotations.ApiOperation)17 ArrayList (java.util.ArrayList)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)15 List (java.util.List)14