private void parseOptionsFromURI(MongoClientURI uri, Map<String, String> options) {
   if (uri.getUsername() != null && uri.getUsername().isEmpty() == false) {
     options.put(MongoDumpOptions.USERNAME, uri.getUsername());
   }
   if (uri.getPassword() != null && uri.getPassword().length > 0) {
     options.put(MongoDumpOptions.PASSWORD, new String(uri.getPassword()));
   }
   if (uri.getHosts() != null && uri.getHosts().isEmpty() == false) {
     final String hostWithPort = uri.getHosts().get(0);
     final Pattern p = Pattern.compile("(.*)(:(\\d+))?");
     final Matcher m = p.matcher(hostWithPort);
     if (m.matches()) {
       final String host = m.group(1);
       final String port = m.group(3);
       if (host.isEmpty() == false) {
         options.put(MongoDumpOptions.HOST, host);
         if (port != null) {
           options.put(MongoDumpOptions.PORT, port);
         }
       }
     }
   }
   if (uri.getDatabase() != null && uri.getDatabase().isEmpty() == false) {
     options.put(MongoDumpOptions.DB, uri.getDatabase());
   }
   if (uri.getCollection() != null && uri.getCollection().isEmpty() == false) {
     options.put(MongoDumpOptions.COLLECTION, uri.getCollection());
   }
 }
Esempio n. 2
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds047752.mlab.com:47752/ase_lab7");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");

    BasicDBObject query = new BasicDBObject().append("username", "Ram");
    query.put("name", "Ram"); // request.getParameter("name"));
    query.put("password", "password"); // request.getParameter("password"));
    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("name", "SreeRam");
    users.update(query, newDocument);

    DBCursor docs = users.find(query);
    response.getWriter().write(docs.toArray().toString());

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
      buffer.append(line);
    }
    String data = buffer.toString();
    System.out.println(data);

    JSONObject params = new JSONObject(data);
    String email = (String) params.get("email");
    String password = (String) params.get("password");

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds011459.mlab.com:11459/farmville");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("logindetails");

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.append("$set", new BasicDBObject().append("password", password));
    BasicDBObject searchQuery = new BasicDBObject().append("email", email);
    WriteResult result = users.update(searchQuery, newDocument);

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    response.getWriter().write(result.toString());
  }
Esempio n. 4
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // response.getWriter().append("Served at: ").append(request.getContextPath());

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds037824.mongolab.com:37824/aseproject");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");
    BasicDBObject query = new BasicDBObject();
    query.put("name", request.getParameter("name"));
    query.put("password", request.getParameter("password"));
    DBCursor docs = users.find();
    response.getWriter().write(docs.toArray().toString());

    /*JSONObject obj=new JSONObject();
    obj.put("message", "Hello World");
    response.getWriter().write(obj.toString());
    */
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // response.getWriter().append("Served at: ").append(request.getContextPath());
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("UserRecords");
    BasicDBObject query = new BasicDBObject();

    String firstname = request.getParameter("FirstName");
    String lastname = request.getParameter("LastName");
    String email = request.getParameter("email");
    String password = request.getParameter("EnterPassword");
    String confpasswd = request.getParameter("ConfirmPassword");
    query.put("First Name", firstname);
    query.put("Last Name", lastname);
    query.put("Email", email);
    System.out.println(email);
    if (password == confpasswd) {
      query.put("Password", password);
    } else {

    }
    DBCursor docs = users.find(query);
    response.getWriter().write(docs.toArray().toString());

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println("Insert doget");
  }
Esempio n. 6
0
 /**
  * Retrieve a DBCollection from a MongoDB URI.
  *
  * @param uri the MongoDB URI
  * @return the DBCollection in the URI
  */
 public static DBCollection getCollection(final MongoClientURI uri) {
   try {
     return getMongoClient(uri).getDB(uri.getDatabase()).getCollection(uri.getCollection());
   } catch (Exception e) {
     throw new IllegalArgumentException("Couldn't connect and authenticate to get collection", e);
   }
 }
