use of io.micronaut.json.tree.JsonNode in project micronaut-core by micronaut-projects.
the class DigitalOceanMetadataResolver method resolve.
@Override
public Optional<ComputeInstanceMetadata> resolve(Environment environment) {
if (!configuration.isEnabled()) {
return Optional.empty();
}
if (cachedMetadata != null) {
cachedMetadata.setCached(true);
return Optional.of(cachedMetadata);
}
DigitalOceanInstanceMetadata instanceMetadata = new DigitalOceanInstanceMetadata();
try {
String metadataUrl = configuration.getUrl();
JsonNode metadataJson = readMetadataUrl(new URL(metadataUrl), CONNECTION_TIMEOUT_IN_MILLS, READ_TIMEOUT_IN_MILLS, JsonNodeTreeCodec.getInstance().withConfig(jsonStreamConfig), jsonFactory, new HashMap<>());
if (metadataJson != null) {
instanceMetadata.setInstanceId(textValue(metadataJson, DROPLET_ID));
instanceMetadata.setName(textValue(metadataJson, HOSTNAME));
instanceMetadata.setVendorData(textValue(metadataJson, VENDOR_DATA));
instanceMetadata.setUserData(textValue(metadataJson, USER_DATA));
instanceMetadata.setRegion(textValue(metadataJson, REGION));
JsonNode networkInterfaces = metadataJson.get(INTERFACES.getName());
List<NetworkInterface> privateInterfaces = processJsonInterfaces(networkInterfaces.get(PRIVATE_INTERFACES.getName()), instanceMetadata::setPrivateIpV4, instanceMetadata::setPrivateIpV6);
List<NetworkInterface> publicInterfaces = processJsonInterfaces(networkInterfaces.get(PUBLIC_INTERFACES.getName()), instanceMetadata::setPublicIpV4, instanceMetadata::setPublicIpV6);
List<NetworkInterface> allInterfaces = new ArrayList<>();
allInterfaces.addAll(publicInterfaces);
allInterfaces.addAll(privateInterfaces);
instanceMetadata.setInterfaces(allInterfaces);
populateMetadata(instanceMetadata, metadataJson);
cachedMetadata = instanceMetadata;
return Optional.of(instanceMetadata);
}
} catch (MalformedURLException mue) {
if (LOG.isErrorEnabled()) {
LOG.error("Digital Ocean metadataUrl value is invalid!: " + configuration.getUrl(), mue);
}
} catch (IOException ioe) {
if (LOG.isErrorEnabled()) {
LOG.error("Error connecting to" + configuration.getUrl() + "reading instance metadata", ioe);
}
}
return Optional.empty();
}
use of io.micronaut.json.tree.JsonNode in project micronaut-core by micronaut-projects.
the class JsonNodeConvertibleValues method get.
@Override
public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) {
String fieldName = name.toString();
JsonNode jsonNode = objectNode.get(fieldName);
if (jsonNode == null) {
return Optional.empty();
} else {
return conversionService.convert(jsonNode, conversionContext);
}
}
use of io.micronaut.json.tree.JsonNode in project micronaut-core by micronaut-projects.
the class JsonContentProcessor method doOnSubscribe.
@Override
protected void doOnSubscribe(Subscription subscription, Subscriber<? super JsonNode> subscriber) {
if (parentSubscription == null) {
return;
}
boolean streamArray = false;
boolean isJsonStream = nettyHttpRequest.getContentType().map(mediaType -> mediaType.equals(MediaType.APPLICATION_JSON_STREAM_TYPE)).orElse(false);
if (subscriber instanceof TypedSubscriber) {
TypedSubscriber typedSubscriber = (TypedSubscriber) subscriber;
Argument typeArgument = typedSubscriber.getTypeArgument();
Class targetType = typeArgument.getType();
if (Publishers.isConvertibleToPublisher(targetType) && !Publishers.isSingle(targetType)) {
Optional<Argument<?>> genericArgument = typeArgument.getFirstTypeVariable();
if (genericArgument.isPresent() && !Iterable.class.isAssignableFrom(genericArgument.get().getType()) && !isJsonStream) {
// if the generic argument is not a iterable type them stream the array into the publisher
streamArray = true;
}
}
}
this.jacksonProcessor = jsonMapper.createReactiveParser(p -> {
}, streamArray);
this.jacksonProcessor.subscribe(new CompletionAwareSubscriber<JsonNode>() {
@Override
protected void doOnSubscribe(Subscription jsonSubscription) {
Subscription childSubscription = new Subscription() {
boolean first = true;
@Override
public synchronized void request(long n) {
// find a better way in the future
if (first) {
jsonSubscription.request(n < Long.MAX_VALUE ? n + 1 : n);
parentSubscription.request(n < Long.MAX_VALUE ? n + 1 : n);
} else {
jsonSubscription.request(n);
parentSubscription.request(n);
}
}
@Override
public synchronized void cancel() {
jsonSubscription.cancel();
parentSubscription.cancel();
}
};
subscriber.onSubscribe(childSubscription);
}
@Override
protected void doOnNext(JsonNode message) {
subscriber.onNext(message);
}
@Override
protected void doOnError(Throwable t) {
subscriber.onError(t);
}
@Override
protected void doOnComplete() {
subscriber.onComplete();
}
});
jacksonProcessor.onSubscribe(subscription);
}
use of io.micronaut.json.tree.JsonNode in project micronaut-core by micronaut-projects.
the class DigitalOceanMetadataResolver method processJsonInterfaces.
private List<NetworkInterface> processJsonInterfaces(JsonNode interfaces, Consumer<String> ipv4Setter, Consumer<String> ipv6Setter) {
List<NetworkInterface> networkInterfaces = new ArrayList<>();
if (interfaces != null) {
AtomicReference<Integer> networkCounter = new AtomicReference<>(0);
interfaces.values().forEach(jsonNode -> {
DigitalOceanNetworkInterface networkInterface = new DigitalOceanNetworkInterface();
networkInterface.setId(networkCounter.toString());
JsonNode ipv4 = jsonNode.get(IPV4.getName());
if (ipv4 != null) {
networkInterface.setIpv4(textValue(ipv4, IP_ADDRESS));
networkInterface.setNetmask(textValue(ipv4, NETMASK));
networkInterface.setGateway(textValue(ipv4, GATEWAY));
}
JsonNode ipv6 = jsonNode.get(IPV6.getName());
if (ipv6 != null) {
networkInterface.setIpv6(textValue(ipv6, IP_ADDRESS));
networkInterface.setIpv6Gateway(textValue(ipv6, GATEWAY));
networkInterface.setCidr(ipv6.get(CIDR.getName()).getIntValue());
}
networkInterface.setMac(textValue(jsonNode, MAC));
networkCounter.getAndSet(networkCounter.get() + 1);
networkInterfaces.add(networkInterface);
});
JsonNode firstIpv4 = interfaces.get(0).get(IPV4.getName());
ipv4Setter.accept(textValue(firstIpv4, IP_ADDRESS));
JsonNode firstIpv6 = interfaces.get(0).get(IPV6.getName());
if (firstIpv6 != null) {
ipv6Setter.accept(textValue(firstIpv6, IP_ADDRESS));
}
}
return networkInterfaces;
}
use of io.micronaut.json.tree.JsonNode in project micronaut-core by micronaut-projects.
the class DefaultHttpClient method buildJsonStreamPublisher.
/**
* @param parentRequest The parent request
* @param request The request
* @param type The type
* @param errorType The error type
* @param <I> The input type
* @param <O> The output type
* @return A {@link Function}
*/
protected <I, O> Function<URI, Publisher<O>> buildJsonStreamPublisher(io.micronaut.http.HttpRequest<?> parentRequest, io.micronaut.http.HttpRequest<I> request, io.micronaut.core.type.Argument<O> type, io.micronaut.core.type.Argument<?> errorType) {
return requestURI -> {
Flux<io.micronaut.http.HttpResponse<Object>> streamResponsePublisher = Flux.from(buildStreamExchange(parentRequest, request, requestURI, errorType));
return streamResponsePublisher.switchMap(response -> {
if (!(response instanceof NettyStreamedHttpResponse)) {
throw new IllegalStateException("Response has been wrapped in non streaming type. Do not wrap the response in client filters for stream requests");
}
MapperMediaTypeCodec mediaTypeCodec = (MapperMediaTypeCodec) mediaTypeCodecRegistry.findCodec(MediaType.APPLICATION_JSON_TYPE).orElseThrow(() -> new IllegalStateException("No JSON codec found"));
StreamedHttpResponse streamResponse = NettyHttpResponseBuilder.toStreamResponse(response);
Flux<HttpContent> httpContentReactiveSequence = Flux.from(streamResponse);
boolean isJsonStream = response.getContentType().map(mediaType -> mediaType.equals(MediaType.APPLICATION_JSON_STREAM_TYPE)).orElse(false);
boolean streamArray = !Iterable.class.isAssignableFrom(type.getType()) && !isJsonStream;
Processor<byte[], JsonNode> jsonProcessor = mediaTypeCodec.getJsonMapper().createReactiveParser(p -> {
httpContentReactiveSequence.map(content -> {
ByteBuf chunk = content.content();
if (log.isTraceEnabled()) {
log.trace("HTTP Client Streaming Response Received Chunk (length: {}) for Request: {} {}", chunk.readableBytes(), request.getMethodName(), request.getUri());
traceBody("Chunk", chunk);
}
try {
return ByteBufUtil.getBytes(chunk);
} finally {
chunk.release();
}
}).subscribe(p);
}, streamArray);
return Flux.from(jsonProcessor).map(jsonNode -> mediaTypeCodec.decode(type, jsonNode));
}).doOnTerminate(() -> {
final Object o = request.getAttribute(NettyClientHttpRequest.CHANNEL).orElse(null);
if (o instanceof Channel) {
final Channel c = (Channel) o;
if (c.isOpen()) {
c.close();
}
}
});
};
}
Aggregations