I want to check whether a file is present in a particular folder in documentum using Java.
Following is my code,
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.IDfLoginInfo;
import com.documentum.operations.IDfDeleteOperation;
public class CountFiles {
// Documentum target repository where the files will be imported
private static final String REPO_NAME = "rep";
public static void main( String[] args ) throws Exception {
try {
String username = "user";
String password = "pwd";
System.out.println( "Starting to connect ..." );
IDfSessionManager sessMgr = createSessionManager( );
addIdentity( sessMgr, username, password);
IDfSession sess = sessMgr.getSession(REPO_NAME );
System.out.println( "Successfully connected to the server.");
queryDocumentum(sess);
} catch( Exception ex ) {
System.out.println( ex );
ex.printStackTrace( );
}
}
private static void queryDocumentum(IDfSession sess) throws DfException {
IDfQuery query = new DfQuery();
String queryStr= "select count(*) from dm_document WHERE FOLDER ('/XXX/YYY',DESCEND) search document contains 'abc.pdf' ";
query.setDQL(queryStr);
IDfCollection coll = query.execute(sess,IDfQuery.DF_EXEC_QUERY);
while(coll.next())
{
System.out.println("Result of method: " + coll.getValueAt(0));
}
coll.close();
}
/**
* Creates a new session manager instance. The session manager does not have
* any identities associated with it.
*
* #return a new session manager object.
* #throws DfException
*/
private static IDfSessionManager createSessionManager( )
throws Exception {
IDfClientX clientX = new DfClientX( );
IDfClient localClient = clientX.getLocalClient( );
IDfSessionManager sessMgr = localClient.newSessionManager( );
System.out.println( "Created session manager." );
return sessMgr;
}
/**
* Adds a new identity to the session manager.
*
*/
private static void addIdentity( final IDfSessionManager sm,
final String username, final String password )
throws Exception {
IDfClientX clientX = new DfClientX( );
IDfLoginInfo li = clientX.getLoginInfo( );
li.setUser( username );
li.setPassword( password );
// check if session manager already has an identity.
// if yes, remove it.
if( sm.hasIdentity( REPO_NAME ) ) {
sm.clearIdentity( REPO_NAME );
System.out.println( "Cleared identity on :" + REPO_NAME );
}
sm.setIdentity( REPO_NAME, li );
System.out.println( "Set up identity for the user." );
}
}
I am getting the following exception - [DM_QUERY_E_SYNTAX]error: "A Parser Error (syntax error) has occurred in the vicinity of "select count(*) from dm_document WHERE FOLDER ('/XXX/YYY',DESCEND) search document contains 'abc.pdf'". what is the issue in the query/code?
Well, obviously your DQL query is wrong:
select count(*) from dm_document WHERE FOLDER ('/XXX/YYY',DESCEND) search document contains 'abc.pdf'
if you just want to check if some document named 'abc.pdf' is present in path /XXX/YYY and all folders below (keyword 'descend') then the DQL should be more like this, you don't need Full Text search capabilities for that:
select count(*) from dm_document where folder('/XXX/YYY', DESCEND) and object_name = 'abc.pdf'
If you don't know exact file name you can use "LIKE", for example:
select count(*) from dm_document where folder('/XXX/YYY', DESCEND) and object_name LIKE '%abc.pdf'
Related
I'm developing a Vaadin Flow (version 14.1) app and I have this issue, I don't get it to connect directly with MySQL database.
I have set up the JDBC connection with maven, I've also created a singleton class I call Datasource where I store my values and methods. However right now it only has one as I'm testing this, this is what I want to do:
Click on a button on the app and update a label
Here's the button click listener:
button.addClickListener(click -> {
label.setText(Datasource.getInstance().getUsername());
});
Here's the Datasource class method:
public String getUsername() {
String username = "QUERY-FAILED";
try {
start();
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from names");
rs.next();
username = rs.getString(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
return username;
}
But the label doesn't update, if I comment the try block it updates to QUERY-FAILED which is the string I put to test if it failed, but if it isn't commented the label just stays the same.
I also tried to add a main method to the Datasource class and run it as a Java application, and the method works fine, it does return a string with the username. So I'm guessing I'm stuck somewhere in between the connection with the vaadin app. Also, If I try to get the username String in my vaadin app when I'm starting the app (and not with a click listener) I got an long stack of errors with the Datasource indicating a nullpointerexception here:
statement = conn.createStatement();
Thanks in advance!
I cannot spot any problem with your code. But I can provide an entire working example app for you to compare
My example app goes along the lines laid out in your Question's code. A Vaadin Button performs a database query using a DataSource object from a table of user names. The value from the first row found is displayed in a Vaadin Label widget on the web page.
This app was built and run with Vaadin 14.1.5 using a "Plain Java Servlet" flavor of a starter project provided by the Vaadin.com site. Running on macOS Mojave with the bundled Jetty web container.
My only changes to their Maven POM file was to change to Java version 13, and to add a dependency for H2 Database Engine to make this a self-contained example using an in-memory database.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
I used the hook for Vaadin starting, to establish my DataSource object and initialize the database. Following the manual, nested in the resources folder, I created folders META-INF > services. Per the Java SPI facility, there I created a file named com.vaadin.flow.server.VaadinServiceInitListener containing a single line to specify the name of my class that implements the interface named in the name of this file:
work.basil.example.ApplicationServiceInitListener
That is, my ApplicationServiceInitListener class implement the Vaadin interface VaadinServiceInitListener. My class will be automatically instantiated and its method invoked via that Java SPI facility when my Vaadin web app launches.
My ApplicationServiceInitListener class:
package work.basil.example;
import com.vaadin.flow.server.ServiceInitEvent;
import com.vaadin.flow.server.VaadinServiceInitListener;
import org.h2.jdbcx.JdbcDataSource;
public class ApplicationServiceInitListener implements VaadinServiceInitListener
{
#Override
public void serviceInit ( ServiceInitEvent serviceInitEvent )
{
System.out.println( "DEBUG Running `serviceInit` of " + this.getClass().getCanonicalName() );
// Database work.
prepareDataSource();
App.INSTANCE.provideDatabase().initializeDatabase();
}
private void prepareDataSource ( )
{
JdbcDataSource ds = new JdbcDataSource();
ds.setURL( "jdbc:h2:mem:demo;DB_CLOSE_DELAY=-1" );
ds.setUser( "scott" );
ds.setPassword( "tiger" );
App.INSTANCE.rememberDataSource( ds );
}
}
That class calls my App class which acts as a sort of service locator. Designed as a singleton via enum.
package work.basil.example;
import javax.sql.DataSource;
import java.util.Objects;
public enum App
{
INSTANCE;
// -------| DataSource |---------------------------------
private DataSource dataSource;
public DataSource provideDataSource ( )
{
return this.dataSource;
}
public void rememberDataSource ( DataSource dataSource )
{
this.dataSource = Objects.requireNonNull( dataSource );
}
// -------| Database |---------------------------------
private Database database;
public Database provideDatabase ( )
{
return new Database();
}
}
That class calls my Database class. In real work, Database would be an interface with various concrete implementations for testing versus deployment. I ignored that here for demonstration purposes.
package work.basil.example;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Database
{
public String getFirstUserName ( )
{
String userName = "QUERY-FAILED";
String newline = "\n";
StringBuilder sql = new StringBuilder();
sql.append( "SELECT name_ from user_ ; " ).append( newline );
System.out.println( "sql = " + sql );
try (
Connection conn = App.INSTANCE.provideDataSource().getConnection() ;
Statement statement = conn.createStatement() ;
ResultSet resultSet = statement.executeQuery( sql.toString() ) ;
)
{
while ( resultSet.next() )
{
userName = resultSet.getString( "name_" );
break; // Go no further. We need only the first row found.
}
}
catch ( SQLException e )
{
e.printStackTrace();
}
return userName;
}
public void initializeDatabase ( )
{
System.out.println( "DEBUG Running `initializeDatabase` of " + this.getClass().getCanonicalName() );
String newline = "\n";
// Create table.
StringBuilder sql = new StringBuilder();
sql.append( "CREATE TABLE user_ ( " ).append( newline );
sql.append( "pkey_ IDENTITY NOT NULL PRIMARY KEY , " ).append( newline ); // `identity` = auto-incrementing long integer.
sql.append( "name_ VARCHAR NOT NULL " ).append( newline );
sql.append( ") " ).append( newline );
sql.append( ";" ).append( newline );
System.out.println( "sql = " + sql );
try (
Connection conn = App.INSTANCE.provideDataSource().getConnection() ;
Statement statement = conn.createStatement() ;
)
{
statement.executeUpdate( sql.toString() );
}
catch ( SQLException e )
{
e.printStackTrace();
}
System.out.println("DEBUG Finished `CREATE TABLE` statement.");
// Populate table.
sql = new StringBuilder();
sql.append( "INSERT INTO user_ ( name_ ) " ).append( newline );
sql.append( "VALUES " ).append( newline );
sql.append( "( 'Alice' ) , " ).append( newline );
sql.append( "( 'Bob' ) , " ).append( newline );
sql.append( "( 'Carol' ) " ).append( newline );
sql.append( ";" ).append( newline );
System.out.println( "sql = " + sql );
try (
Connection conn = App.INSTANCE.provideDataSource().getConnection() ;
Statement statement = conn.createStatement() ;
)
{
int rowsAffected = statement.executeUpdate( sql.toString() );
System.out.println( "DEBUG Inserted rows into name_ table: " + rowsAffected );
}
catch ( SQLException e )
{
e.printStackTrace();
}
System.out.println("DEBUG Finished `INSERT` statement.");
}
}
And lastly, the MainView class. I disable the #PWA annotation as we are not using that feature for progressive web apps.
package work.basil.example;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
/**
* The main view contains a button and a click listener.
*/
#Route ( "" )
//#PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
public class MainView extends VerticalLayout
{
private Label label;
private Button button;
public MainView ( )
{
// Widgets
this.label = new Label( "User: ?" );
this.button = new Button(
"Get user" ,
event -> {
Notification.show( "Getting user." );
String userName = App.INSTANCE.provideDatabase().getFirstUserName();
this.label.setText( "User: " + userName );
}
);
add( button );
// Arrange
this.add( label , button );
}
}
You should check if the ResultSet rs actually has results. When calling rs.next(), look if it returns false. How to check if ResultSet is empty
public String getUsername() {
String username = "QUERY-FAILED";
try {
start();
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select userName from names");
if(rs.next() != false){
username = rs.getString(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
return username;
}
Another thing I noticed is that from the query select * from names, one cannot be sure that the userName attribute is the first column, which you are reading with rs.getString(1). Make sure to write your query more precise to avoid hard-to-find bugs: select userName from names; Do this even if the table only has one column, because what if somebody prepended another column? it could break your application.
I'm a beginner for Java and neo4j.
Trying my first connection to neo4j using Java Application. I'm unable to understand why I am getting Error:
Exception in thread "main" org.neo4j.driver.v1.exceptions.AuthenticationException: The client is unauthorized due to authentication failure.
Bolt : bolt://localhost:7687 (neo4j Desktop on my macbook)
GraphName : PrakashTest1
Password : 12345678
Java Application:
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable {
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
#Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message ) {
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
#Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "PrakashTest1", "12345678" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
i'm trying to secure my enterprise web-app!
i have to constraint resources.
Since i have all stored in my db (users and roles), i won't create a fileRealm or store any user's credential in (Glassfish) server. Moreover, i'm using jBCrypt to encrypt users' passwords, so i can't use standard jdbcRealm.
How can i secure my resources?
i'm thinking about custom jdbcRealm, it's the right way? How can i create and use it?
Some existing framework can help me?
Thank you in advance.
I would suggest you to use a framework Apache Shiro. The configuration file is below
[main]
sha256Matcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
sha256Matcher.hashAlgorithmName = SHA-256
sha256Matcher.hashIterations=1
# base64 encoding
sha256Matcher.storedCredentialsHexEncoded = false
#datasource type
ds = org.apache.shiro.jndi.JndiObjectFactory
#datasourcename
ds.resourceName = cfresource
#datasourcetype
ds.requiredType = javax.sql.DataSource
#configuring jdbc realm
jdbcRealm = com.connectifier.authc.realm.CustomJDBCRealm
jdbcRealm.credentialsMatcher = $sha256Matcher
jdbcRealm.dataSource=$ds
jdbcRealm.userRolesQuery=select name from role where email = ? and isactive=1
jdbcRealm.authenticationQuery=select hash, salt from user where email = ?
jdbcRealm.permissionsLookupEnabled=false
securityManager.realms = $jdbcRealm
#login url
authc.loginUrl = /
#page to redirected to after logout
logout.redirectUrl = /
#page to where to land after login
authc.successUrl = /
#username parameter name in the loginform
authc.usernameParam = username
#password parameter name in the loginform
authc.passwordParam = password
#rememberme parameter name in the loginform
authc.rememberMeParam=rememberme
#cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
#securityManager.cacheManager = $cacheManager
#jdbcRealm.authenticationCachingEnabled = true
[urls]
# The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but
# the 'authc' filter must still be specified for it so it can process that url's
# login submissions. It is 'smart' enough to allow those requests through as specified by the
# shiro.loginUrl above.
/* = anon
The CustomJDBCRealm overriding JDBCRealm is below
package com.connectifier.authc.realm;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.JdbcUtils;
import org.apache.shiro.util.SimpleByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author kiranchowdhary
*
* Application specific JDBC realm. If required override methods of {#link JdbcRealm} to load users, roles and
* permissions from database.
*
* Do not override configuration in code if it can be done via shiro.ini file.
*/
public class CustomJDBCRealm extends JdbcRealm {
private static final Logger log = LoggerFactory.getLogger(JdbcRealm.class);
public CustomJDBCRealm() {
super();
setSaltStyle(SaltStyle.COLUMN);
}
/**
* overriding the method which is in JdbcRealm. If SaltStyle is COLUMN, then gets String salt value from database
* and forms salt byte array of type {#link ByteSource} with decoded string salt value and sets it to salt value of
* AuthenticationInfo.
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
// Null username is invalid
if (username == null) {
throw new AccountException("Null usernames are not allowed by this realm.");
}
Connection conn = null;
SimpleAuthenticationInfo info = null;
try {
conn = dataSource.getConnection();
String password = null;
String salt = null;
switch (saltStyle) {
case NO_SALT:
case CRYPT:
case EXTERNAL:
return super.doGetAuthenticationInfo(token);
case COLUMN:
String[] queryResults = getPasswordForUser(conn, username);
password = queryResults[0];
salt = queryResults[1];
break;
}
if (password == null) {
throw new UnknownAccountException("No account found for user [" + username + "]");
}
info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
if (salt != null) {
info.setCredentialsSalt(new SimpleByteSource(Base64.decode(salt)));
}
} catch (SQLException e) {
final String message = "There was a SQL error while authenticating user [" + username + "]";
if (log.isErrorEnabled()) {
log.error(message, e);
}
// Rethrow any SQL errors as an authentication exception
throw new AuthenticationException(message, e);
} finally {
JdbcUtils.closeConnection(conn);
}
return info;
}
private String[] getPasswordForUser(Connection conn, String username) throws SQLException {
String[] result;
boolean returningSeparatedSalt = false;
switch (saltStyle) {
case NO_SALT:
case CRYPT:
case EXTERNAL:
result = new String[1];
break;
default:
result = new String[2];
returningSeparatedSalt = true;
}
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(authenticationQuery);
ps.setString(1, username);
// Execute query
rs = ps.executeQuery();
// Loop over results - although we are only expecting one result,
// since usernames should be unique
boolean foundResult = false;
while (rs.next()) {
// Check to ensure only one row is processed
if (foundResult) {
throw new AuthenticationException("More than one user row found for user [" + username
+ "]. Usernames must be unique.");
}
result[0] = rs.getString(1);
if (returningSeparatedSalt) {
result[1] = rs.getString(2);
}
foundResult = true;
}
} finally {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(ps);
}
return result;
}
}
I want to make a simple program where you can send email from the Command Line. I found this tutorial, ' http://www.tutorialspoint.com/java/java_sending_email.htm ', however the downloads don't. So where can I get JavaMail API and Java Activation Framework (JAF) and how would i put it in my class path.
Basically Im looking for someone to break it down and show me how I could make an email program.
Im using Eclipse luna.
Do have a look at this example. This example, simply sends one attachment as a mail. The contents of attachment quiz.txt are as follows:
What is the Capital of India?/New Delhi
Where is the Taj Mahal?/Agra
Here is the SendMailExample.java file:
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class SendMailExample {
private String from;
private String to;
private String subject;
private String messageBody;
private String fileName;
private String host;
private Properties properties;
private MimeMessage message;
private BodyPart messageBodyPart;
private Multipart multipart;
private Authenticator authenticator;
public SendMailExample () {
from = "sender#gmail.com";
to = "recipient#gmail.com";
subject = "Subject Testing";
messageBody = "<html><body><h1>HAVE FAITH, AND STAY" +
" CALM :-) I AM WITH YOU, OKAY :-)</h1></body></html>";
fileName = "quiz.txt";
host = "smtp.gmail.com";
authenticator = new SMTPAuthenticator ();
properties = System.getProperties ();
properties.put ( "mail.smtp.host", host );
properties.put ( "mail.smtp.starttls.enable", "true" );
properties.put ( "mail.smtp.port", "587" );
properties.put ( "mail.smtp.auth", "true" );
}
private void sendMail ( String from, String to,
String subject, String messageBody, String fileName ) {
try {
Session session = Session.getDefaultInstance ( properties, authenticator );
message = new MimeMessage ( session );
message.setFrom ( new InternetAddress ( from ) );
message.addRecipient ( Message.RecipientType.TO,
new InternetAddress ( to ) );
message.setSubject ( subject );
multipart = new MimeMultipart ();
messageBodyPart = new MimeBodyPart ();
messageBodyPart.setContent ( messageBody, "text/html" );
multipart.addBodyPart ( messageBodyPart );
messageBodyPart = new MimeBodyPart ();
DataSource source = new FileDataSource ( fileName );
messageBodyPart.setDataHandler ( new DataHandler ( source ) );
messageBodyPart.setFileName ( fileName );
multipart.addBodyPart ( messageBodyPart );
message.setContent ( multipart );
Transport.send ( message );
System.out.println ( "Message send successfully...." );
} catch ( Exception me ) {
me.printStackTrace ();
}
}
private void performTask () {
sendMail ( from, to, subject, messageBody, fileName );
}
public static void main ( String[] args ) {
new SendMailExample ().performTask ();
}
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
class SMTPAuthenticator extends Authenticator {
private static final String SMTP_AUTH_USER = "example#gmail.com";
private static final String SMTP_AUTH_PASSWORD = "somepassword";
public PasswordAuthentication getPasswordAuthentication () {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PASSWORD;
return new PasswordAuthentication( username, password );
}
}
You simply needed this mail.jar file.
To compile, simply write ( mail.jar is present at C:\install\java\mail\mail.jar` location ):
javac -classpath .;C:\install\java\mail\mail.jar SendMailExample.java
To run, write:
java -classpath .;C:\install\java\mail\mail.jar SendMailExample
THis will do :-)
Take a look at this library Commons Email it will simplify your task
I am trying to use the 'Hello World' for Neo4j. The problem is that I when I boot up the server and check the neo4j's browser (localhost:7474), I cannot see any graphic visualisation of my nodes.
import java.io.File;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class MyFirstMain
{
private static final String DB_PATH = "/neo4j/data/graph.db";
public String greeting;
// START SNIPPET: vars
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
// END SNIPPET: vars
// START SNIPPET: createReltype
private static enum RelTypes implements RelationshipType
{
KNOWS
}
// END SNIPPET: createReltype
public static void main( final String[] args )
{
MyFirstMain hello = new MyFirstMain();
hello.createDb();
// hello.removeData();
// hello.shutDown();
}
void createDb()
{
// START SNIPPET: startDb
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
registerShutdownHook( graphDb );
// END SNIPPET: startDb
// START SNIPPET: transaction
try ( Transaction tx = graphDb.beginTx() )
{
// Database operations go here
// END SNIPPET: transaction
// START SNIPPET: addData
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Hello, " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "World!" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
relationship.setProperty( "message", "brave Neo4j " );
// END SNIPPET: addData
// START SNIPPET: readData
System.out.print( firstNode.getProperty( "message" ) );
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
// END SNIPPET: readData
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) );
// START SNIPPET: transaction
tx.success();
}
// END SNIPPET: transaction
}
// START SNIPPET: shutdownHook
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
// END SNIPPET: shutdownHook
}
I do NOT want to use anything else, except the neo4j's built in browser.
How should I proceed?
Thanks in advance.
You must shut down the server, then create your data, then start the server again, you cannot use the same data directory from two database processes at the same time.
Your DB_PATH is also wrong, you can't have a star in there.