Esempio n. 7
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    // response.getWriter().append("Served at: ").append(request.getContextPath());
    // JSONObject object = new JSONObject();
    // object.put("message", "Hello World");
    // response.getWriter().write(object.toString());

    response.getWriter().write("Read Users<br /><br />");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds031611.mongolab.com:31611/testbeerdb");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection songs = db.getCollection("users");

    DBCursor docs = songs.find();
    response.getWriter().write(docs.toArray().toString());

    doPost(request, response);
  }
Esempio n. 8
0
 public boolean delete(String id) {
   MongoClientURI uri =
       new MongoClientURI("mongodb://*****:*****@ds015909.mlab.com:15909/lab8_ase");
   MongoClient client = new MongoClient(uri);
   DB db = client.getDB(uri.getDatabase());
   DBCollection Users = db.getCollection("userdata");
   BasicDBObject query = new BasicDBObject();
   ObjectId oid = new ObjectId(id);
   query.put("_id", oid);
   Users.remove(query);
   client.close();
   return true;
 }
  public MongoRolePersonRepository2(final String mongoUri) {
    super();

    // WARNING: mongoUri may contain password!
    final MongoClientURI realMongoUri = new MongoClientURI(mongoUri);
    log.info(
        "Connecting to MongoDB role-person repository {}/{} as {}, rolePerson collection={}",
        realMongoUri.getHosts(),
        realMongoUri.getDatabase(),
        realMongoUri.getUsername(),
        ROLE_PERSON_COLL_NAME);
    try {
      final DB db = MongoUtils.getDb(realMongoUri, ReadPreference.primary());
      rolePersonColl = db.getCollection(ROLE_PERSON_COLL_NAME);

      morphia = new Morphia();
      morphia.map(Role2.class);
      morphia.getMapper().getOptions().objectFactory =
          new DefaultCreator() {
            @Override
            public Object createInstance(Class clazz, DBObject dbObj) {
              // TODO: Do not hardcode
              if (clazz == Email.class) {
                return new EmailImpl();
              }
              return super.createInstance(clazz, dbObj);
            }
          };
    } catch (Exception e) {
      throw new MongoRepositoryException(
          e,
          "Cannot connect to MongoDB role-person repository {}/{} as {} for collection '{}'",
          realMongoUri.getHosts(),
          realMongoUri.getDatabase(),
          realMongoUri.getUsername(),
          ROLE_PERSON_COLL_NAME);
    }
  }
Esempio n. 10
0
  public boolean updatedb(String input, String username) {
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds037824.mongolab.com:37824/ase");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection Users = db.getCollection("Patients");
    DBObject inputDBObj = (DBObject) JSON.parse(input);
    System.out.println(inputDBObj.toString());
    BasicDBObject searchQuery = new BasicDBObject().append("username", username);
    Users.update(searchQuery, inputDBObj);
    client.close();

    return true;
  }
  /** @param p */
  public MongoConfig(Properties p) {
    String uri = p.getProperty(URI_PROPERTY);

    if (uri == null) {
      throw new ConfigurationException("Please define a MongoDB URI for property: " + URI_PROPERTY);
    }

    MongoClientURI mongoUri = new MongoClientURI(uri);
    dbName = mongoUri.getDatabase();
    try {
      client = new MongoClient(mongoUri);
    } catch (UnknownHostException e) {
      throw new ConfigurationException(e);
    }
  }
Esempio n. 12
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds019648.mlab.com:19648/aselab7nag");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("ASELAB7");
    BasicDBObject query = new BasicDBObject();

    users.remove(new BasicDBObject("city", request.getParameter("city")));
    //		response.getWriter().append("Served at: ").append(request.getContextPath());
    System.out.println("Deleted " + request.getParameter("city"));
  }
