Integrating Spring-Shell with the MongoDb driver - mongodb

Is it me, or are the MongoDb drivers and Spring-Shell deeply incompatible? To start, I'm not talking about the Spring-Data-Mongo stuff, I'm talking about the actual java client that the MongoDb folks put out.
My Pom is as follows:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell-starter</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.11.0</version>
</dependency>
</dependencies>
If I try to use the MongoDb client from the Spring shell, I consistenty get noclassdeffound errors all over the place. A simplified bare bones shell method is as follows:
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import java.util.Date;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
#ShellComponent
public class AuditCommands {
#ShellMethod("Just testing here")
public int cube(int number)
{
return number*number*number;
}
#ShellMethod("Sends a test document to mongo")
public void mgo()
{
System.out.println("Hello there. Doing some mongo stuff");
//MongoClient mongoClient = MongoClients.create();
MongoClient mongoClient = MongoClients.create("mongodb://whateversite:12345");
// New up a registry to automatically handle pojos
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
// Grep database instance
MongoDatabase database = mongoClient.getDatabase("MyDb");
database = database.withCodecRegistry(pojoCodecRegistry);
MongoCollection<Audit> collection = database.getCollection("MyCollection", Audit.class);
Audit audit = new Audit();
audit.setAuditId(1);
audit.setAuditTypeId(5);
audit.setCreatedOn(new Date());
audit.setMessage("Making mongo great again..");
collection.insertOne(audit);
System.out.println("Done..!!..");
}
}
I receive the following error if I try to execute the "mgo" ShellMethod in my example I get the following error.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-02 18:10:54.634 ERROR 18848 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
com.mongodb.client.internal.MongoClientImpl.<init>(MongoClientImpl.java:67)
The following method did not exist:
com.mongodb.MongoClientSettings.getAutoEncryptionSettings()Lcom/mongodb/AutoEncryptionSettings;
The method's class, com.mongodb.MongoClientSettings, is available from the following locations:
jar:file:/C:/Users/xxxxx/.m2/repository/org/mongodb/mongodb-driver-core/3.8.2/mongodb-driver-core-3.8.2.jar!/com/mongodb/MongoClientSettings.class
It was loaded from the following location:
file:/C:/Users/xxxxx/.m2/repository/org/mongodb/mongodb-driver-core/3.8.2/mongodb-driver-core-3.8.2.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of com.mongodb.MongoClientSettings
Process finished with exit code 1
If I remove Spring-Shell and Spring-Boot, that MongoDb code works fine.
So what gives here? Am I missing some essential point here or is this stuff essentially broken? I'm not a Java/Spring native, so I'm sure it won't come as a surprise when I say that connecting to Mongo and throwing a couple of documents around comes off muuuuuuch cleaner in C#, Python, and node. (And yes I know I can use spring-data-mongo, but that just seems like a really opinionated API for someone coming from a different language background)

Okay, I'm going to answer my own question here because I've learned a little more about this.
I wound up giving up on trying to make spring boot exclude all the mongodb dependencies that I didn't want and didn't ask for. So this wasn't really a spring-shell issue. I wound up just matching the version of the driver that spring boot is using in my own pom.
As in..
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.2</version>
</dependency>
Once you do that, you get a bunch "connecting to localhost:27017...." issues. You can fix this by excluding the ludicrous MongoAutoConfigure that spring defaults to. More specifically, you have to go with a parameterized SpringBootApplication annotation like this:
#SpringBootApplication(exclude = MongoAutoConfiguration.class)
public class Main {
public static void main(String[] args)
{
SpringApplication.run(Main.class);
}
}
As I mentioned earlier, I'm not a Java native, so my opinions are heavily flavored by the frameworks I grew up on. But.. The idea that spring just automatically tries to connect to a potentially networked resource is completely asinine to me. It's one thing if I'm actually trying to use spring-mongodb and it's super opinionated pattern, but I'm not in my case. The equivalent would be if I pulled the Dapper assemblies from NuGet and they tried to log into the nearest local instance of sql server just for the heck of it. Very sketchy value proposition at best, and surface area for some sort of creative exploit at worst. I just don't see what "I" get out of this behavior.

