Connecting mongodb to java project in Eclipse IDE (MacOS) - java

I'm trying to connect mongodb to my java project in eclipse. I've mentioned the code I've written following some instructions on youtube and the official mongodb documentation.
Below are the .jar files I've added to the project build path.
Project Properties/Build Path/JRE Files
package mongoConnect;
import com.mongodb.*;
import com.mongodb.client.MongoClients;
#SuppressWarnings("unused")
public class MongoDatabase {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
com.mongodb.client.MongoClient client = MongoClients.create("mongodb://localhost:27017");
DB db1 = mongo.getDB("collegemanagementsystem");
//error saying "mongo cannot be resolved" in mongo.getDB
DBCollection col1 = db1.getCollection("Student");
BasicDBObject d1 = new BasicDBObject("name", "Sabiha").append("age", "23");
BasicDBObject d2 = new BasicDBObject("name", "Abdullah").append("age", "25");
col1.insert(d1);
col1.insert(d2);
DBCursor cur = col1.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
The Code
I do have mongodb compass installed if that helps. I also have a local database created in mongodb.
Mongodb Connection in Mongodb Compass
My questions are:
Is this method different to connecting by jdbc or is this the jdbc method for connecting database to java project?
How can I resolve this issue?
If this is not the jdbc method how can I connect mongodb to my java project with the jdbc method?
Error Message

Related

How to create a Fuseki SPARQL server connection in Android Studio

How can I create a connection to a Fuseki server through the android studio and upload my owl file into the Fuseki server in order to send SPARQL query and get the result?
I did it from the command-line and it works fine but I need to do it through the android studio.
I found some code but "DatasetAccessor and DatasetAccessorFactory" can not be resolved
public static void uploadRDF(File rdf, String serviceURI)
throws IOException {
// parse the file
Model m = ModelFactory.createDefaultModel();
try (FileInputStream in = new FileInputStream(rdf)) {
m.read(in, null, "RDF/XML");
}
// upload the resulting model
DatasetAccessor accessor = DatasetAccessorFactory
.createHTTP(serviceURI);
accessor.putModel(m);
}

Java JDBC-ODBC cannot load driver for Excel

import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionExample {
public static void main(String args[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
System.out.println("JDBC-ODBC driver failed to load.");
return;
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:abcdefg", "", "");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
This code always prints
"JDBC-ODBC driver failed to load."
I can't understand what the problem is.. I follow these steps:
go to c:\windows\sysWOW64\odbcad32.exe
system dsn tab - add -> Microsoft Excel Driver (*xls, *xlsx, *xlsm, *xlsb)
give Data Source Name abcdefg
Select Workbook -> go to myFile excel path and add it -> OK
and then run my code... where is the mistake?
The JDBC-ODBC Bridge is obsolete and has been removed from Java 8. If you need to manipulate an Excel document and you are unable (or unwilling) to downgrade your environment to Java 7 then you might want to investigate Apache POI.

Orient DB - Export database with Specified datatables

Im working with orient db where i have to export specified data tables using java. Here is the code im working with:
ODatabaseDocumentTx db = new ODatabaseDocumentTx("remote:localhost/sampleDB").open("admin", "admin");
try {
OCommandOutputListener listener = new OCommandOutputListener() {
#Override
public void onMessage(String iText) {
// System.out.print(iText);
}
};
Set<String> abcd = new HashSet<String>();
abcd.add("sample_demo1_OnlineShopping");
System.out.println(abcd);
ODatabaseExport export = new ODatabaseExport(db, "DataCont/Data.gz", listener);
export.setIncludeInfo(false);
export.setIncludeClusterDefinitions(false);
export.setIncludeSchema(false);
export.setIncludeIndexDefinitions(false);
export.setIncludeManualIndexes(false);
export.setIncludeClasses(abcd);
// export.exportRecords();
export.exportDatabase();
export.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
db.close();
}
The problem is, its not including any classes. Output file was like this:
{"records":[]}
But when i tries without the "setIncludeClasses" it prints all the classes available in the database. What would the issue for this problem. Thanks in advance.
Change this line to:
abcd.add("sample_demo1_OnlineShopping".toUpperCase());
I haven't found it in the documentation, but includeClasses is expecting classes in UpperCase (same for excludeClasses).
See the source code.

how to quickly create a test database for Cucumber-jvm?

I am using cucumber-jvm to test the behaviour of the legacy system I'm working on at work. I have to use Java 1.5 and Hibernate 3.3, upgrading is not an option. Since, during my tests, it stores some objects in the database, I have created a new development database.
What bothers me is that I have to manually drop the records (using a sql script) everytime I'll rerun my tests, or they'll fail. And anyone else wanting to run them would have to do the same. I want to quickly and automatically clean my test database, by either:
Creating an empty database and populating it with what I need, or
Using an already existing database, droping the records before starting the tests.
What I have so far: I'm using the cucumber-junit plugin, and the RunTests class redirects to my test database:
#RunWith(Cucumber.class)
#Cucumber.Options(
features = "test/resources/cucumber",
format = "html:target/cucumber"
)
public class RunTests {
private static Configuration configuration;
#BeforeClass
public static void preparaBase() {
// gets the mapped configuration to the db
configuration = HibernateUtil.getConfiguration();
configuration.setProperty("hibernate.connection.url", "test-db-url");
configuration.setProperty("hibernate.connection.username", "user");
configuration.setProperty("hibernate.connection.password", "pass");
// configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
// rebuilds the configuration using my test database
HibernateUtil.rebuildSessionFactory(configuration);
}
}
I have tried using the hibernate.hbm2ddl.auto property with the create-drop value and using the import.sql file to prepare the database, but it takes ages to start the tests and it seems that it's not detecting my import.sql file.
Sadly, using Maven and its excellent maven-sql-plugin is not an option (I have suggested a switch to Maven, to no avail). Is there an alternative?
I did it!
I used this ScriptRunner class as such:
#RunWith(Cucumber.class)
#Cucumber.Options(
features = "test/resources/cucumber",
format = "html:target/cucumber"
)
public class RunTests {
private static Configuration configuration;
String url = "test-db-url";
String user = "user";
String pass = "pass";
#BeforeClass
public static void preparaBase() {
// gets the mapped configuration to the db
configuration = HibernateUtil.getConfiguration();
configuration.setProperty("hibernate.connection.url", url);
configuration.setProperty("hibernate.connection.username", user);
configuration.setProperty("hibernate.connection.password", pass);
// rebuilds the configuration using my test database
HibernateUtil.rebuildSessionFactory(configuration);
// executes a script stored in test/resources/cucumber
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
ScriptRunner runner = new ScriptRunner(conn, false, true);
runner.runScript(new BufferedReader(new FileReader("test/resources/cucumber/db.sql")));
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}

mysql error with GWT

i am trying to create an sample apps using GWT and my code is below
public void onModuleLoad() {
VerticalPanel panel = new VerticalPanel();
MultiWordSuggestOracle oracle = new MultiWordSuggestOracle();
database data=new database();
Statement s1;
try {
s1 = data.conn.createStatement();
s1.executeQuery ("SELECT * FROM details LIMIT 10");
ResultSet rs = s1.getResultSet ();
while (rs.next ())
{
String name = rs.getString ("name");
oracle.add(name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SuggestBox suggestbox = new SuggestBox(oracle);
panel.add(new Label("Enter Country"));
panel.add(suggestbox);
panel.addStyleName("demo-panel-padded");
RootPanel.get("demo").add(panel);
}
and i have added the mysql-bin.jar connector in war/WEB_INF/lib/ and now i am getting an compilation error
17:39:52.353 [ERROR] [a] Line 28: No source code is available for type java.sql.Statement; did you forget to inherit a required module?
i need to know why i am getting this error and how can i rectify it
You cannot use server-side code (java.sql.* in your case) in GWT client side modules.
You should make an RPC call to the server. The server callback should fetch the data from your database, and send it back to your GWT client.
Using Eclipse with the google plugin, you can create a new "Web Application Project". More information about the plugin can be found here: http://code.google.com/eclipse/
You will get a simple project that contains a GreetingService which receives a String from the client side and responds with "Hello" + string. For your example you would have to add the code that reads from the DB in the GreetingServiceImpl class and then use the response (which can be a String[] containing the name read from DB) on the client side to populate the SuggestionBox

Categories