use of com.fasterxml.jackson.databind.JavaType in project druid by druid-io.
the class DirectDruidClient method run.
@Override
public Sequence<T> run(final Query<T> query, final Map<String, Object> context) {
QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query);
boolean isBySegment = BaseQuery.getContextBySegment(query, false);
Pair<JavaType, JavaType> types = typesMap.get(query.getClass());
if (types == null) {
final TypeFactory typeFactory = objectMapper.getTypeFactory();
JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference());
JavaType bySegmentType = typeFactory.constructParametricType(Result.class, typeFactory.constructParametricType(BySegmentResultValueClass.class, baseType));
types = Pair.of(baseType, bySegmentType);
typesMap.put(query.getClass(), types);
}
final JavaType typeRef;
if (isBySegment) {
typeRef = types.rhs;
} else {
typeRef = types.lhs;
}
final ListenableFuture<InputStream> future;
final String url = String.format("http://%s/druid/v2/", host);
final String cancelUrl = String.format("http://%s/druid/v2/%s", host, query.getId());
try {
log.debug("Querying queryId[%s] url[%s]", query.getId(), url);
final long requestStartTime = System.currentTimeMillis();
final ServiceMetricEvent.Builder builder = toolChest.makeMetricBuilder(query);
builder.setDimension("server", host);
final HttpResponseHandler<InputStream, InputStream> responseHandler = new HttpResponseHandler<InputStream, InputStream>() {
private long responseStartTime;
private final AtomicLong byteCount = new AtomicLong(0);
private final BlockingQueue<InputStream> queue = new LinkedBlockingQueue<>();
private final AtomicBoolean done = new AtomicBoolean(false);
@Override
public ClientResponse<InputStream> handleResponse(HttpResponse response) {
log.debug("Initial response from url[%s] for queryId[%s]", url, query.getId());
responseStartTime = System.currentTimeMillis();
emitter.emit(builder.build("query/node/ttfb", responseStartTime - requestStartTime));
try {
final String responseContext = response.headers().get("X-Druid-Response-Context");
// context may be null in case of error or query timeout
if (responseContext != null) {
context.putAll(objectMapper.<Map<String, Object>>readValue(responseContext, new TypeReference<Map<String, Object>>() {
}));
}
queue.put(new ChannelBufferInputStream(response.getContent()));
} catch (final IOException e) {
log.error(e, "Error parsing response context from url [%s]", url);
return ClientResponse.<InputStream>finished(new InputStream() {
@Override
public int read() throws IOException {
throw e;
}
});
} catch (InterruptedException e) {
log.error(e, "Queue appending interrupted");
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
}
byteCount.addAndGet(response.getContent().readableBytes());
return ClientResponse.<InputStream>finished(new SequenceInputStream(new Enumeration<InputStream>() {
@Override
public boolean hasMoreElements() {
// Then the stream should be spouting good InputStreams.
synchronized (done) {
return !done.get() || !queue.isEmpty();
}
}
@Override
public InputStream nextElement() {
try {
return queue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
}
}
}));
}
@Override
public ClientResponse<InputStream> handleChunk(ClientResponse<InputStream> clientResponse, HttpChunk chunk) {
final ChannelBuffer channelBuffer = chunk.getContent();
final int bytes = channelBuffer.readableBytes();
if (bytes > 0) {
try {
queue.put(new ChannelBufferInputStream(channelBuffer));
} catch (InterruptedException e) {
log.error(e, "Unable to put finalizing input stream into Sequence queue for url [%s]", url);
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
}
byteCount.addAndGet(bytes);
}
return clientResponse;
}
@Override
public ClientResponse<InputStream> done(ClientResponse<InputStream> clientResponse) {
long stopTime = System.currentTimeMillis();
log.debug("Completed queryId[%s] request to url[%s] with %,d bytes returned in %,d millis [%,f b/s].", query.getId(), url, byteCount.get(), stopTime - responseStartTime, byteCount.get() / (0.0001 * (stopTime - responseStartTime)));
emitter.emit(builder.build("query/node/time", stopTime - requestStartTime));
emitter.emit(builder.build("query/node/bytes", byteCount.get()));
synchronized (done) {
try {
// An empty byte array is put at the end to give the SequenceInputStream.close() as something to close out
// after done is set to true, regardless of the rest of the stream's state.
queue.put(ByteSource.empty().openStream());
} catch (InterruptedException e) {
log.error(e, "Unable to put finalizing input stream into Sequence queue for url [%s]", url);
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
} catch (IOException e) {
// This should never happen
throw Throwables.propagate(e);
} finally {
done.set(true);
}
}
return ClientResponse.<InputStream>finished(clientResponse.getObj());
}
@Override
public void exceptionCaught(final ClientResponse<InputStream> clientResponse, final Throwable e) {
// Don't wait for lock in case the lock had something to do with the error
synchronized (done) {
done.set(true);
// Make a best effort to put a zero length buffer into the queue in case something is waiting on the take()
// If nothing is waiting on take(), this will be closed out anyways.
queue.offer(new InputStream() {
@Override
public int read() throws IOException {
throw new IOException(e);
}
});
}
}
};
future = httpClient.go(new Request(HttpMethod.POST, new URL(url)).setContent(objectMapper.writeValueAsBytes(query)).setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? SmileMediaTypes.APPLICATION_JACKSON_SMILE : MediaType.APPLICATION_JSON), responseHandler);
queryWatcher.registerQuery(query, future);
openConnections.getAndIncrement();
Futures.addCallback(future, new FutureCallback<InputStream>() {
@Override
public void onSuccess(InputStream result) {
openConnections.getAndDecrement();
}
@Override
public void onFailure(Throwable t) {
openConnections.getAndDecrement();
if (future.isCancelled()) {
// forward the cancellation to underlying queriable node
try {
StatusResponseHolder res = httpClient.go(new Request(HttpMethod.DELETE, new URL(cancelUrl)).setContent(objectMapper.writeValueAsBytes(query)).setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? SmileMediaTypes.APPLICATION_JACKSON_SMILE : MediaType.APPLICATION_JSON), new StatusResponseHandler(Charsets.UTF_8)).get();
if (res.getStatus().getCode() >= 500) {
throw new RE("Error cancelling query[%s]: queriable node returned status[%d] [%s].", res.getStatus().getCode(), res.getStatus().getReasonPhrase());
}
} catch (IOException | ExecutionException | InterruptedException e) {
Throwables.propagate(e);
}
}
}
});
} catch (IOException e) {
throw Throwables.propagate(e);
}
Sequence<T> retVal = new BaseSequence<>(new BaseSequence.IteratorMaker<T, JsonParserIterator<T>>() {
@Override
public JsonParserIterator<T> make() {
return new JsonParserIterator<T>(typeRef, future, url);
}
@Override
public void cleanup(JsonParserIterator<T> iterFromMake) {
CloseQuietly.close(iterFromMake);
}
});
// avoid the cost of de-serializing and then re-serializing again when adding to cache
if (!isBySegment) {
retVal = Sequences.map(retVal, toolChest.makePreComputeManipulatorFn(query, MetricManipulatorFns.deserializing()));
}
return retVal;
}
use of com.fasterxml.jackson.databind.JavaType in project java-chassis by ServiceComb.
the class ClassUtils method getOrCreateClass.
// 获取modelImpl对应的class
public static Class<?> getOrCreateClass(ClassLoader classLoader, String packageName, Swagger swagger, ModelImpl modelImpl, String clsName) {
Class<?> cls = getClassByName(classLoader, clsName);
if (cls != null) {
return cls;
}
ClassConfig classConfig = new ClassConfig();
classConfig.setClassName(clsName);
for (Entry<String, Property> entry : modelImpl.getProperties().entrySet()) {
JavaType propertyJavaType = ConverterMgr.findJavaType(classLoader, packageName, swagger, entry.getValue());
classConfig.addField(entry.getKey(), propertyJavaType);
}
cls = JavassistUtils.createClass(classConfig);
return cls;
}
use of com.fasterxml.jackson.databind.JavaType in project java-chassis by ServiceComb.
the class ClassUtils method createInterface.
private static Class<?> createInterface(Swagger swagger, ClassLoader classLoader, String packageName, String intfName) {
ClassConfig classConfig = new ClassConfig();
classConfig.setClassName(intfName);
classConfig.setIntf(true);
StringBuilder sbMethod = new StringBuilder();
StringBuilder sbMethodGenericSignature = new StringBuilder();
for (Path path : swagger.getPaths().values()) {
for (Operation operation : path.getOperations()) {
boolean hasGenericSignature = false;
sbMethod.setLength(0);
sbMethodGenericSignature.setLength(0);
Response result = operation.getResponses().get(SwaggerConst.SUCCESS_KEY);
JavaType resultJavaType = ConverterMgr.findJavaType(classLoader, packageName, swagger, result.getSchema());
hasGenericSignature = hasGenericSignature || resultJavaType.hasGenericTypes();
sbMethod.append(JavassistUtils.getNameForGenerateCode(resultJavaType)).append(" ").append(operation.getOperationId()).append("(");
sbMethodGenericSignature.append("(");
for (Parameter parameter : operation.getParameters()) {
String paramName = parameter.getName();
paramName = correctMethodParameterName(paramName);
JavaType paramJavaType = ConverterMgr.findJavaType(classLoader, packageName, swagger, parameter);
hasGenericSignature = hasGenericSignature || paramJavaType.hasGenericTypes();
String code = String.format("%s %s,", paramJavaType.getRawClass().getName(), paramName);
sbMethod.append(code);
sbMethodGenericSignature.append(paramJavaType.getGenericSignature());
}
if (!operation.getParameters().isEmpty()) {
sbMethod.setLength(sbMethod.length() - 1);
}
sbMethod.append(");");
sbMethodGenericSignature.append(")");
sbMethodGenericSignature.append(resultJavaType.getGenericSignature());
if (hasGenericSignature) {
classConfig.addMethod(sbMethod.toString(), sbMethodGenericSignature.toString());
} else {
classConfig.addMethod(sbMethod.toString(), null);
}
}
}
return JavassistUtils.createClass(classLoader, classConfig);
}
use of com.fasterxml.jackson.databind.JavaType in project java-chassis by ServiceComb.
the class ClassUtils method getOrCreateBodyClass.
// 将一系列body parameter包装成一个class
public static Class<?> getOrCreateBodyClass(OperationGenerator operationGenerator, List<BodyParameter> bodyParameters) {
SwaggerGenerator swaggerGenerator = operationGenerator.getSwaggerGenerator();
Method method = operationGenerator.getProviderMethod();
String clsName = swaggerGenerator.ensureGetPackageName() + "." + method.getName() + "Body";
Class<?> cls = getClassByName(swaggerGenerator.getClassLoader(), clsName);
if (cls != null) {
return cls;
}
ClassConfig classConfig = new ClassConfig();
classConfig.setClassName(clsName);
// 2.预备body与明确body混合
for (BodyParameter bp : bodyParameters) {
JavaType javaType = ConverterMgr.findJavaType(swaggerGenerator.getClassLoader(), swaggerGenerator.ensureGetPackageName(), swaggerGenerator.getSwagger(), bp);
classConfig.addField(bp.getName(), javaType);
}
return JavassistUtils.createClass(classConfig);
}
use of com.fasterxml.jackson.databind.JavaType in project java-chassis by ServiceComb.
the class TestSwaggerUtils method testConverter.
@Test
public void testConverter() {
SwaggerGenerator generator = new SwaggerGeneratorForTest(context, null);
Swagger swagger = generator.getSwagger();
ParamUtils.addDefinitions(swagger, User.class);
Model model = swagger.getDefinitions().get("User");
model.getVendorExtensions().clear();
JavaType javaType = ConverterMgr.findJavaType(generator, model);
checkJavaType(swagger, javaType);
RefModel refModel = new RefModel();
refModel.setReference("User");
javaType = ConverterMgr.findJavaType(generator, refModel);
checkJavaType(swagger, javaType);
}
Aggregations