use of javax.ws.rs.POST in project druid by druid-io.
the class LookupCoordinatorResource method createOrUpdateLookup.
@POST
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Path("/{tier}/{lookup}")
public Response createOrUpdateLookup(@PathParam("tier") String tier, @PathParam("lookup") String lookup, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, InputStream in, @Context HttpServletRequest req) {
try {
if (Strings.isNullOrEmpty(tier)) {
return Response.status(Response.Status.BAD_REQUEST).entity(ServletResourceUtils.sanitizeException(new NullPointerException("`tier` required"))).build();
}
if (Strings.isNullOrEmpty(lookup)) {
return Response.status(Response.Status.BAD_REQUEST).entity(ServletResourceUtils.sanitizeException(new IAE("`lookup` required"))).build();
}
final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(req.getContentType());
final ObjectMapper mapper = isSmile ? smileMapper : jsonMapper;
final Map<String, Object> lookupSpec;
try {
lookupSpec = mapper.readValue(in, new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(ServletResourceUtils.sanitizeException(e)).build();
}
if (lookupCoordinatorManager.updateLookup(tier, lookup, lookupSpec, new AuditInfo(author, comment, req.getRemoteAddr()))) {
return Response.status(Response.Status.ACCEPTED).build();
} else {
throw new RuntimeException("Unknown error updating configuration");
}
} catch (Exception e) {
LOG.error(e, "Error updating tier [%s] lookup [%s]", tier, lookup);
return Response.serverError().entity(ServletResourceUtils.sanitizeException(e)).build();
}
}
use of javax.ws.rs.POST in project druid by druid-io.
the class ListenerResource method serviceAnnouncementPOST.
@Path("/{id}")
@POST
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
public Response serviceAnnouncementPOST(@PathParam("id") final String id, final InputStream inputStream, // used only to get request content-type
@Context final HttpServletRequest req) {
if (Strings.isNullOrEmpty(id)) {
return makeNullIdResponse();
}
final String reqContentType = req.getContentType();
final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(reqContentType);
final ObjectMapper mapper = isSmile ? smileMapper : jsonMapper;
try {
return handler.handlePOST(inputStream, mapper, id);
} catch (Exception e) {
LOG.error(e, "Exception in handling POST request for ID [%s]", id);
return Response.serverError().entity(ServletResourceUtils.sanitizeException(e)).build();
}
}
use of javax.ws.rs.POST in project druid by druid-io.
the class LookupCoordinatorResource method updateAllLookups.
@POST
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
public Response updateAllLookups(InputStream in, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, @Context HttpServletRequest req) {
try {
final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(req.getContentType());
final ObjectMapper mapper = isSmile ? smileMapper : jsonMapper;
final Map<String, Map<String, Map<String, Object>>> map;
try {
map = mapper.readValue(in, new TypeReference<Map<String, Map<String, Map<String, Object>>>>() {
});
} catch (IOException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(ServletResourceUtils.sanitizeException(e)).build();
}
if (lookupCoordinatorManager.updateLookups(map, new AuditInfo(author, comment, req.getRemoteAddr()))) {
return Response.status(Response.Status.ACCEPTED).entity(map).build();
} else {
throw new RuntimeException("Unknown error updating configuration");
}
} catch (Exception e) {
LOG.error(e, "Error creating new lookups");
return Response.serverError().entity(ServletResourceUtils.sanitizeException(e)).build();
}
}
use of javax.ws.rs.POST in project druid by druid-io.
the class ResourceFilterTestHelper method getRequestPaths.
// Feeds in an array of [ PathName, MethodName, ResourceFilter , Injector]
public static Collection<Object[]> getRequestPaths(final Class clazz, final Iterable<Class<?>> mockableInjections, final Iterable<Key<?>> mockableKeys, final Iterable<?> injectedObjs) {
final Injector injector = Guice.createInjector(new Module() {
@Override
public void configure(Binder binder) {
for (Class clazz : mockableInjections) {
binder.bind(clazz).toInstance(EasyMock.createNiceMock(clazz));
}
for (Object obj : injectedObjs) {
binder.bind((Class) obj.getClass()).toInstance(obj);
}
for (Key<?> key : mockableKeys) {
binder.bind((Key<Object>) key).toInstance(EasyMock.createNiceMock(key.getTypeLiteral().getRawType()));
}
binder.bind(AuthConfig.class).toInstance(new AuthConfig(true));
}
});
//Ignore the first "/"
final String basepath = ((Path) clazz.getAnnotation(Path.class)).value().substring(1);
final List<Class<? extends ResourceFilter>> baseResourceFilters = clazz.getAnnotation(ResourceFilters.class) == null ? Collections.<Class<? extends ResourceFilter>>emptyList() : ImmutableList.copyOf(((ResourceFilters) clazz.getAnnotation(ResourceFilters.class)).value());
return ImmutableList.copyOf(Iterables.concat(// Step 3 - Merge all the Objects arrays for each endpoints
Iterables.transform(// - Resource Filter instance for the endpoint
Iterables.filter(// ResourceFilters applied to them
ImmutableList.copyOf(clazz.getDeclaredMethods()), new Predicate<Method>() {
@Override
public boolean apply(Method input) {
return input.getAnnotation(GET.class) != null || input.getAnnotation(POST.class) != null || input.getAnnotation(DELETE.class) != null && (input.getAnnotation(ResourceFilters.class) != null || !baseResourceFilters.isEmpty());
}
}), new Function<Method, Collection<Object[]>>() {
@Override
public Collection<Object[]> apply(final Method method) {
final List<Class<? extends ResourceFilter>> resourceFilters = method.getAnnotation(ResourceFilters.class) == null ? baseResourceFilters : ImmutableList.copyOf(method.getAnnotation(ResourceFilters.class).value());
return Collections2.transform(resourceFilters, new Function<Class<? extends ResourceFilter>, Object[]>() {
@Override
public Object[] apply(Class<? extends ResourceFilter> input) {
if (method.getAnnotation(Path.class) != null) {
return new Object[] { String.format("%s%s", basepath, method.getAnnotation(Path.class).value()), input.getAnnotation(GET.class) == null ? (method.getAnnotation(DELETE.class) == null ? "POST" : "DELETE") : "GET", injector.getInstance(input), injector };
} else {
return new Object[] { basepath, input.getAnnotation(GET.class) == null ? (method.getAnnotation(DELETE.class) == null ? "POST" : "DELETE") : "GET", injector.getInstance(input), injector };
}
}
});
}
})));
}
use of javax.ws.rs.POST 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();
}
}
Aggregations