/** Connect the instance. */
  public synchronized MongoClient connect() {
    if (m == null) {
      Builder options = new MongoClientOptions.Builder();
      options.connectionsPerHost(maxConnections);
      options.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockMultiplier);

      try {

        // Connect to replica servers if given. Else the standard way to one server.
        if (replicaServers != null && replicaServers.size() > 0) {
          m = new MongoClient(replicaServers, options.build());
        } else {
          ServerAddress address = new ServerAddress(host, port);
          m = new MongoClient(address, options.build());
        }
        db = m.getDB(database);
        db.setWriteConcern(WriteConcern.SAFE);

        // Try to authenticate if configured.
        if (useAuth) {
          if (!db.authenticate(username, password.toCharArray())) {
            throw new RuntimeException(
                "Could not authenticate to database '"
                    + database
                    + "' with user '"
                    + username
                    + "'.");
          }
        }
      } catch (UnknownHostException e) {
        throw new RuntimeException("Cannot resolve host name for MongoDB", e);
      }
    }
    return m;
  }
예제 #2
0
  @Override
  public void reset() {
    super.reset();
    try {
      String ritePropertiesFilename = Rite.getInstance().getProperty(Rite.PropertyKeys.HOST);
      Properties hostProps = new Properties();
      hostProps.load(new FileInputStream(ritePropertiesFilename));
      String hostname = hostProps.getProperty("hostname");
      int port = Integer.parseInt(hostProps.getProperty("port"));
      String dbname = hostProps.getProperty("dbname");
      boolean auth = Boolean.parseBoolean(hostProps.getProperty("auth"));
      Mongo mongo = new Mongo(hostname, port);
      DB db = mongo.getDB(dbname);
      if (auth) {
        String user = hostProps.getProperty("user");
        String pass = hostProps.getProperty("pass");
        db.authenticate(user, pass.toCharArray());
      }

      GridFS gfs = new GridFS(db);
      String filename = getFileName();
      File f = new File(filename);
      f.delete();
      gfs.remove(filename);
      mongo.close();
    } catch (Exception e) {
      this.fail();
      this.complete();
    }
  }
  /*
   * mongo.local.hostname=localhost
   * mongo.local.port=27017
   * mongo.remote.hostname=
   * mongo.remote.port=25189
   * mongo.remote.username=
   * mongo.remote.password=
   */
  private static DB getDb() {
    String userName = play.Configuration.root().getString("mongo.remote.username");
    String password = play.Configuration.root().getString("mongo.remote.password");
    boolean local = true;

    String localHostName = play.Configuration.root().getString("mongo.local.hostname");
    Integer localPort = play.Configuration.root().getInt("mongo.local.port");

    String remoteHostName = play.Configuration.root().getString("mongo.remote.hostname");
    Integer remotePort = play.Configuration.root().getInt("mongo.remote.port");

    Mongo m;
    DB db = null;
    if (local) {
      String hostname = localHostName;
      int port = localPort;
      try {
        m = new Mongo(hostname, port);
        db = m.getDB("db");
      } catch (Exception e) {
        Logger.error("Exception while intiating Local MongoDB", e);
      }
    } else {
      String hostname = remoteHostName;
      int port = remotePort;
      try {
        m = new Mongo(hostname, port);
        db = m.getDB("db");
        boolean auth = db.authenticate(userName, password.toCharArray());
      } catch (Exception e) {
        Logger.error("Exception while intiating Local MongoDB", e);
      }
    }
    return db;
  }
예제 #4
0
파일: MongoDB.java 프로젝트: shlee322/owl
  boolean DBStart() {
    try {
      m = new Mongo(Controller.MongoDB_IP);
      SendDBName = "SendMail";
      SendMailDB = m.getDB(SendDBName);
      SendMailDB.authenticate("owl", "70210".toCharArray());

      UserDB = m.getDB("User");
      UserDB.authenticate("owl", "70210".toCharArray());

      return true;

    } catch (Exception e) {
      return false;
    }
  }
예제 #5
0
  private DB getDb(DbConfigProvider configProvider)
      throws UnknownHostException, MongoException, FileNotFoundException {
    Mongo mongo = getMongoConnection(configProvider);
    DB result = mongo.getDB(configProvider.getDbName());

    if (configProvider.isSecured()) {
      result.authenticate(configProvider.getUser(), configProvider.getPassword().toCharArray());
    }

    return result;
  }