Esempio n. 13
0
  /**
   * Get an authenticated DBCollection from a MongodB URI.
   *
   * @param authURI the URI with which to authenticate
   * @param uri the MongoDB URI
   * @return the authenticated DBCollection
   */
  public static DBCollection getCollectionWithAuth(
      final MongoClientURI uri, final MongoClientURI authURI) {
    // Make sure auth uri is valid and actually has a username/pw to use
    if (authURI == null || authURI.getUsername() == null || authURI.getPassword() == null) {
      throw new IllegalArgumentException(
          "auth URI is empty or does not contain a valid username/password combination.");
    }

    DBCollection coll;
    try {
      Mongo mongo = getMongoClient(authURI);
      coll = mongo.getDB(uri.getDatabase()).getCollection(uri.getCollection());
      return coll;
    } catch (Exception e) {
      throw new IllegalArgumentException("Couldn't connect and authenticate to get collection", e);
    }
  }
Esempio n. 14
0
  @SuppressWarnings("deprecation")
  @POST
  @Path("/register")
  @Consumes("application/json")
  @Produces(MediaType.TEXT_PLAIN)
  public String registerUser(String jsonStr) {

    mongoClientUri = new MongoClientURI(uri);
    mongoClient = new MongoClient(mongoClientUri);
    db = mongoClient.getDB(mongoClientUri.getDatabase());
    dbCollection = db.getCollection(COLLECTIONNAME);

    JSONObject obj = new JSONObject(jsonStr);

    firstName = obj.getString("first_name");
    lastName = obj.getString("last_name");
    email = obj.getString("email");
    phone = obj.getString("phone_number");
    countryCode = obj.getString("country_code");
    imei = obj.getString("device_id");
    nameToneDir = obj.getString("name_tone");

    System.out.println("FIRST NAME: " + firstName + "\n");
    System.out.println("LAST NAME: " + lastName + "\n");
    System.out.println("EMAIL: " + email + "\n");
    System.out.println("PHONE NUMBER: " + phone + "\n");
    System.out.println("COUNTRY CODE: " + countryCode + "\n");
    System.out.println("IMEI: " + imei + "\n");
    System.out.println("NAME TONE DIR: " + nameToneDir + "\n");

    BasicDBObject doc =
        new BasicDBObject("first_name", firstName)
            .append("last_name", lastName)
            .append("email", email)
            .append("phone_number", phone)
            .append("country_code", countryCode)
            .append("device_imei", imei)
            .append("name_tone_dir", nameToneDir);

    dbCollection.insert(doc);

    mongoClient.close();

    return "SUCCESS";
  }
Esempio n. 15
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, MongoException, DuplicateKeyException {
    // TODO Auto-generated method stub
    // response.getWriter().append("Served at: ").append(request.getContextPath());
    PrintWriter out = response.getWriter();
    String uname = request.getParameter("username2");
    String password = request.getParameter("password2");
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds035014.mongolab.com:35014/vikas2");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");
    BasicDBObject query = new BasicDBObject("username", uname).append("password", password);
    DBCursor docs = users.find(query);
    if (docs.hasNext()) {
      out.println("login successful");
      // out.println("<a href=”http://localhost:9080/example/update”> update password </a>");
      // out.println("<a href=”http://localhost:8080/HelloWorld/test”> Hello World Servlet </a>");
      HttpSession session = request.getSession();
      session.setAttribute("username", uname);
      out.println("<html>");
      out.println("<body bgcolor = '#81F781'>");
      out.println("<form action='update' method='get'>");
      out.println("new password : <input type = 'password' name='update_password'>");
      out.println("<input type = 'submit' value='update password'>");
      out.println("</form>");

      out.println("<form action='delete' method='get'>");
      // out.println("new password : <input type = 'password' name='update_password'>");
      out.println("<input type = 'submit' value='delete account'>");
      out.println("</form>");
      out.println("</body>");
      out.println("</html>");
    } else {
      out.println("login unsuccessful");
    }
    // List<DBObject> userarray = docs.toArray();
    // if( docs.hasNext() )
    // BasicDBObject user1;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
  }
