Neo4j - java Authentication failure - java

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" );
}
}
}

Related

why does my vue client not receive websocket messages

I want to send messages via queue and topic to my frontend but it doesnt work, useing SOCKJS and STOMP. My backend logs, that new memeber subscribe, but when i send a message via convertAndSend or convertAndSendToUser nothing happens on the client side. pls help me. ty in advance. pls dont delete this question.
SERVER:
CONFIG:
#Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableSimpleBroker("/user", "/topic", "/queue");
config.setApplicationDestinationPrefixes("/ws");
}
#Override
public void configureClientInboundChannel(final ChannelRegistration registration) {
registration.interceptors(new UserInterceptor());
}
#Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/connect").setAllowedOriginPatterns("*").withSockJS();
}
CONTROLLER:
#Controller
#Slf4j
public class WebsocketController {
#Autowired
SimpMessagingTemplate simpMessagingTemplate;
#Autowired
LobbyManagerService lobbyManagerService;
#Autowired
WebsocketService websocketService;
final String newMember = "/queue/newMember/";
final String lobbyDestination = "/topic/lobby/";
#MessageMapping("/get/infos/on/join/{lobby}")
public void getInfosOnJoinLobby(final SimpMessageHeaderAccessor sha, #DestinationVariable final String lobby) throws JsonProcessingException {
log.info("Send lobby infos to newly joined player");
final Message joinLobbyMessage = new JoinLobbyMessage(lobbyManagerService.getLobby(lobby).getPlayerNames());
final MessageWrapper joinLobbyMessageWrapped = websocketService.wrapMessage(joinLobbyMessage, Purpose.JOIN_LOBBY_MESSAGE);
simpMessagingTemplate.convertAndSendToUser(sha.getUser().getName(), newMember + lobby, joinLobbyMessageWrapped);
}
#MessageMapping("/lobby/{lobby}/join/team/{team}/player/{player}")
public void joinTeam(#DestinationVariable final String lobby, #DestinationVariable final String team, #DestinationVariable final String player) throws JsonProcessingException {
log.info("player '{}' joined team '{}' in lobby '{}'", player, team, lobby);
final JoinTeamMessage joinTeamMessage = new JoinTeamMessage(team, player);
final MessageWrapper joinTeamMessageWrapped = websocketService.wrapMessage(joinTeamMessage, Purpose.JOIN_TEAM_MESSAGE);
simpMessagingTemplate.convertAndSend(lobbyDestination + lobby, joinTeamMessageWrapped);
}
#MessageMapping("/start/lobby/{lobby}")
public void startLobby(#DestinationVariable final String lobby) {
log.info("start lobby");
//todo this methods will be implemented later
}
}
CLIENT:
function connect() {
console.log("connect to lobby");
return new Promise((resolve, reject) => {
stompClientGame.value = Stomp.over(
new SockJS("/minigames/towercrush/api/v1/connect")
);
let uuid = generateUUID();
console.log("players uuid was: ", uuid);
stompClientGame.value.connect(
{ player: player.value, lobby: lobby.value, userUUID: uuid },
() => resolve(stompClientGame.value)
);
});
}
function connectToLobby() {
connect()
.then(() => {
stompClientGame.value.subscribe(
"/user/queue/newMember/" + lobby.value,
function (messageOutput: any) {
handleMessageReceipt(messageOutput.body);
}
);
})
.then(() => {
stompClientGame.value.subscribe(
"/topic/lobby/" + lobby.value,
function (messageOutput: any) {
handleMessageReceipt(messageOutput.body);
}
);
});
}
i tryed literally every possible variation that came to my mind but nothing worked. pls help.

Mockito: Wanted but not invoked - however, there were other interactions

