use of javax.ws.rs.WebApplicationException in project jersey by jersey.
the class AccessTokenResource method postAccessTokenRequest.
/**
* POST method for creating a request for Request Token.
* @return an HTTP response with content of the updated or created resource.
*/
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@TokenResource
public Response postAccessTokenRequest(@Context ContainerRequestContext requestContext, @Context Request req) {
boolean sigIsOk = false;
OAuthServerRequest request = new OAuthServerRequest(requestContext);
OAuth1Parameters params = new OAuth1Parameters();
params.readRequest(request);
if (params.getToken() == null) {
throw new WebApplicationException(new Throwable("oauth_token MUST be present."), 400);
}
String consKey = params.getConsumerKey();
if (consKey == null) {
throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
}
OAuth1Token rt = provider.getRequestToken(params.getToken());
if (rt == null) {
// token invalid
throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
}
OAuth1Consumer consumer = rt.getConsumer();
if (consumer == null || !consKey.equals(consumer.getKey())) {
// token invalid
throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
}
OAuth1Secrets secrets = new OAuth1Secrets().consumerSecret(consumer.getSecret()).tokenSecret(rt.getSecret());
try {
sigIsOk = oAuth1Signature.verify(request, params, secrets);
} catch (OAuth1SignatureException ex) {
Logger.getLogger(AccessTokenResource.class.getName()).log(Level.SEVERE, null, ex);
}
if (!sigIsOk) {
// signature invalid
throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
}
// We're good to go.
OAuth1Token at = provider.newAccessToken(rt, params.getVerifier());
if (at == null) {
throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
}
// Preparing the response.
Form resp = new Form();
resp.param(OAuth1Parameters.TOKEN, at.getToken());
resp.param(OAuth1Parameters.TOKEN_SECRET, at.getSecret());
resp.asMap().putAll(at.getAttributes());
return Response.ok(resp).build();
}
use of javax.ws.rs.WebApplicationException in project jersey by jersey.
the class MessageBodyReaderTestFormat method readFrom.
@Override
public Message readFrom(final Class<Message> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, MessageUtils.getCharset(mediaType)));
final String line = reader.readLine();
if (line == null || !line.startsWith(Utils.FORMAT_PREFIX) || !line.endsWith(Utils.FORMAT_SUFFIX)) {
throw new WebApplicationException(new IllegalArgumentException("Input content '" + line + "' is not in a valid format!"));
}
final String text = line.substring(Utils.FORMAT_PREFIX.length(), line.length() - Utils.FORMAT_SUFFIX.length());
if (serverSide) {
Utils.throwException(text, this, Utils.TestAction.MESSAGE_BODY_READER_THROW_WEB_APPLICATION, Utils.TestAction.MESSAGE_BODY_READER_THROW_PROCESSING, Utils.TestAction.MESSAGE_BODY_READER_THROW_ANY);
}
return new Message(text);
}
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 ConfigResourceFilter 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 resourceName = "CONFIG";
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(resourceName, ResourceType.CONFIG), 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 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;
}
Aggregations