Esempio n. 16
0
  @POST
  @Path("/checkUser")
  @Consumes("application/json")
  @Produces(MediaType.APPLICATION_JSON)
  public String checkUser(String emailJson) {
    JSONObject res;
    StringBuilder sb = new StringBuilder();
    String response;

    try {
      mongoClientUri = new MongoClientURI(uri);
      mongoClient = new MongoClient(mongoClientUri);
      db = mongoClient.getDB(mongoClientUri.getDatabase());
      dbCollection = db.getCollection(COLLECTIONNAME);

      JSONObject obj = new JSONObject(emailJson);
      String email = obj.getString("email");

      System.out.println("JSON: " + obj.toString() + "\n");
      BasicDBObject basicDBObject = new BasicDBObject();
      basicDBObject.put("email", email);

      DBCursor dbCursor = dbCollection.find(basicDBObject);

      while (dbCursor.hasNext()) {
        sb.append(dbCursor.next().toString());
        // System.out.println(dbCursor.next());
      }

      response = sb.toString();

      mongoClient.close();

      if (response.length() > 0) return response;

      return null;
    } catch (Exception e) {
      mongoClient.close();
      System.out.println("EXCEPTION: " + e.getMessage() + " : " + e.getCause() + "\n");
      e.printStackTrace();
      return null;
    }
  }
 public void setMongoURI(MongoClientURI uri) {
   hostsListModel.clear();
   optionsListModel.clear();
   for (String string : uri.getHosts()) {
     final String[] rawHost = string.split(":");
     final String hostname = urlDecode(rawHost[0]);
     final Integer port = rawHost.length > 1 ? Integer.parseInt(rawHost[1]) : null;
     hostsListModel.addElement(new Host(hostname, port));
   }
   usernameField.setText(uri.getUsername());
   if (uri.getPassword() != null) {
     passwordField.setText(new String(uri.getPassword()));
   }
   databaseField.setText(uri.getDatabase());
   final List<Option> options = decodeOptions(uri);
   optionsListModel.clear();
   for (Option option : options) {
     optionsListModel.addElement(option);
   }
   updateURIField();
 }
Esempio n. 18
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.getWriter().write("<br />Insert Test User<br /><br />");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;

    while ((line = reader.readLine()) != null) {

      buffer.append(line);
    }
    String data = buffer.toString();
    // System.out.println("Data ::: " + data);

    JSONObject params = (JSONObject) JSON.parse(data);
    BasicDBObject user1 = new BasicDBObject(params);

    for (Object key : params.keySet().toArray()) {
      user1.put(key.toString(), params.get(key));
    }

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds031611.mongolab.com:31611/testbeerdb");
    MongoClient client = new MongoClient(uri);

    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");
    WriteResult result = users.insert(user1);

    response.getWriter().write(result.toString());

    // doGet(request, response);
  }
Esempio n. 19
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, MongoException, DuplicateKeyException,
          UnknownHostException {
    // TODO Auto-generated method stub
    doGet(request, response);

    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String uname = request.getParameter("username");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    System.out.println(uname + " " + password + " " + email);
    /*String line;
    while((line=reader.readLine())!=null){
     buffer.append(line);
    }
    String data = buffer.toString();
    System.out.println(data);
    data = "{\"p\":\"N\",\"c\":\"W\"}";*/
    // System.out.println(data);
    // JSONObject params = (JSONObject)JSON.parse(data);
    JSONObject params = new JSONObject();
    params.put("username", uname);
    params.put("password", password);
    BasicDBObject user1 = new BasicDBObject(params);
    for (Object key : params.keySet().toArray()) {
      user1.put(key.toString(), params.get(key));
    }
    // System.out.println(user1.toJson());
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds035014.mongolab.com:35014/vikas2");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");
    users.insert(user1);
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
  }
Esempio n. 20
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds037234.mongolab.com:37234/stockdb");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection stocks = db.getCollection("stock");

    BasicDBObject orderBy = new BasicDBObject("price", 1);
    DBCursor cursor = stocks.find().sort(orderBy);

    PrintWriter out = response.getWriter();
    try {
      while (cursor.hasNext()) {
        out.println("<p>" + cursor.next() + "</p>");
      }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      client.close();
    }
    doGet(request, response);
  }
 private MongoDBConnection(String databasename) {
   MongoClientURI uri =
       new MongoClientURI("mongodb://*****:*****@ds039484.mongolab.com:39484/keepshopping");
   MongoClient client = new MongoClient(uri);
   db = client.getDB(uri.getDatabase());
 }