Using MongoDB and Java WITHOUT gradle, maven or an IDE - java

I want to use MongoDB in java, without an IDE or additional tools. I have downloaded mongo-java-driver-3.12.8.jar, and put it in the same folder as my helloMongo.java file.
I then have tried to run it with:
javac -cp "mongo-java-driver.jar" helloMongo.java
java -cp "mongo-java-driver.jar" helloMongo
Only to get that it cannot find the main class.
Then I tried, assuming the main path had been lost in javas braindead implementation:
javac -cp ".;mongo-java-driver.jar" helloMongo.java
java -cp ".;mongo-java-driver.jar" helloMongo
still to no luck. Then I tried:
javac -cp ".;/mongo-java-driver.jar" helloMongo.java
java -cp ".;/mongo-java-driver.jar" helloMongo
And a hundred other variants, and still no luck.
Is an IDE and Gradle essentially required to use Mongo with Java?
package com.javatpoint.java.mongo.db;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class JavaMongoDemo {
public static void main(String[] args){
try{
//---------- Connecting DataBase -------------------------//
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//---------- Creating DataBase ---------------------------//
MongoDatabase db = mongoClient.getDatabase("javatpoint");
//---------- Creating Collection -------------------------//
MongoCollection<Document> table = db.getCollection("employee");
//---------- Creating Document ---------------------------//
Document doc = new Document("name", "Peter John");
doc.append("id",12);
//----------- Inserting Data ------------------------------//
table.insertOne(doc);
}catch(Exception e){
System.out.println(e);
}
}
}

If your package is com.javatpoint.java.mongo.db, then your class has to be in
./com/javatpoint/java/mongo/db
and assuming you leave the Mongo jar in the same directory as your source,
your java command must be
java -cp ./com/javatpoint/java/mongo/db/mongo-java-driver.jar com.javatpoint.java.mongo.db.helloMongo

Related

Use the Mysql ClusterJ jar file to connect to NDB cluster

I followed the instruction in the ClusterJ tutorial here to connect to MySQL NDB cluster using the NDB api. Below is a sample code of what I am doing right now:
Main.java
import com.mysql.clusterj.ClusterJHelper;
import com.mysql.clusterj.SessionFactory;
import com.mysql.clusterj.Session;
import com.mysql.clusterj.Query;
import com.mysql.clusterj.query.QueryBuilder;
import com.mysql.clusterj.query.QueryDomainType;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.*;
import java.util.Properties;
import java.util.List;
public class Main {
public static void main (String[] args) throws
java.io.FileNotFoundException,java.io.IOException {
// Load the properties from the clusterj.properties file
File propsFile = new File("clusterj.properties");
InputStream inStream = new FileInputStream(propsFile);
Properties props = new Properties();
props.load(inStream);
//Used later to get user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Create a session (connection to the database)
SessionFactory factory = ClusterJHelper.getSessionFactory(props);
Session session = factory.getSession();
// Create and initialize an Employee
Employee newEmployee = session.newInstance(Employee.class);
newEmployee.setId(988);
newEmployee.setFirst("John");
newEmployee.setLast("Jones");
newEmployee.setStarted("1 February 2009");
newEmployee.setDepartment(666);
// Write the Employee to the database
session.persist(newEmployee);
}
}
I encounter the below error when I am trying to run this:
java.lang.UnsatisfiedLinkError: no ndbclient in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at com.mysql.clusterj.tie.ClusterConnectionServiceImpl.loadSystemLibrary(ClusterConnectionServiceImpl.java:68)
at com.mysql.clusterj.tie.ClusterConnectionServiceImpl.create(ClusterConnectionServiceImpl.java:87)
at com.mysql.clusterj.core.SessionFactoryImpl.createClusterConnection(SessionFactoryImpl.java:335)
at com.mysql.clusterj.core.SessionFactoryImpl.createClusterConnectionPool(SessionFactoryImpl.java:288)
at com.mysql.clusterj.core.SessionFactoryImpl.<init>(SessionFactoryImpl.java:211)
at com.mysql.clusterj.core.SessionFactoryImpl.getSessionFactory(SessionFactoryImpl.java:146)
at com.mysql.clusterj.core.SessionFactoryServiceImpl.getSessionFactory(SessionFactoryServiceImpl.java:36)
at com.mysql.clusterj.core.SessionFactoryServiceImpl.getSessionFactory(SessionFactoryServiceImpl.java:27)
at com.mysql.clusterj.ClusterJHelper.getSessionFactory(ClusterJHelper.java:72)
at com.mysql.clusterj.ClusterJHelper.getSessionFactory(ClusterJHelper.java:57)
at com.pkg.mysql.Main.main(Main.java:27)
The error occurs since ClusterJ requires the ndb_engine.so file in the java classpath.
Refer Link: http://ftp.nchu.edu.tw/MySQL/doc/ndbapi/en/mccj-getting.html
I could run the program once I specify the path.
# steps to compile and run the ndb java program on linux
javac -classpath /home/user1/clusterj-7.6.8.jar:. Main.java Employee.java
java -classpath /home/user1/clusterj-7.6.8.jar:. -Djava.library.path=/usr/lib64/mysql Main
I still could not find a way to resolve it on Windows environment.
Add as vm arguments or running including following path
For Mac:
-Djava.library.path="/usr/local/mysql-{cluster-version}/lib/"
For Windows:
search for library path and replace inside double quotes