Related

Dynamic destination in Spring Cloud Stream from Azure Event Hub to Kafka

I'm trying to use Spring Cloud Stream to process messages sent to an Azure Event Hub instance. Those messages should be routed to a tenant-specific topic determined at runtime, based on message content, on a Kafka cluster. For development purposes, I'm running Kafka locally via Docker.
I've done some research about bindings not known at configuration time and have found that dynamic destination resolution might be exactly what I need for this scenario.
However, the only way to get my solution working is to use StreamBridge. I would rather use the dynamic destination header spring.cloud.stream.sendto.destination, in that way the processor could be written as a Function<> instead of a Consumer<> (it is not properly a sink). The main concern about this approach is that, since the final solution will be deployed with Spring Data Flow, I'm afraid I will have troubles configuring the streams if using StreamBridge.
Moving on to the code, this is the processor function, I stripped away the unrelated parts
private static final String OUTPUT_DESTINATION_TEMPLATE = "%s.gateway-report";
private static final String STREAM_DESTINATION_HEADER = "spring.cloud.stream.sendto.destination";
private static final String TENANT_ID_HEADER = "tenant-id";
#Bean
public Function<Message<String>, Message<String>>
routeMessageToTenantDestination(TenantGatewayDeviceService gatewayDeviceService) {
return msg -> {
final String tenantId = "test";
final String destination = String.format(OUTPUT_DESTINATION_TEMPLATE, tenantId);
return MessageBuilder.withPayload(msg.getPayload())
.setHeader(STREAM_DESTINATION_HEADER, destination)
.setHeader(TENANT_ID_HEADER, tenantId)
.build();
};
}
and this is my application.yml
spring:
cloud:
stream:
bindings:
routeMessageToTenantDestination-in-0:
binder: kafka-evthub
destination: gateway-report
group: report-processor
dynamic-destinations:
binders:
kafka-ioc:
type: kafka
environment:
spring.cloud.stream.kafka.binder:
brokers: localhost:29092
kafka-evthub:
type: kafka
environment:
spring.cloud.stream.kafka.binder:
brokers: xxxxxxxxxxx.servicebus.windows.net:9093
configuration:
sasl:
jaas:
config: org.apache.kafka.common.security.plain.PlainLoginModule required username="$ConnectionString" password="Endpoint=sb://xxxxxxxxxxx.servicebus.windows.net/;SharedAccessKeyName=*******;SharedAccessKey=********";
mechanism: PLAIN
security.protocol: SASL_SSL
default-binder: kafka-ioc
My relevant dependencies in pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
This is the exception I get each time the function fires
2022-01-20 10:56:18.848 ERROR 2258917 --- [container-0-C-1] o.s.integration.handler.LoggingHandler : org.springframework.messaging.MessageHandlingException: error occurred in message handler [... stripped away ...]
at org.springframework.integration.support.utils.IntegrationUtils.wrapInHandlingExceptionIfNecessary(IntegrationUtils.java:191)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:65)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:133)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:72)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:317)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:272)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:208)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.sendMessageIfAny(KafkaMessageDrivenChannelAdapter.java:385)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.access$300(KafkaMessageDrivenChannelAdapter.java:79)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:442)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:416)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.lambda$onMessage$0(RetryingMessageListenerAdapter.java:125)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:329)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:255)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.onMessage(RetryingMessageListenerAdapter.java:119)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.onMessage(RetryingMessageListenerAdapter.java:42)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeOnMessage(KafkaMessageListenerContainer.java:2588)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeOnMessage(KafkaMessageListenerContainer.java:2569)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeRecordListener(KafkaMessageListenerContainer.java:2483)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeWithRecords(KafkaMessageListenerContainer.java:2405)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:2284)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:1958)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeIfHaveRecords(KafkaMessageListenerContainer.java:1353)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:1344)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:1236)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.NullPointerException
at org.springframework.cloud.stream.function.StreamBridge.resolveDestination(StreamBridge.java:276)
at org.springframework.cloud.stream.function.FunctionConfiguration$FunctionToDestinationBinder$1.doSendMessage(FunctionConfiguration.java:604)
at org.springframework.cloud.stream.function.FunctionConfiguration$FunctionToDestinationBinder$1.handleMessageInternal(FunctionConfiguration.java:597)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:56)
... 32 more
I've tried different things, f.i. manually creating the destination topic, configuring an explicit destination binding with the same name assigned to the header (not a definitive solution, just for testing), but I keep getting this exception. I've also tried to provide a NewDestinationBindingCallback<> and I can see from printing a log that the framework enters the method, but nevertheless I keep getting the same error.
This happens also with the other approach for integrating Spring Cloud Stream with Event Hubs, namely the library azure-spring-cloud-stream-binder-eventhubs.
As I said previously, I've found a workaround in relying to StreamBridge, but this solution seems less desirable to me and I would like to understand what I'm missing.
EDIT: I made a small step forward and managed to make it work by downgrading spring boot starter version from 2.6.2 to 2.4.4
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
and setting
<properties>
<spring-cloud.version>2020.0.2</spring-cloud.version>
</properties>
instead of 2021.0.0 in pom.xml, as found in the sample provided by sobychacko. However, it seems like a regression, or something is missing in my configuration to make this work with the most recent version?
Not sure what exactly is causing the issues you have. I just created a basic sample app demonstrating the sendto.destination header and verified that the app works as expected. It is a multi-binder application with two Kafka clusters connected. The function will consume from the first cluster and then using the sendto header, produce the output to the second cluster. Compare the code/config in this sample with your app and see what is missing.
I see references to StreamBridge in the stacktrace you shared. However, when using the sendto.destination header, it shouldn't go through StreamBridge.