I'm receiving this error and have researched that it is because I am not calling the Mocked class but the actual class? I've looked over it numerous times and it seems to be pretty straightforward to simply be invoking the mock. The main error I get is
Wanted but not invoked:
dsIn.setItemString(1, "MAKE", "MAKE");
However, there were other interactions with this mock:
dsIn.getItemNumber(1, "APPROVED");
dsIn.setItemString(1, "VIN", "VIN");
dsIn.setItemObject(1, "MAKE", null);
And then it just continues through the others.
Below is the class to be tested:
if(dsIn.getItemNumber(1,"APPROVED") == 1) {
throw new TRDIException("Cannot change Approved record");
}
String sql;
sql = "select c.EQUIPMENT_NAME, c.VIN, c.MAKE, c.MODEL,c.EQUIPMENT_CLASS_CODE_ID,c.SALVAGE_VALUE,c.GARAGE_ASSIGNED,c.EQ_LOCATION_ID, c.DEPT_PM_NOTIFY, " +
"GET_DEPR_VALUE(c.EQUIPMENT_ID) AS EQ_CURRENT_VALUE " +
" from EQUIPMENT_INVENTORY c where c.EQUIPMENT_ID = " + newValueIn ;
DataStore ds = dl.createDataStore(sql);
ds.retrieve();
dsIn.setItemString(1,"VIN",ds.getItemString(1,"VIN"));
dsIn.setItemObject(1,"MAKE",ds.getItemObject(1,"MAKE"));
dsIn.setItemObject(1,"MODEL",ds.getItemObject(1,"MODEL"));
dsIn.setItemObject(1,"EQUIPMENT_CLASS_CODE_ID",ds.getItemObject(1,"EQUIPMENT_CLASS_CODE_ID"));
dsIn.setItemObject(1,"GARAGE_ASSIGNED",ds.getItemObject(1,"GARAGE_ASSIGNED"));
dsIn.setItemObject(1,"EQ_LOCATION_ID",ds.getItemObject(1,"EQ_LOCATION_ID"));
dsIn.setItemObject(1,"SALVAGE_VALUE",ds.getItemObject(1,"SALVAGE_VALUE"));
if(dsIn.getItemNumber(1,"APPROVED") == 1) {
throw new TRDIException("Cannot change approved record");
}
Below is the test class:
#RunWith(Parameterized.class)
public class TestFillEqDisposalAttr extends TestGroovy {
#Mock
private DataLayer dl;
#Mock
private DataStore dsIn;
#Mock
private DataStore ds;
private String newValueIn;
#Parameter
public String client;
#Parameters(name = "{index}: {0}")
public static Object[] data() {
return new Object[]{
"test"
};
}
#Before
public void setUp() throws Exception {
//groovy script file to test
groovyScriptFile = new File(GROOVY_SCRIPTS_FOLDER + "/" + client + "/test.groovy");
MockitoAnnotations.initMocks(this);
Mockito.when(dl.createDataStore(Mockito.anyString())).thenReturn(ds);
newValueIn = "1";
//groovy script parameters
addGroovyBindingVariable(GroovyScriptArgName.DATALAYER, dl);
addGroovyBindingVariable(GroovyScriptArgName.DATASTORE, dsIn);
addGroovyBindingVariable(GroovyScriptArgName.NEW_VALUE, newValueIn);
}
/**
*/
#Test
public void testEqDisposalAttr() throws IOException, TRDIException {
Mockito.when(ds.getItemString(1, "VIN")).thenReturn("VIN");
Mockito.when(ds.getItemString(1, "MAKE")).thenReturn("MAKE");
Mockito.when(ds.getItemString(1, "MODEL")).thenReturn("MODEL");
Mockito.when(ds.getItemString(1, "EQUIPMENT_CLASS_CODE_ID")).thenReturn("EQUIPMENT_CLASS_CODE_ID");
Mockito.when(ds.getItemString(1, "GARAGE_ASSIGNED")).thenReturn("GARAGE_ASSIGNED");
Mockito.when(ds.getItemString(1, "EQ_LOCATION_ID")).thenReturn("EQ_LOCATION_ID");
Mockito.when(ds.getItemString(1, "SALVAGE_VALUE")).thenReturn("SALVAGE_VALUE");
evaluate();
String sql = "select c.EQUIPMENT_NAME, c.VIN, c.MAKE, c.MODEL,c.EQUIPMENT_CLASS_CODE_ID,c.SALVAGE_VALUE,c.GARAGE_ASSIGNED,c.EQ_LOCATION_ID, c.DEPT_PM_NOTIFY, " +
"GET_DEPR_VALUE(c.EQUIPMENT_ID) AS EQ_CURRENT_VALUE " +
" from EQUIPMENT_INVENTORY c where c.EQUIPMENT_ID = " + newValueIn ;
Mockito.verify(dl).createDataStore(sql);
Mockito.verify(ds).retrieve();
Mockito.verify(dsIn).setItemString(1, "VIN", "VIN");
Mockito.verify(dsIn).setItemString(1, "MAKE", "MAKE");
Mockito.verify(dsIn).setItemString(1, "MODEL", "MODEL");
Mockito.verify(dsIn).setItemString(1, "EQUIPMENT_CLASS_CODE_ID", "EQUIPMENT_CLASS_CODE_ID");
Mockito.verify(dsIn).setItemString(1, "GARAGE_ASSIGNED", "GARAGE_ASSIGNED");
Mockito.verify(dsIn).setItemString(1, "EQ_LOCATION_ID", "EQ_LOCATION_ID");
Mockito.verify(dsIn).setItemString(1, "SALVAGE_VALUE", "SALVAGE_VALUE");
}

How to run dql search query in java?

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'

Java Simple Email Program in Eclipse

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

Neo4j - Browser Visualization Error

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.

Categories