예제 #6
0
파일: MongoDB.java 프로젝트: shlee322/owl
  // 디비 시작 (클라에서 로그온 했을때 무조건 이 메소드는 실행 해야함!)
  boolean LogIn(String User) {
    try {
      UserName = User;
      AdressDB = m.getDB(UserName);
      AdressDB.authenticate("owl", "70210".toCharArray());

      return true;
    } catch (Exception e) {
      return false;
    }
  }
 public void start() {
   try {
     mongo = new Mongo(host, port);
     db = mongo.getDB(dbname);
     if (username != null
         && password != null
         && !db.authenticate(username, password.toCharArray())) {
       throw new RuntimeException("auth");
     }
   } catch (Exception e) {
     throw new RuntimeException();
   }
 }
예제 #8
0
 @Inject
 public MongoStore(SeyrenConfig seyrenConfig) {
   try {
     String uri = seyrenConfig.getMongoUrl();
     MongoURI mongoUri = new MongoURI(uri);
     DB mongo = mongoUri.connectDB();
     if (mongoUri.getUsername() != null) {
       mongo.authenticate(mongoUri.getUsername(), mongoUri.getPassword());
     }
     this.mongo = mongo;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
예제 #9
0
파일: Main.java 프로젝트: aditya7/TrendRR
  /** @throws NullPointerException */
  public static void PrintHighestJerseyNumber() throws NullPointerException {
    Mongo m = null;
    try {
      m = new Mongo("dbh63.mongolab.com", 27637);
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (MongoException e) {
      e.printStackTrace();
    }
    DB trendrr = m.getDB("trendrr");
    /* authentication line */
    trendrr.authenticate("", "".toCharArray());
    DBCollection players = trendrr.getCollection("players");

    BasicDBObject query = new BasicDBObject();
    query.put("team", "jets");
    query.put("position", "wr");

    DBCursor cur = players.find(query);

    int maxJerseyNumber = 0;
    String playerName = "";

    while (cur.hasNext()) {
      DBObject playerDetails = cur.next();
      String nameAndNumber = playerDetails.get("name").toString();
      String NameNumberTokens[] = nameAndNumber.split(",");
      try {
        if (NameNumberTokens.length != 2) {
          System.out.println("Invalid name field in the database");
          System.out.println(
              "Name: " + NameNumberTokens[0] + " Jersey Number: " + NameNumberTokens[1]);
        }
      } catch (NullPointerException e) {
        System.out.println("NULL value in name field " + e);
        continue;
      }
      try {
        if (maxJerseyNumber < Integer.parseInt(NameNumberTokens[1].trim())) {
          maxJerseyNumber = Integer.parseInt(NameNumberTokens[1].trim());
          playerName = NameNumberTokens[0];
        }
      } catch (NumberFormatException e) {
        System.out.println("Invalid data in name field " + e);
        continue;
      }
    }
    System.out.println("Player Name: " + playerName);
  }
예제 #10
0
 /**
  * Initializes database if it exists and create it otherwise.
  *
  * @param dbName
  */
 protected void initDatabase() {
   db = mongo.getDB(CommonsProperties.getMongodbDb());
   if (!mongo.getDatabaseNames().contains(CommonsProperties.getMongodbDb())) {
     BasicDBObject commandArguments = new BasicDBObject();
     commandArguments.put("user", CommonsProperties.getMongodbUser());
     commandArguments.put("pwd", CommonsProperties.getMongodbPass());
     String[] roles = {"readWrite"};
     commandArguments.put("roles", roles);
     BasicDBObject command = new BasicDBObject("createUser", commandArguments);
     db.command(command);
   }
   boolean auth =
       db.authenticate(
           CommonsProperties.getMongodbUser(), CommonsProperties.getMongodbPass().toCharArray());
 }
 private DB getDatabase(Mongo mongo, String username, String password, String database)
     throws ConnectionException {
   DB db = mongo.getDB(database);
   if (password != null) {
     Validate.notNull(username, "Username must not be null if password is set");
     if (!db.isAuthenticated()) {
       if (!db.authenticate(username, password.toCharArray())) {
         throw new ConnectionException(
             ConnectionExceptionCode.INCORRECT_CREDENTIALS,
             null,
             "Couldn't connect with the given credentials");
       }
     }
   }
   return db;
 }
  /*
   * (non-Javadoc)
   *
   * @see org.ow2.play.service.registry.api.Registry#init()
   */
  @Override
  @WebMethod
  public void init() throws RegistryException {
    logger.info("Initializing registry service");

    if (initialized) {
      logger.info("Already initialized");
      return;
    }

    if (mongo != null) {
      close();
    }

    if (properties != null) {
      logger.fine("Getting properties from " + properties);
      hostname = properties.getProperty("mongo.hostname", DEFAULT_MONGO_DB_HOSTNAME);
      port = properties.getProperty("mongo.port", DEFAULT_MONGO_DB_PORT);
      userName = properties.getProperty("mongo.username", userName);
      password = properties.getProperty("mongo.password", password);
      collectionName = properties.getProperty("mongo.collection", DEFAULT_MONGO_DB_COLLECTION_NAME);
    }

    if (logger.isLoggable(Level.INFO)) {
      logger.info(
          String.format(
              "Connection to %s %s with credentials %s %s", hostname, port, userName, "******"));
    }

    List<ServerAddress> addresses = getServerAddresses(hostname, port);
    logger.fine("Got server addresses " + addresses);
    mongo = getMongo(addresses);

    DB database = getDatabase(mongo, databaseName);

    if (userName != null && userName.trim().length() > 0) {
      if (!database.authenticate(userName, password.toCharArray())) {
        throw new RuntimeException("Unable to authenticate with MongoDB server.");
      }

      // Allow password to be GCed
      password = null;
    }

    setCollection(database.getCollection(collectionName));
    initialized = true;
  }
예제 #13
0
  public static void main(String[] args)
      throws IOException, URISyntaxException, InterruptedException {
    final int port = System.getenv("PORT") != null ? Integer.valueOf(System.getenv("PORT")) : 8080;
    final URI baseUri = UriBuilder.fromUri("http://0.0.0.0/").port(port).build();
    final Application application =
        Application.builder(
                ResourceConfig.builder().packages(BarServer.class.getPackage().getName()).build())
            .build();
    application.addModules(new JsonJacksonModule());
    final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, application);
    httpServer
        .getServerConfiguration()
        .addHttpHandler(new StaticHttpHandler("src/main/webapp"), CONTENT_PATH);

    for (NetworkListener networkListener : httpServer.getListeners()) {
      if (System.getenv("FILE_CACHE_ENABLED") == null) {
        networkListener.getFileCache().setEnabled(false);
      }
    }

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                httpServer.stop();
              }
            });

    MongoURI mongolabUri =
        new MongoURI(
            System.getenv("MONGOLAB_URI") != null
                ? System.getenv("MONGOLAB_URI")
                : "mongodb://127.0.0.1:27017/hello");
    Mongo m = new Mongo(mongolabUri);
    mongoDB = m.getDB(mongolabUri.getDatabase());
    if ((mongolabUri.getUsername() != null) && (mongolabUri.getPassword() != null)) {
      mongoDB.authenticate(mongolabUri.getUsername(), mongolabUri.getPassword());
    }

    contentUrl = System.getenv("CONTENT_URL") != null ? System.getenv("CONTENT_URL") : CONTENT_PATH;

    Thread.currentThread().join();
  }
  private synchronized void connectToMongo() {

    try {
      client = new MongoClient(config.getHost(), config.getPort().intValue()).getDB(config.getDb());
    } catch (UnknownHostException e) {
      e.printStackTrace();
      return;
    }

    if (!Strings.isNullOrEmpty(config.getUser()) && !Strings.isNullOrEmpty(config.getPassword()))
      client.authenticate(config.getUser(), config.getPassword().toCharArray());

    if (!client.collectionExists(config.getCollection())) {
      client.createCollection(config.getCollection(), null);
    }
    ;

    collection = client.getCollection(config.getCollection());
  }