How to connect to rexster server over rexpro within the java code?

I have a rexster server running locally on my machine on port 8984. I want to connect to my graph dadabase (orientdb) and execute gremlin scripts within my java code. I couldn't find any good example or tutorial on doing that.
Here is my code:
import com.tinkerpop.rexster;
import com.tinkerpop.rexster.*;
public class Orient {
public static void main(String[] args) {
RexsterClient client = RexsterClientFactory.open("localhost", 8984);
String script = String.format("g=rexster.getGraph('%s');g.v('%s').map", "test_test", "9:6267");
List<Map<String, Object>> results = client.execute(script);
Map<String, Object> map = results.get(0);
System.out.println(map.get("name"));
}
}
when I try to compile my code like :
$javac -cp rexster-protocol-2.6.0.jar Orient.java
I get this :
Orient.java:1: error: package com.tinkerpop does not exist
import com.tinkerpop.rexster;
^
Orient.java:2: error: package com.tinkerpop.rexster does not exist
import com.tinkerpop.rexster.*;
^
Orient.java:7: error: cannot find symbol
RexsterClient client = RexsterClientFactory.open("localhost", 8984);
^
symbol: class RexsterClient
location: class Orient
what am I doing wrong? where can I get the dependencies (.jar) files. if any needed.
Thanks
You need to add all dependent jar files in classpath to compile
http://mvnrepository.com/artifact/com.tinkerpop.rexster/rexster-protocol/2.6.0
You would better use maven or gradle build tool rather downloading all the jar files and typing compile command manually.

Getting the following error - No suitable driver found for jdbc:postgresql://localhost: 5432/testDBMS

I get back an error indicating java.sql.SQLException: No suitable driver found for
jdbc:postgresql://localhost:
5432/testDBMS
import java.sql.*;
import java.util.*;
public class JdbcPostgresqlConnection {
public static void main(String[] args) {
Connection conn3 = null;
try {
String dbURL3 = "jdbc:postgresql://localhost:5432/testDBMS";
Properties parameters = new Properties();
parameters.put("user", "pgmrHere");
parameters.put("password", "111111");
conn3 = DriverManager.getConnection(dbURL3, parameters);
}
catch (SQLException ex) { ex.printStackTrace(); }
}
}
java -cp . JdbcPostgresqlConnection
So, clearly, the only thing that is in the classpath is the current directory (.). The postgresql driver jar is not. You need to add it to the classpath:
java -cp .:/path/to/driver.jar JdbcPostgresqlConnection
on Linux/MacOS, or
java -cp .;c:\path\to\driver.jar JdbcPostgresqlConnection
on Windows.
The syntax to compile was - java -cp .;"C:\Program Files\PostgreSQL\9.3\lib\postgresql-9.3-1102.jdbc4.jar" JdbcPostgresqlConnection. Note 2 things; the quotes around the jar specification and the jar files cannot be in a folder with a space in the name. This is normally not the case on *nix system, but is often encountered in Windows systems. Note too, that when I put the jar file in the same folder with the java program I could eliminate the double quotes - java -cp .;C:\AZ_Fantasy5\postgresql-9.3-1102.jdbc4.jar JdbcPostgresqlConnection. Special thanks to JB Nizet for pointing out this situation.
As the error says java -cp . JdbcPostgresqlConnection java.sql.SQLException:
No suitable driver found for jdbc:postgresql://localhost: 5432/testDBMS
Which means you didnot include the postgresql.jar in your classpath
Try executing like this and I'm assuming it is Windows OS by seeing your error
java -cp .;pathOfYourDriverjar/postgresql.jar JdbcPostgresqlConnection
Did you not load the driver in your code? Either define the jdbc.drivers property setting it to org.postgresql.Driver or add Class.forName("org.postgresql.Driver") to your code.

