I am running neo4j-community-2.2.5 locally on my macbook.
I am trying to connect to the code using the neo4j-ogm version : 1.1.2
Here is the session factory:
public class Neo4jSessionFactory {
private final static SessionFactory sessionFactory = new SessionFactory("com.readypulse.rpinfluencernetwork.ogm.model");
private static Neo4jSessionFactory factory = new Neo4jSessionFactory();
public static Neo4jSessionFactory getInstance() {
return factory;
}
private Neo4jSessionFactory() {
}
public Session getNeo4jSession() {
return sessionFactory.openSession("http://localhost:7474", "neo4j", "mypassword");
}
}
I have a entity class :
#NodeEntity(label="Hashtag")
public class Hashtag extends Entity {
#Property(name = "name")
String name;
...
Service :
public interface HashtagService extends Service<Hashtag>{
}
Generic Service:
public abstract class GenericService<T> implements Service<T> {
private static final int DEPTH_LIST = 0;
private static final int DEPTH_ENTITY = 1;
private Session session = Neo4jSessionFactory.getInstance().getNeo4jSession();
public Iterable<T> findAll() {
return session.loadAll(getEntityType(), DEPTH_LIST);
}
public T find(Long id) {
return session.load(getEntityType(), id, DEPTH_ENTITY);
}
public void delete(Long id) {
session.delete(session.load(getEntityType(), id));
}
public void createOrUpdate(T entity) {
session.save(entity, DEPTH_ENTITY);
}
public abstract Class<T> getEntityType();
}
Calling code :
public static void main(String args[]) {
Hashtag hashtag = new Hashtag("fun");
HashtagService service = new HashtagServiceImpl();
service.createOrUpdate(hashtag);
}
I am running the code on eclipse as simple java process, and not on any Application server.
Here is the full log with trace:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/lazywiz/.m2/repository/org/slf4j/slf4j-log4j12/1.5.8/slf4j-log4j12-1.5.8.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/lazywiz/.m2/repository/org/slf4j/slf4j-jdk14/1.5.11/slf4j-jdk14-1.5.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/lazywiz/.m2/repository/ch/qos/logback/logback-classic/1.1.2/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
15/10/09 14:55:16 INFO info.ClassFileProcessor: Starting Post-processing phase
15/10/09 14:55:16 INFO info.ClassFileProcessor: Building annotation class map
15/10/09 14:55:16 INFO info.ClassFileProcessor: Building interface class map for 9 classes
15/10/09 14:55:16 INFO info.ClassFileProcessor: Registering default type converters...
15/10/09 14:55:16 INFO info.ClassFileProcessor: Post-processing complete
15/10/09 14:55:16 INFO info.ClassFileProcessor: 9 classes loaded in 16 milliseconds
15/10/09 14:55:17 WARN request.DefaultRequest: Caught response exception: No Host
Exception in thread "main" org.neo4j.ogm.session.result.ResultProcessingException: Failed to execute request: {"statements":[{"statement":"CREATE (_0:`Hashtag`{_0_props}) RETURN id(_0) AS _0","parameters":{"_0_props":{"name":"varun"}},"resultDataContents":["row"],"includeStats":false}]}
at org.neo4j.ogm.session.request.DefaultRequest.execute(DefaultRequest.java:105)
at org.neo4j.ogm.session.request.SessionRequestHandler.execute(SessionRequestHandler.java:99)
at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:68)
at org.neo4j.ogm.session.Neo4jSession.save(Neo4jSession.java:391)
at com.readypulse.rpinfluencernetwork.ogm.service.GenericService.createOrUpdate(GenericService.java:26)
at com.readypulse.rpinfluencernetwork.GraphManager.main(GraphManager.java:16)
Caused by: org.apache.http.client.HttpResponseException: No Host
at org.neo4j.ogm.session.request.DefaultRequest.execute(DefaultRequest.java:86)
... 5 more
Can someone please suggest where I am going wrong.
Prior to this I was having a totally different code base where I was using
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath); and
But later I realized that this is not the right way when I want to connect to the neo4j server running in prod environment. I want to start the server and hence connect is via java and Ruby client concurrently.
Thanks!
Some points :
a)
You can not use neo4j as password, this is the default password when you install a new database, but the password need to be changed at first start.
For changing the password :
Open the Neo4j browser and the first prompt will ask you to change the password
Or issue a curl request for changing the password :
curl -H "Content-Type: application/json"\
-H "Authorization: Basic echo -n 'neo4j:neo4j' | base64"\
-X POST -d '{"password":"yourNewPassword"}'\
-I http://localhost:7474/user/neo4j/password
b) If you're not using SDN4, In the sessionFactoryyou need to pass the user and password as arguments to the openSession method:
Session session = sessionFactory.openSession("http://localhost:7474", username, password);
Docs :
Neo4j Authentication: http://neo4j.com/docs/stable/rest-api-security.html#rest-api-user-status-on-first-access
Neo4j OGM Session Authentication : http://neo4j.com/docs/ogm/java/stable/#reference_programming-model_session
Related
I'm stuck with a problem on a built Spring Native image:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [collection type; class java.util.HashSet, contains [simple type, class java.lang.Object]]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.util.HashSet (no Creators, like default constructor, exist): no default no-arguments constructor found
at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 5, column: 14] (through reference chain: com.example.app.payload.request.SignupRequest["roles"])] with root cause
From this description it seems that I need use custom deserializer, but the problem appears only if I run code from native image - same code works perfectly well if run from JAR.
POJOs are very simple:
public class SignupRequest {
#NotBlank
#Size(min = 3, max = 20)
private String username;
#NotBlank
#Size(max = 50)
#Email
private String email;
private Set<String> roles;
#NotBlank
#Size(min = 6, max = 40)
private String password;
// getters & setters no Lombok (but Lombok is in project)
}
Controller uses standard (nothing fancy) annotations:
public ResponseEntity<MessageResponse> registerUser(#Valid #RequestBody SignupRequest signUpRequest)
Has anyone encountered a similar problem?
Finally I found missing part - I have to add HashSet to SerializationHint:
#SpringBootApplication
#SerializationHint(types = {
java.util.HashSet.class
})
public class SpringNativeApplication {
public static void main(String[] args) {
// ...
}
}
In the process of setup a bridge between guice and jersey, I ran into one problem.
When trying to create a jersey filter, I was unable to inject guice dependencies into it.
I found a duplicate, however there is no solution to the problem there.
Everything is exactly the same.
The only difference is that I don't get a startup error. The filter works, but my dependencies are null.
Interestingly, Filter and HttpFilter work fine. But it doesn't really work for me.
There's another thing that's interesting. In the resource, which I understand is an HK2 dependency, I can inject guice bean.
#ApplicationPath("/test")
private static class TestApplicationConfig extends ResourceConfig
{
public TestApplicationConfig()
{
register(JacksonFeature.class);
register(AuthFilter.class);
register(new ContainerLifecycleListener()
{
public void onStartup(Container container)
{
ServletContainer servletContainer = (ServletContainer) container;
ServiceLocator serviceLocator = container.getApplicationHandler().getServiceLocator();
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
Injector injector = (Injector) servletContainer
.getServletContext()
.getAttribute(Injector.class.getName());
guiceBridge.bridgeGuiceInjector(injector);
}
public void onReload(Container container)
{
}
public void onShutdown(Container container)
{
}
});
}
}
In ServletModule child.
serve(path).with(ServletContainer.class, ImmutableMap.of(
"javax.ws.rs.Application", TestApplicationConfig.class.getName(),
"jersey.config.server.provider.packages", sb.toString()));
I trying with register(AuthFilter.class) and #Provider
#Singleton
#Provider
public class AuthFilter implements ContainerRequestFilter
{
#Inject
private SomeInjectedService someInjectedService; **// null here**
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// some code
}
}
SomeInjectedService I register by guice
bind(SomeInjectedService.class).asEagerSingleton();
Where can I start diagnosing and what can I do?
UPD:
I noticed different behavior when using different annotations.
If I use javax.inject.Inject, I get the following error message.
org.glassfish.hk2.api.MultiException: A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=SomeInjectedService,parent=AuthFilter,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1496814489)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of some.package.AuthFilter errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on some.package.AuthFilter
If com.google.inject.Inject, just null. As I understand this method is not correct.
Considering that javax Inject is trying to inject the service but can't find it. Can we conclude that the bridge is not working correctly? But if it's not working correctly, why can I inject this service into my resource?
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class SomeResource
{
private final SomeInjectedService someInjectedResource;
#Inject // here I use javax annotation and this code working correctry
public SomeResource(SomeInjectedService someInjectedResource)
{
this.someInjectedResource = someInjectedResource;
}
#GET
#Path("/{user}")
public Response returnSomeResponse(#PathParam("user") String user) throws Exception
{
// some code
}
}
I have created a project that contains an ExtensionFactory subclass annotated as #ServiceProvider that returns a LifecycleAdapter subclass which registers a transaction event listener in its start() method, as shown in this example. The code is below:
#ServiceProvider
public class EventListenerExtensionFactory extends ExtensionFactory<EventListenerExtensionFactory.Dependencies> {
private final List<TransactionEventListener<?>> listeners;
public EventListenerExtensionFactory() {
this(List.of(new MyListener()));
}
public EventListenerExtensionFactory(List<TransactionEventListener<?>> listeners) {
super(ExtensionType.DATABASE, "EVENT_LISTENER_EXT_FACTORY");
this.listeners = listeners;
}
#Override
public Lifecycle newInstance(ExtensionContext context, Dependencies dependencies) {
return new EventListenerLifecycleAdapter(dependencies, listeners);
}
#RequiredArgsConstructor
private static class EventListenerLifecycleAdapter extends LifecycleAdapter {
private final Dependencies dependencies;
private final List<TransactionEventListener<?>> listeners;
#Override
public void start() {
DatabaseManagementService managementService = dependencies.databaseManagementService();
listeners.forEach(listener -> managementService.registerTransactionEventListener(
DEFAULT_DATABASE_NAME, listener));
dependencies.log()
.getUserLog(EventListenerExtensionFactory.class)
.info("Registering transaction event listener for database " + DEFAULT_DATABASE_NAME);
}
}
interface Dependencies {
DatabaseManagementService databaseManagementService();
LogService log();
}
}
It works fine in an integration test:
public AbstractDatabaseTest(TransactionEventListener<?>... listeners) {
URI uri = Neo4jBuilders.newInProcessBuilder()
.withExtensionFactories(List.of(new EventListenerExtensionFactory(List.of(listeners))))
.withDisabledServer()
.build()
.boltURI();
driver = GraphDatabase.driver(uri);
session = driver.session();
}
Then I copy the jar file in the plugins directory of my desktop database:
$ cp build/libs/<myproject>.jar /mnt/c/Users/albert.gevorgyan/.Neo4jDesktop/relate-data/dbmss/dbms-7fe3cbdb-11b2-4ca2-81eb-474edbbb3dda/plugins/
I restart the database and even the whole desktop Neo4j program but it doesn't seem to identify the plugin or to initialize the factory: no log messages are found in neo4j.log after the start event, and the transaction events that should be captured by my listener are ignored. Interestingly, a custom function that I have defined in the same jar file actually works - I can call it in the browser. So something must be missing in the extension factory as it doesn't get instantiated.
Is it possible at all to deploy an ExtensionFactory in a Desktop installation and if yes, what am I doing wrong?
It works after I added a provider configuration file to META-INF/services, as explained in https://www.baeldung.com/java-spi. Neo4j finds it then.
I am using Neo4j OGM 2.0.4 driver with Java (embedded driver). When I do save(item) on session everything looks all right. Hovewer when I want to load items from database I get this exception:
16:01:23.182 [main] INFO org.neo4j.ogm.service.DriverService - Using driver: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
16:01:24.768 [main] DEBUG org.neo4j.ogm.service.Components - Setting driver to: org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
16:01:24.782 [main] WARN org.neo4j.ogm.session.Neo4jSession - Thread 1: neo4jCMS.entity.Author is not an instance of a persistable class
16:01:24.782 [main] WARN org.neo4j.ogm.session.Neo4jSession - Thread 1: neo4jCMS.entity.Author is not an instance of a persistable class
Saved
Exception in thread "main" java.lang.NullPointerException
at org.neo4j.ogm.MetaData.entityType(MetaData.java:280)
at org.neo4j.ogm.session.Neo4jSession.entityType(Neo4jSession.java:486)
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:60)
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:108)
at org.neo4j.ogm.session.Neo4jSession.loadAll(Neo4jSession.java:152)
at neo4jCMS.TestSite.run(TestSite.java:35)
at neo4jCMS.Application.main(Application.java:20)
While executing:
Author author1 = new Author("Author no 1");
Author author2 = new Author("Author no 2");
session.save(author1);
session.save(author2);
System.out.println("Saved");
Iterable<Author> authors = session.loadAll(Author.class);
for (Author author : authors)
{
System.out.println("Author: " + author.getName());
}
My node class is:
#NodeEntity
public class Author
{
#GraphId
private Long id;
private String _name;
public Author() { _name = "";}
public Author(String name)
{
_name = name;
}
public String getName()
{
return _name;
}
}
First of all you will need to add a no-arg constructor to your Author class in order for the OGM to create objects.
If that does not solve it try rerunning the loadAll code segment again. I have seen the odd Exception on first execution. I thought this was fixed but maybe it's only in 2.0.5-SNAPSHOT.
The issue was in configuration. new SessionFactory() was without argument "myProject.subDirectory". After adding that it works.
We need an option to set the ProviderManifestToken in code for a Database First Model in order to override the value from the EDMX, which defaults to "2012" for SQL Server 2012 in our particular case.
What we've tried so far: As described in this post we decorated our context class with the DbConfigurationType attribute, our derived class looks exactly the same as in that post.
internal sealed class MyDbConfiguration : DbConfiguration
{
public MyDbConfiguration()
{
//this.AddDependencyResolver(new SingletonDependencyResolver<IManifestTokenResolver>(new ManifestTokenService()));
this.SetManifestTokenResolver(new ManifestTokenService());
}
}
As you can see, we tried 2 different things here, AddDependencyResolver and SetManifestTokenResolver.
When we start the application program execution enters the constructor of MyDbConfiguration - and that's it, the dependency resolver itself
internal sealed class ManifestTokenService : IManifestTokenResolver
{
private const string SqlServerManifestToken = #"2005";
private static readonly IManifestTokenResolver DefaultManifestTokenResolver = new DefaultManifestTokenResolver();
/// <inheritdoc />
public string ResolveManifestToken(DbConnection connection)
{
if (connection is SqlConnection)
{
return SqlServerManifestToken;
}
return DefaultManifestTokenResolver.ResolveManifestToken(connection);
}
}
is never invoked so it seems we've reached a dead end here. Has anyone had the same problem and found a solution?