예제 #15
0
  @Override
  public Operation call() throws Exception {
    try {
      String ritePropertiesFilename = Rite.getInstance().getProperty(Rite.PropertyKeys.HOST);
      Properties hostProps = new Properties();
      hostProps.load(new FileInputStream(ritePropertiesFilename));
      String hostname = hostProps.getProperty("hostname");
      int port = Integer.parseInt(hostProps.getProperty("port"));
      String dbname = hostProps.getProperty("dbname");
      boolean auth = Boolean.parseBoolean(hostProps.getProperty("auth"));
      Mongo mongo = new Mongo(hostname, port);
      DB db = mongo.getDB(dbname);
      if (auth) {
        String user = hostProps.getProperty("user");
        String pass = hostProps.getProperty("pass");
        db.authenticate(user, pass.toCharArray());
      }

      GridFS gfs = new GridFS(db);
      String filename = getFileName();
      File f = new File(filename);
      if (!f.exists()) {
        throw new Exception("The file " + filename + " does not exist locally!");
      }
      int filesInDb = gfs.find(filename).size();
      if (filesInDb > 0) {
        throw new Exception("The file " + filename + " already exists in the database!");
      }
      GridFSInputFile gsampleFile = gfs.createFile(f);
      gsampleFile.setFilename(f.getName());
      gsampleFile.save();
      mongo.close();
    } catch (Exception e) {
      this.setProperty(
          GenericOperation.PropertyKeys.ERROR, OperationUtilities.getStackTraceAsString(e));
      this.fail();
      this.complete();
      return this;
    }
    this.complete();
    return this;
  }
  private void init() {
    try {
      Mongo m = new Mongo(mongoHost, mongoPort);
      DB db = m.getDB("mtg");
      db.authenticate("mtg", "mtg".toCharArray());
      cardCollection = db.getCollection(collectionName);

      graphDb = new RestGraphDatabase(HEROKU_NEO4J, herokuUser, herokuPassword);
      Iterable<Node> allNodes = graphDb.getAllNodes();
      Iterator<Node> it = allNodes.iterator();
      while (it.hasNext()) {
        Node node = it.next();
        if (node.hasProperty("name")) {
          cardNodes.put(node.getProperty("name").toString(), node);
        }
      }
      System.out.println("There are " + cardNodes.size() + " card nodes");
      registerShutdownHook(graphDb);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
예제 #17
0
  @SuppressWarnings("unchecked")
  private void initMorphia_() {
    Properties c = Play.configuration;

    String dbName = c.getProperty(PREFIX + "name");
    if (null == dbName) {
      warn("mongodb name not configured! using [test] db");
      dbName = "test";
    }
    DB db = mongo_.getDB(dbName);
    if (c.containsKey(PREFIX + "username") && c.containsKey(PREFIX + "password")) {
      String username = c.getProperty(PREFIX + "username");
      String password = c.getProperty(PREFIX + "password");
      if (!db.isAuthenticated() && !db.authenticate(username, password.toCharArray())) {
        throw new RuntimeException("MongoDB authentication failed: " + dbName);
      }
    }

    String loggerClass = c.getProperty("morphia.logger");
    Class<? extends LogrFactory> loggerClazz = SilentLogrFactory.class;
    if (null != loggerClass) {
      final Pattern P_PLAY = Pattern.compile("(play|enable|true|yes|on)", Pattern.CASE_INSENSITIVE);
      final Pattern P_SILENT =
          Pattern.compile("(silent|disable|false|no|off)", Pattern.CASE_INSENSITIVE);
      if (P_PLAY.matcher(loggerClass).matches()) {
        loggerClazz = PlayLogrFactory.class;
      } else if (!P_SILENT.matcher(loggerClass).matches()) {
        try {
          loggerClazz = (Class<? extends LogrFactory>) Class.forName(loggerClass);
        } catch (Exception e) {
          warn(
              "Cannot init morphia logger factory using %s. Use PlayLogrFactory instead",
              loggerClass);
        }
      }
    }
    loggerRegistered_ = false;
    MorphiaLoggerFactory.reset();
    MorphiaLoggerFactory.registerLogger(loggerClazz);
    morphia_ = new Morphia();
    loggerRegistered_ = true;
    ds_ = morphia_.createDatastore(mongo_, dbName);
    dataStores_.put(dbName, ds_);

    String uploadCollection = c.getProperty("morphia.collection.upload", "uploads");

    if (getBooleanProperty("gridfs.enabled")) {
      gridfs = new GridFS(MorphiaPlugin.ds().getDB(), uploadCollection);
    }

    morphia_
        .getMapper()
        .addInterceptor(
            new AbstractEntityInterceptor() {
              @Override
              public void preLoad(Object ent, DBObject dbObj, Mapper mapr) {
                if (ent instanceof Model) {
                  PlayPlugin.postEvent(MorphiaEvent.ON_LOAD.getId(), ent);
                  ((Model) ent)._h_OnLoad();
                }
              }

              @Override
              public void postLoad(Object ent, DBObject dbObj, Mapper mapr) {
                if (ent instanceof Model) {
                  Model m = (Model) ent;
                  PlayPlugin.postEvent(MorphiaEvent.LOADED.getId(), ent);
                  m._h_Loaded();
                }
              }
            });
  }
  private static DB doGetDB(
      Mongo mongo, String databaseName, UserCredentials credentials, boolean allowCreate) {

    DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo);

    // Do we have a populated holder and TX sync active?
    if (dbHolder != null
        && !dbHolder.isEmpty()
        && TransactionSynchronizationManager.isSynchronizationActive()) {

      DB db = dbHolder.getDB(databaseName);

      // DB found but not yet synchronized
      if (db != null && !dbHolder.isSynchronizedWithTransaction()) {

        LOGGER.debug(
            "Registering Spring transaction synchronization for existing MongoDB {}.",
            databaseName);

        TransactionSynchronizationManager.registerSynchronization(
            new MongoSynchronization(dbHolder, mongo));
        dbHolder.setSynchronizedWithTransaction(true);
      }

      if (db != null) {
        return db;
      }
    }

    // Lookup fresh database instance
    LOGGER.debug("Getting Mongo Database name=[{}]", databaseName);

    DB db = mongo.getDB(databaseName);
    boolean credentialsGiven = credentials.hasUsername() && credentials.hasPassword();

    synchronized (db) {
      if (credentialsGiven && !db.isAuthenticated()) {

        String username = credentials.getUsername();
        String password = credentials.hasPassword() ? credentials.getPassword() : null;

        if (!db.authenticate(username, password == null ? null : password.toCharArray())) {
          throw new CannotGetMongoDbConnectionException(
              "Failed to authenticate to database ["
                  + databaseName
                  + "], username = ["
                  + username
                  + "], password = ["
                  + password
                  + "]",
              databaseName,
              credentials);
        }
      }
    }

    // TX sync active, bind new database to thread
    if (TransactionSynchronizationManager.isSynchronizationActive()) {

      LOGGER.debug(
          "Registering Spring transaction synchronization for MongoDB instance {}.", databaseName);

      DbHolder holderToUse = dbHolder;

      if (holderToUse == null) {
        holderToUse = new DbHolder(databaseName, db);
      } else {
        holderToUse.addDB(databaseName, db);
      }

      TransactionSynchronizationManager.registerSynchronization(
          new MongoSynchronization(holderToUse, mongo));
      holderToUse.setSynchronizedWithTransaction(true);

      if (holderToUse != dbHolder) {
        TransactionSynchronizationManager.bindResource(mongo, holderToUse);
      }
    }

    // Check whether we are allowed to return the DB.
    if (!allowCreate && !isDBTransactional(db, mongo)) {
      throw new IllegalStateException(
          "No Mongo DB bound to thread, "
              + "and configuration does not allow creation of non-transactional one here");
    }

    return db;
  }
예제 #19
0
파일: signup.java 프로젝트: nkistler/fourup
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String verifypassword = request.getParameter("verifypassword");
    Map<String, String> myResponse = new HashMap<String, String>();
    PrintWriter out = response.getWriter();
    if (email.matches(
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) // make sure email is properly
    // formatted
    {
      try {

        MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
        DB db = mongoURI.connectDB(); // instance of databse
        db.authenticate(mongoURI.getUsername(), mongoURI.getPassword()); // authenticates d
        // Set<string> accounts = db.getCollectionName("accounts");
        // Mongo mongo = new Mongo("localhost", 27017); //creates new instance of mongo
        // DB db = mongo.getDB("fourup"); //gets fourup database
        DBCollection accounts = db.getCollection("accounts"); // creates collection for accounts	
        BasicDBObject query = new BasicDBObject(); // creates a basic object named query
        query.put("email", email); // sets email to email
        DBCursor cursor = accounts.find(query);
        if (cursor.size() > 0) // check if email has already been registered
        {
          myResponse.put("Status", "Error");
          myResponse.put("Error", "Account already exists using this email address.");
        } else // since email doesn't currently exist in DB, go ahead and register user
        {
          if (password.equals(
              verifypassword)) // check that both of the passwords entered match each other
          {
            BasicDBObject document = new BasicDBObject();
            int salt = getSalt();
            String hpass = passwrdHash(password, salt);
            document.put("email", email);
            document.put("salt", salt);
            document.put("password", hpass); // this is where we need to hash the password
            accounts.insert(document);
            myResponse.put("Status", "Sucess");
            myResponse.put("Sucess", "Account has been Created");
            AccountObject user = new AccountObject(email, hpass);
            // set session
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", email);
            // return cookie
            Cookie cookie = new Cookie("fourupCookie", email); // add the login information here
            response.addCookie(cookie);
            // redirect to homepage
            String message = "this is a test";
            myResponse.put("html", "<html></html>");
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            // response.sendRedirect("index.html"); //should add check to index page for cookie with
            // login information
          } else {
            myResponse.put("Status", "Failed");
            myResponse.put("Failed", "Passwords do not match.");
          }
        }

      } catch (MongoException e) {

        out.write(e.getMessage());
      }
    } else {
      myResponse.put("Status", "Invalid");
      myResponse.put(
          "Invalid", "The email address has not been entered correctly."); // should output error
    }

    String strResponse = new Gson().toJson(myResponse);
    response.getWriter().write(strResponse);
    response.getWriter().close();
  }