How to access the remote .mdb file in shared folder using java and jackcess from linux machine

This is my first post. I am trying to open the remote .mdb file which is in shared folder in Windows machine from the linux machine using jackcess lib. and set the table values in busineess object. I wrote the below code.
Scenario 1 : I have run the code from windows machine it is working fine. Scenario 2 : If i run the code from linux machine it is getting file not found exception. Hope it should be small mistake. Please correct me what am missing here .
package com.gg.main;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
import com.penske.model.Login;
public class Test {
public static void main(String args[]){
Table table = null;
Database db = null;
Login login = null;
ArrayList<Login> rowList = null;
try {
rowList = new ArrayList();
db = Database.open(new File("//aa.bb.com/file/access.mdb"));
table = db.getTable("Maintenance");
System.out.println(Database.open(new File("//aa.bb.com/file/access.mdb"))
.getTable("Maintenance").getColumns());
for(Map<String, Object> row : table) {
login = new Login();
if(row.get("Req_ID")!=null){
login.setId(row.get("Req_ID").toString());
}
if(row.get("Name")!=null){
login.setName(row.get("Name").toString());
}if(row.get("Loc")!=null){
login.setLoc(row.get("Loc").toString());
}
rowList.add(login);
}
login.setRowList(rowList);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Linux does not have native support for Windows' UNC path, as you use them here:
new File("//aa.bb.com/file/access.mdb")
You'll have to mount the remote filesystem somewhere in your Linux filesystem where your program can access it and then replace the paths in your program to use that local filesystem path, using smbfs or something like it. It's been a long time since I've had to interact with Windows machines, but it should go something like this:
mount -t smbfs -o username=foo,password=bar //aa.bb.com/file /mnt/whatever_you_choose_to_name_it
See the manpage for smbmount for details.
Of course, if your program is supposed to start automatically eg. as part of the system booting, you'll have to see to it that the filesystem is automatically mounted as well. See fstab(5).

Trouble with installing JDBC for Postgres

I would like to use JDBC. My code:
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
public class test {
Connection conn;
public test() throws ClassNotFoundException, SQLException{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost/tb";
Properties props = new Properties();
props.setProperty("user","user");
props.setProperty("password","passwd");
conn = DriverManager.getConnection(url, props);
System.out.println(conn.isClosed());
}
public static void main(String[] args) {
try{
test t = new test();
} catch (Exception e){
e.printStackTrace();
}
}
}
My soft: postgres 9.1, java 1.7
My try:
ziel#gad ~/java/test $ ls
postgresql-9.1-902.jdbc4.jar test.java
ziel#gad ~/java/test $ javac test.java
ziel#gad ~/java/test $ java -cp postgresql-9.1-902.jdbc4.jar test
Error: Could not find or load main class test
According to people from google this should load the driver. What am I doing wrong?
Use java -cp postgresql-9.1-902.jdbc4.jar:. test under Linux / Unix / OS X
Thats because when you did -cp postgresql-9.1-902.jdbc4.jar, you defined the jar postgresql-9.1-902.jdbc4.jar as the only location of your class files and the class test isn't in this jar. To resolve the problem you have to execute this cmd java -cp postgresql-9.1-902.jdbc4.jar;. test
i guess you are using linux os, so try this java -cp postgresql-9.1-902.jdbc4.jar:. test.
In windows java -cp postgresql-9.1-902.jdbc4.jar;. test
Execute following on Linux machine
javac -cp '.:postgresql-9.1-901.jdbc4.jar' postgresjavatest.java
java -cp '.:postgresql-9.1-901.jdbc4.jar' postgresjavatest
make sure jar file is on same location where command is fired.

Categories