Using Spring Boot auto configuration of MongoDB with Camel, how to know what application.properties

I'm trying to add a Camel rout to a working project with Spring Boot for using MongoDB. I've using Mongo with Spring Boot autoconfigure, and it worked pretty easily.
I was confused about how to specify the bean that Spring Boot generates, but I finally found an answer to a related question on SO that said the name of the bean is "mongo". So I changed my rout to .to("mongodb:mongo?....
No Spring is trying to connect to default parameters, localhost and 72017, etc. So how do I figure out what properties to specify in application.properties to set the connection parameters? The documentation isn't being helpful here.
{Edit: I managed to figure this out. The below works now}
Here are the Maven dependencies I added:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-mongodb</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-mongodb-starter</artifactId>
<version>${camel-version}</version>
</dependency>
And here are the additions to my application.properties file
spring.data.mongodb.host=<IP>
spring.data.mongodb.port=27017
spring.data.mongodb.database=dev
spring.data.mongodb.username=test
spring.data.mongodb.password=password
And the Camel route:
package Order;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
#Component
public class OrderRouter extends RouteBuilder {
#Override
public void configure() {
// Process message
from("jms:topic:order")
.log("JMS Message: ${body}")
.choice()
.when().jsonpath("$.[?(#.type=='partial')]")
.to("mongodb:mongo?database=dev&collection=order&operation=insert");
}
}
Does this mean I need to define a bean when connecting with Camel? Looking at the documentation it seems that it should generate a bean by adding camel-mongodb-starter along with the application.properteis
https://camel.apache.org/components/latest/mongodb-component.html#_spring_boot_auto_configuration
I found the spring bean name, but only by looking around for examples...
spring.data.mongodb

Spring Cloud Stream unable to detect message router

I'm trying to set up a simple cloud stream Sink but keep running into the following errors.
I've tried several binders and they all keep giving the same error.
"SEVERE","logNameSource":"org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter","message":"
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method binderAwareRouterBeanPostProcessor in org.springframework.cloud.stream.config.BindingServiceConfiguration required a bean of type '[ Lorg.springframework.integration.router.AbstractMappingMessageRouter;' that could not be found.
Action:
Consider defining a bean of type '[ Lorg.springframework.integration.router.AbstractMappingMessageRouter;' in your configuration.
I'm trying to use a simple Sink to log an incoming message from a kafka topic
#EnableBinding(Sink.class)
public class ReadEMPMesage {
private static Logger logger =
LoggerFactory.getLogger(ReadEMPMesage.class);
public ReadEMPMesage() {
System.out.println("In constructor");
}
#StreamListener(Sink.INPUT)
public void loggerSink(String ccpEvent) {
logger.info("Received" + ccpEvent);
}
}
and my configuration is as follows
# Test consumer properties
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.group-id=testEmbeddedKafkaApplication
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.ByteArrayDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.ByteArrayDeserializer
# Binding properties
spring.cloud.stream.bindings.output.destination=testEmbeddedOut
spring.cloud.stream.bindings.input.destination=testEmbeddedIn
spring.cloud.stream.bindings.output.producer.headerMode=raw
spring.cloud.stream.bindings.input.consumer.headerMode=raw
spring.cloud.stream.bindings.input.group=embeddedKafkaApplication
and my pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
TL;DR - check your version of Spring Boot and try upgrading it a few minor revs.
I ran into this problem on a project after upgrading from Spring Cloud DALSTON.RELEASE to Spring Cloud Edgware.SR4 -- it was strange because other projects worked fine but there was a single one that didn't.
After further investigation I realized that the troublemaker project was using Spring Boot 1.5.3.RELEASE and others were using 1.5.9.RELEASE
After upgrading Spring Boot to 1.5.9.RELEASE things seemed to start working

Need help in REST ASSURED

I am starting with REST Assured, getting error while executing below code :
Code 1-
RestAssured.expect().statusCode(200).
body(
"name", equalTo("Russia")
).
when().
get("http://restcountries.eu/rest/v1/callingcode/7");
Exception-
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method equalTo(String) is undefined for the type
Code 2 -
RestAssured.expect().statusCode(200).
body(
"name", Matchers.equalTo("Russia")
).
when().
get("http://restcountries.eu/rest/v1/callingcode/7");
Exception-
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: com.jayway.restassured.internal.ContentParser.parse() is applicable for argument types: (com.jayway.restassured.internal.RestAssuredResponseImpl, com.jayway.restassured.internal.ResponseParserRegistrar, com.jayway.restassured.config.RestAssuredConfig, java.lang.Boolean) values: [com.jayway.restassured.internal.RestAssuredResponseImpl#753455ab, ...] Possible solutions: wait(), any(), grep()
Below are the only 2 methods in my class, I am having issue with first one, second one is running fine. Please let me know what I am missing in first method.
Method -1
public static void testCountriesCallingCode() {
RestAssured.expect().statusCode(200).
body(
"name", equalTo("Russia")
).
when().
get("http://restcountries.eu/rest/v1/callingcode/7");
System.out.println(RestAssured.get("http://restcountries.eu/rest/v1/callingcode/7").asString());
}
Method-2
public static void testCountriesCallingCodeUsingJSONPATH(){
Response res = RestAssured.get("http://restcountries.eu/rest/v1/callingcode/7");
System.out.println(res.getStatusCode());
String json = res.asString();
JsonPath jp = new JsonPath(json);
System.out.println(jp.get("name"));
}
Thanks Hti, your answer worked. Without the other dependencies, Rest Assured kind of works. I have no idea why Rest Assured website does not note this. Following in pom.xml worked
<properties>
<rest-assured.version>3.0.2</rest-assured.version>
<resteasy.version>3.0.17.Final</resteasy.version>
</properties>
...
<!-- Jackson is for allowing you to convert pojo (plain old Java object) into JSON -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-xml</artifactId>
<version>2.4.11</version>
<scope>test</scope>
</dependency>
Change the body of your first example to:
body(
"[0].name", equalTo("Russia")
)
That is because the JSON response from the server is not an object, but an array, and you have to query for the first object ([0]), then the name (.name).
For the Code-1, for equalTo() method you have to import org.hamcrest.Matchers.*;
For the exception in code 2, it is very hard to mention without looking at the RESPONSE but try to follow below link if you have nested generic parameters in your response.
How to validate nested response using REST Assured?
Please let me know if you have any issue or question. Thanks!
Even though this question is old, I just stumpled upon the second problem:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: com.jayway.restassured.internal.ContentParser.parse() is applicable for argument types: (com.jayway.restassured.internal.RestAssuredResponseImpl, com.jayway.restassured.internal.ResponseParserRegistrar, com.jayway.restassured.config.RestAssuredConfig, java.lang.Boolean) values: [com.jayway.restassured.internal.RestAssuredResponseImpl#753455ab, ...] Possible solutions: wait(), any(), grep()
This is due to missing dependencies. In my case I needed to add the dependencies for xml-path and groovy-xml, even though I'm just working with JSON data. So the best thing to do is resolving the dependencies transitively.
equalTo comes from Hamcrest which is a JUnit dependency contained within the JUnit jar. You probably just need to import the static method for it from Hamcrest.
import static org.hamcrest.core.IsEqual.*;
Add a static package for equal to:
import static org.hamcrest.Matchers.*;

Unable to add label using Neo4j Rest API - Error reading as JSON ''

The neo4j rest api throws runtime exception (error reading as JSON '') when trying to add a label.
My current set up
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-rest-graphdb</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.neo4j.app</groupId>
<artifactId>neo4j-server</artifactId>
<version>2.0.0</version>
</dependency>
Code that tries to create a new node and add a property and label. The runtime exception is thrown when we try to add the label. The rollback is working fine though. It appears that the API is trying to get details for the resource that is not yet created and trying to parse the response.
try ( Transaction tx = db.beginTx() ) {
//create new user
Node userNode = db.createNode();
userNode.setProperty( "id", id );
userNode.addLabel(DynamicLabel.label("GuestUser")); //throws runtime exception
tx.success();
}
Stack trace
java.lang.RuntimeException: Error reading as JSON ''
at org.neo4j.rest.graphdb.util.JsonHelper.readJson(JsonHelper.java:57)
at org.neo4j.rest.graphdb.util.JsonHelper.jsonToSingleValue(JsonHelper.java:62)
at org.neo4j.rest.graphdb.RequestResult.toEntity(RequestResult.java:114)
at org.neo4j.rest.graphdb.RequestResult.toMap(RequestResult.java:120)
at org.neo4j.rest.graphdb.ExecutingRestAPI.getData(ExecutingRestAPI.java:501)
at org.neo4j.rest.graphdb.RestAPIFacade.getData(RestAPIFacade.java:179)
at org.neo4j.rest.graphdb.entity.RestEntity.getStructuralData(RestEntity.java:75)
at org.neo4j.rest.graphdb.entity.RestNode.labelsPath(RestNode.java:188)
at org.neo4j.rest.graphdb.entity.RestNode.addLabel(RestNode.java:147)
Caused by: java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2775)
...
at org.neo4j.rest.graphdb.util.JsonHelper.readJson(JsonHelper.java:55)
... 43 more
Has anyone seen this problem so far.
This is a problem as those "pseudo" transactions only aggregate operations to send them at once at commit.
So you cannot do "read your writes" or make decisions on them.
And the addLabel operation uses the path returned from the structural info of the node which does not yet exist.
Don't think it's worth fixing. If you think so, please raise an issue at https://github.com/neo4j/java-rest-binding/issues