package org.greenstone.atea; import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Properties; import org.apache.log4j.Logger; /** * https://www.tutorialspoint.com/mongodb/mongodb_java.htm * * TO COMPILE: * maori-lang-detection/src$ * javac -cp ".:../conf:../lib/*" org/greenstone/atea/MongoDBAccess.java * * TO RUN: * java -cp ".:../conf:../lib/*" org.greenstone.atea.MongoDBAccess */ public class MongoDBAccess { private static Logger logger = Logger.getLogger(org.greenstone.atea.MongoDBAccess.class.getName()); final static String HOST = "localhost"; final static int PORT = 27017; // mongodb port final static String PROPS_FILENAME = "config.properties"; final static String DB_NAME = "ateacrawldata"; private String USERNAME; private String PASSWORD; public MongoDBAccess() throws Exception { boolean success = false; // Read in the username and password from our props file Properties props = new Properties(); //File propsFile = new File(PROPS_FILENAME); //logger.debug("*** Conf props filename: " + propsFile.getAbsolutePath()); try { props.load(getClass().getClassLoader().getResourceAsStream(PROPS_FILENAME)); } catch(Exception e) { logger.error(e); } USERNAME = props.getProperty("mongodb.user", ""); if(USERNAME.equals("")) { USERNAME = "root"; logger.warn("WARNING: No sensible value for mongodb.user specified in " + PROPS_FILENAME + " defaulting to: " + USERNAME); } PASSWORD = props.getProperty("mongodb.pwd"); logger.debug("Got pwd: " + PASSWORD); if(PASSWORD != null && PASSWORD.equals("CHANGEME")) { success = false; throw new Exception("************ FATAL ERROR: Change DB password in properties file " + PROPS_FILENAME); } } public void connectToDB() throws Exception { // Creating a Mongo client MongoClient mongo = new MongoClient( HOST, PORT ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential(USERNAME, DB_NAME, PASSWORD.toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase(DB_NAME); //System.out.println("Credentials: "+ credential); } public static void main(String args[]) { try { MongoDBAccess mongodbCon = new MongoDBAccess(); //mongodbCon.connectToDB(); }catch(Exception e) { e.printStackTrace(); } } }