public void updateDeviceLog(String productId, String[] vids, Modal model) {
   MongoCollection<Document> deviceLog = getDeviceLog();
   Document filter = new Document("product-id", productId);
   Document doc = getDeviceLog().find(filter).first();
   if (doc != null && model != null) {
     List<Document> models = doc.get("models", List.class);
     Document m = convertModel(vids, model);
     if (models != null) {
       models.add(m);
     } else {
       models = new ArrayList<>();
       models.add(m);
     }
     doc.append("models", models);
     deviceLog.replaceOne(filter, doc);
   } else {
     Device device = new Device();
     device.setProductId(productId);
     doc = toDocument(device);
     List<Document> models = new ArrayList<>();
     models.add(convertModel(vids, model));
     doc.append("models", models);
     deviceLog.insertOne(doc);
   }
 }
Exemplo n.º 2
0
  private void setListeners() {
    widthProperty()
        .addListener(
            (InvalidationListener)
                (listener) -> {
                  confDoc.append("width", width.get());
                  //			save();
                  DBUtils.getCollection()
                      .updateOne(
                          Filters.eq("_id", "conf"),
                          new Document("$set", new Document("width", width.get())));
                });

    heightProperty()
        .addListener(
            (InvalidationListener)
                (listener) -> {
                  confDoc.append("height", height.get());
                  DBUtils.getCollection()
                      .updateOne(
                          Filters.eq("_id", "conf"),
                          new Document("$set", new Document("height", height.get())));
                });

    lastDocProperty()
        .addListener(
            (InvalidationListener)
                (listener) -> {
                  confDoc.append("lastDoc", lastDoc.get());
                  DBUtils.getCollection()
                      .updateOne(
                          Filters.eq("_id", "conf"),
                          new Document("$set", new Document("lastDoc", lastDoc.get())));
                });
  }
 private Document convertModel(String[] vids, Modal model) {
   Document doc = new Document();
   doc.append("vids", Arrays.asList(vids));
   doc.append("values", model.getValues());
   doc.append("productIds", convertProductIds(model.getProductId()));
   doc.append("created", new Date());
   return doc;
 }
 private Document convertProductId(ProductId productId) {
   Document doc = new Document();
   doc.append("values", productId.getValue());
   if (productId.getCondition() != null && !productId.getCondition().isEmpty()) {
     doc.append("conditions", productId.getCondition());
   }
   return doc;
 }
Exemplo n.º 5
0
 public final void setLastDoc(final org.bson.Document lastDoc) {
   this.lastDocProperty().set(lastDoc);
   confDoc.append("lastDoc", lastDoc);
   DBUtils.getCollection()
       .updateOne(
           Filters.eq("_id", "conf"), new Document("$set", new Document("lastDoc", lastDoc)));
 }
  /**
   * 更新用户信息
   *
   * @return 是否更新成功
   */
  private boolean updateRecord(record exist_record, record new_record) {
    try {
      System.out.print("update record");
      MongoDAO dao = MongoDAO.GetInstance();
      System.out.print("update record1");
      Document existing = new Document();
      existing.append("admission_number", exist_record.getAdmission_number());

      long num = dao.GetCollection("records").deleteMany(existing).getDeletedCount();
      System.out.print("remove record number = " + num);

      try {
        Map<String, Object> docMap = new_record.getDocMap();
        docMap.put("inHospital", true);
        docMap.put("leaveHospital", false);
        docMap.put("followup", false);
        dao.GetCollection("records").insertOne(new Document(docMap));
      } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.toString());
        return false;
      }

      System.out.print("update record2");
    } catch (Exception e) {
      e.printStackTrace();
      logger.error(e.toString());
      return false;
    }
    return true;
  }
Exemplo n.º 7
0
  // validates that username is unique and insert into db
  public boolean addUser(String username, String password, String email) {

    String passwordHash = makePasswordHash(password, Integer.toString(random.nextInt()));

    // XXX WORK HERE
    // create an object suitable for insertion into the user collection
    // be sure to add username and hashed password to the document. problem instructions
    // will tell you the schema that the documents must follow.
    password = makePasswordHash(password, "asd");
    Document user = new Document("_id", username).append("password", password);

    if (email != null && !email.equals("")) {
      // XXX WORK HERE
      // if there is an email address specified, add it to the document too.
      user.append("email", email);
    }

    try {
      // XXX WORK HERE
      // insert the document into the user collection here
      usersCollection.insertOne(user);
      return true;
    } catch (MongoWriteException e) {
      if (e.getError().getCategory().equals(ErrorCategory.DUPLICATE_KEY)) {
        System.out.println("Username already in use: " + username);
        return false;
      }
      throw e;
    }
  }
  /**
   * Map an Order object to a Mongo Document object.
   *
   * @param o Order
   * @return A Document object with all the information of the Order.
   */
  public static final Document toDocument(Order o) {
    Document c = CustomerAdapter.toDocument(o.getCustomer());
    c.remove("_id");

    List<Document> itemsDoc = new ArrayList<>(o.getItems().size());
    Document iDoc = null;

    for (Item i : o.getItems()) {
      iDoc = ItemAdapter.toDocument(i);
      iDoc.remove("_id");
      itemsDoc.add(iDoc);
    }

    Document d =
        new Document("total", o.getTotal())
            .append("date", o.getDate())
            .append("status", o.getStatus().getName())
            .append("customer", c)
            .append("items", itemsDoc);

    if (o.getId() != null) {
      d.append("_id", new ObjectId(o.getId()));
    }
    return d;
  }
 private Document toDocument(Device device) {
   Document doc = new Document();
   doc.append("product-id", device.getProductId());
   doc.append("brand", device.getBrand());
   doc.append("product", device.getProduct());
   doc.append("alias", device.getAlias());
   doc.append("type", device.getType());
   doc.append("created", new Date());
   return doc;
 }
Exemplo n.º 10
0
  /**
   * Marks the questions as used for players in MongoDB
   *
   * @param players
   * @param questionId
   */
  public void markQuestionsUsed(List<BasicPlayer> players, int questionId) {
    Document query = new Document();

    List<Document> orPlayerList = new ArrayList<>();
    for (BasicPlayer player : players) {
      orPlayerList.add(new Document(Config.USER_USERNAME, player.getAccountName()));
    }
    query.append("$or", orPlayerList);

    Document questionIdPush = new Document(Config.USER_QUESTIONS_USED, questionId);
    Document update = new Document("$push", questionIdPush);

    userCollection.updateMany(query, update);

    return;
  }
Exemplo n.º 11
0
  // starts a new session in the sessions table
  public String startSession(String username) {

    // get 32 byte random number. that's a lot of bits.
    SecureRandom generator = new SecureRandom();
    byte randomBytes[] = new byte[32];
    generator.nextBytes(randomBytes);

    BASE64Encoder encoder = new BASE64Encoder();

    String sessionID = encoder.encode(randomBytes);

    // build the BSON object
    Document session = new Document("username", username);

    session.append("_id", sessionID);

    sessionsCollection.deleteMany(new Document("username", username));

    sessionsCollection.insertOne(session);

    return session.getString("_id");
  }
Exemplo n.º 12
0
  @Override
  public void insertAlbum(Album album) {
    Document albumToAdd = new Document();
    try {

      db.getCollection("album")
          .insertOne(
              albumToAdd
                  .append("title", album.getTitle())
                  .append("score", album.getScore())
                  .append("released", album.getReleased())
                  .append("genre", album.getGenre())
                  .append(
                      "artist",
                      new Document()
                          .append("name", this.getArtists())
                          .append("nation", this.getArtists())));

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 13
0
  public String addPost(String title, String body, List tags, String username) {

    System.out.println("inserting blog entry " + title + " " + body);

    String permalink = title.replaceAll("\\s", "_"); // whitespace becomes _
    permalink = permalink.replaceAll("\\W", ""); // get rid of non alphanumeric
    permalink = permalink.toLowerCase();
    permalink = permalink + (new Date()).getTime();

    Document post = new Document();

    if (username != null && !username.equals("")) {
      post.append("author", username);
    }
    if (title != null && !title.equals("")) {
      post.append("title", title);
    }
    if (body != null && !body.equals("")) {
      post.append("body", body);
    }
    if (permalink != null && !permalink.equals("")) {
      post.append("permalink", permalink);
    }
    if (tags != null && !tags.equals("")) {
      post.append("tags", tags);
    }
    post.append("comments", new ArrayList<String>());
    post.append("date", new Date());

    try {
      postsCollection.insertOne(post);
      return permalink;
    } catch (MongoWriteException e) {
      if (e.getError().getCategory().equals(ErrorCategory.UNCATEGORIZED)) {
        System.out.println("Username already in use: " + username);
        return e.getMessage();
      }
      throw e;
    }
  }
Exemplo n.º 14
0
 public static void sparkFare(ApplicationContext applicationcontext) throws ParseException {
   try {
     CalcDependenciesService calcDependenciesService =
         applicationcontext.getBean("calcDependenciesService", CalcDependenciesService.class);
     HashMap calcDependencies = calcDependenciesService.getCalcDependencies();
     Date deptDate = DateUtils.parseDate("2016-01-25", "yyyy-MM-dd");
     Document doc = new Document();
     Document flightInfo = new Document();
     flightInfo.append("carrier", "MU");
     flightInfo.append("flightNo", "5111");
     flightInfo.append("oriEng", "SHA");
     flightInfo.append("desEng", "PEK");
     flightInfo.append("flightDt", deptDate);
     doc.append("flightInfo", flightInfo);
     doc.append("routetype", "OW");
     doc.append("currency", "CNY");
     doc.append("channel", new Double(38));
     AtomicFareCalc.getInstance().fareCalc(doc, calcDependencies);
   } catch (BeansException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 15
0
  private Conf() {

    confDoc = DBUtils.getConfDoc();
    if (confDoc == null) {
      confDoc = new Document();
      confDoc
          .append("_id", "conf")
          .append("width", 400d)
          .append("height", 400d)
          .append("traductor", false)
          .append("lastDoc", lastDoc.get());
      DBUtils.getCollection().insertOne(confDoc);
    } else {
      System.out.println(confDoc.toJson());
      height.set(confDoc.getDouble("height"));
      width.set(confDoc.getDouble("width"));
      traductorVisible.set(confDoc.getBoolean("traductor", false));
      Document _ld = (Document) confDoc.get("lastDoc");
      if (_ld != null) {
        lastDoc.set(_ld);
      }
    }
    setListeners();
  }
Exemplo n.º 16
0
 @SuppressWarnings("rawtypes")
 public static void sparkFare(ApplicationContext applicationcontext) throws ParseException {
   try {
     CalcDependenciesService calcDependenciesService =
         applicationcontext.getBean("calcDependenciesService", CalcDependenciesService.class);
     HashMap calcDependencies = calcDependenciesService.getCalcDependencies();
     Date deptDate = DateUtils.parseDate("2016-07-09", "yyyy-MM-dd");
     Date depTime = DateUtils.parseDate("2016-07-09 20:50", "yyyy-MM-dd HH:mm");
     Document doc = new Document();
     doc.append("carrier", "FM");
     doc.append("flightNo", "9136");
     doc.append("oriEng", "BAV");
     doc.append("desEng", "PVG");
     doc.append("flightDt", deptDate);
     doc.append("depTime", depTime);
     doc.append("routetype", "OW");
     doc.append("currency", "USD");
     doc.append("channel", new Double(3));
     AtomicFareCalc.getInstance().fareCalc(doc, calcDependencies);
   } catch (BeansException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 17
0
  private static void doSomething(MongoClient mongo) {
    MongoDatabase db = mongo.getDatabase("testdb");

    MongoCollection<Document> collection = db.getCollection("users");

    Document user = new Document("username", "johnd");
    user.append("_id", 1);
    user.append("firstName", "John");
    user.append("name", "Doe");
    user.append("enabled", Boolean.FALSE);
    user.append("noOfLogins", 0);
    user.append("lastLogin", new Date());
    user.append("groups", Arrays.asList("admin", "user"));

    System.out.println(user);
    collection.insertOne(user);

    user = new Document("username", "francol");
    user.append("firstName", "Franco");
    user.append("name", "Lawrence");
    user.append("enabled", Boolean.TRUE);
    user.append("noOfLogins", 0);
    user.append("lastLogin", new Date());
    user.append("groups", Arrays.asList("user"));
    collection.insertOne(user);
  }
Exemplo n.º 18
0
  private void insertMongo() throws Exception {
    // *****This is to connect to database**//

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("database");

    MongoCollection<Document> elexirCollection = db.getCollection("test");

    // *********This is to connect to the database***********//

    // To clear out existing files from mongo
    db.getCollection("test").deleteMany(new Document());

    // *******This is to read the file into program*********//
    // String fileDirectory = chooser.getCurrentDirectory() + "";

    FileReader file = new FileReader(pathField.getText());
    BufferedReader reader = new BufferedReader(file);

    String line = reader.readLine();

    // **********This is to read the text file into program***************//

    // Creating the Array List to store types of variables
    List<String> Types = new ArrayList<String>();
    List<String> Objects = new ArrayList<String>();
    List<String> Predicates = new ArrayList<String>();
    List<String> Cats = new ArrayList<String>();
    List<String> Category = new ArrayList<String>();
    List<String> Action = new ArrayList<String>();

    List<Double> DerivProb = new ArrayList<Double>();
    List<Double> RootProb = new ArrayList<Double>();
    List<String> InitialState = new ArrayList<String>();
    List<String> FinalState = new ArrayList<String>();
    List<String> Roots = new ArrayList<String>();

    List<String> Probability = new ArrayList<String>();

    ArrayList<Document> Doc = new ArrayList<Document>();

    // initialize all types of definitions
    String type = null;
    String object = null;
    String predicate = null;
    String cat = null;
    String category = null;
    String action = null;
    String derivProb = null;
    String rootProb = null;
    String initialState = null;
    String finalState = null;
    String roots = null;
    String probability = null;

    Document Exp = new Document();
    Document definitions = new Document();
    Document stats = new Document();

    // Read type Definitions
    while (line != null) {

      if (line.contains("Defined Type: ")) {
        int startingIndexOfType;
        String types = "Defined Type: ";
        startingIndexOfType = line.indexOf("Defined Type: ");
        int endingIndexOfType = line.indexOf(".");
        type = line.substring(startingIndexOfType + types.length(), endingIndexOfType);
        // putting the piece of string into the new string
        Types.add(type);

      }

      // Read object definitions.
      else if (line.contains("Defined Object: ")) {
        int startingIndexOfObj; // this is to split each word from its
        // spaces and print word by word
        String objects = "Defined Object: ";
        startingIndexOfObj = line.indexOf("Defined Object: ");
        int endingIndexOfObj = line.indexOf(".");
        object = line.substring(startingIndexOfObj + objects.length(), endingIndexOfObj);
        // putting the piece of string into the new string
        Objects.add(object);
      }

      // Read predicate definitions.
      else if (line.contains("Defined predicate:")) {
        String predicates = "Defined predicate:";
        int startingIndexOfPred; // this is to split each word from its
        // spaces and print word by word
        startingIndexOfPred = line.indexOf("Defined predicate:");
        int endingIndexOfPred = line.indexOf(".");
        predicate = line.substring(startingIndexOfPred + predicates.length(), endingIndexOfPred);
        // putting the piece of string into the new string
        Predicates.add(predicate);
      }

      // Defined Cat-Definition
      else if (line.contains("Defined: Cat-Definition: ")) {
        int startingIndexOfCat; // this is to split each word from its
        // spaces and print word by word
        String catDef = "Defined: Cat-Definition: ";
        startingIndexOfCat = line.indexOf("Defined: Cat-Definition: ");
        int endingIndexOfCat = line.indexOf(".", startingIndexOfCat);
        cat = line.substring(startingIndexOfCat + catDef.length(), endingIndexOfCat);
        // putting the piece of string into the new string
        Cats.add(cat);
      }

      // Defined Action Definitions

      else if (line.contains("Defined: category: ")) {
        String categ = "Defined: category: ";
        int startingIndexOfCategory = line.indexOf("Defined: category: ");
        int endingIndexOfCategory = line.indexOf(";", startingIndexOfCategory);
        category = line.substring(startingIndexOfCategory + categ.length(), endingIndexOfCategory);
        Category.add(category);

      } else if (line.contains("Defined: ")) {
        // this is to split each word from its
        // spaces and print word by word
        String defined = "Defined: ";
        int startingIndexOfAct = line.indexOf("Defined: ");
        int endingIndexOfAct = line.indexOf(".", startingIndexOfAct);
        action = line.substring(startingIndexOfAct + defined.length(), endingIndexOfAct);
        // putting the piece of string into the new string
        Action.add(action);
      }
      line = reader.readLine();
      definitions = new Document();
      if (line.startsWith("Read goals for query.")) break;
    }

    definitions
        .append("Types", Types)
        .append("Objects", Objects)
        .append("Predicates", Predicates)
        .append("Cats", Cats)
        .append("Category", Category)
        .append("Actions", Action);

    elexirCollection.insertOne(definitions);

    while (line != null) {

      DerivProb = new ArrayList<Double>();
      RootProb = new ArrayList<Double>(); // To clear out the array so that
      InitialState = new ArrayList<String>(); // the document does not repeat with
      FinalState = new ArrayList<String>(); // roots from previous explanations
      Roots = new ArrayList<String>();

      if (line.startsWith("[Exp:")) {
        String dp = "derivProb :";
        int startingIndexOfDP;
        startingIndexOfDP = line.indexOf("derivProb: ");
        int endingIndexOfDP = line.indexOf(" root", startingIndexOfDP);
        derivProb = line.substring(startingIndexOfDP + dp.length(), endingIndexOfDP);
        DerivProb.add(Double.parseDouble(derivProb));

        String rp = "rootProb :";
        int startingIndexOfRP;
        startingIndexOfRP = line.indexOf("rootProb: ");
        int endingIndexOfRP = line.indexOf(" Initial", startingIndexOfRP);
        rootProb = line.substring(startingIndexOfRP + rp.length(), endingIndexOfRP);
        RootProb.add(Double.parseDouble(rootProb));

        String is = "Initial State:[ ";
        int startingIndexOfIS;
        startingIndexOfIS = line.indexOf("Initial State:[ ");
        int endingIndexOfIS = line.indexOf(" ]", startingIndexOfIS);
        initialState = line.substring(startingIndexOfIS + is.length(), endingIndexOfIS);
        InitialState.add(initialState);

        String fs = "Final State:[ ";
        int startingIndexOfFS;
        startingIndexOfFS = line.indexOf("Final State:[ ");
        int endingIndexOfFS = line.indexOf(" ]", startingIndexOfFS);
        finalState =
            line.substring(startingIndexOfFS + fs.length(), endingIndexOfFS); // capture last
        FinalState.add(finalState);

        String rootStr = "root:[";
        for (int x = line.indexOf(rootStr); x > -1; x = line.indexOf(rootStr, ++x)) {
          int endingIndexOfRoot = line.indexOf("]", x);
          roots = line.substring(x + rootStr.length(), endingIndexOfRoot);

          Roots.add(roots);
        }

        Exp = new Document();
        Exp.append("derivProb", Arrays.asList(derivProb))
            .append("rootProb", Arrays.asList(rootProb))
            .append("initialState", Arrays.asList(initialState))
            .append("finalState", Arrays.asList(finalState))
            .append("Roots", Roots);

        Doc.add(Exp);
        elexirCollection.insertOne(Exp);

      } else if (!line.startsWith("[Exp:")) {
        // System.out.println("At first if else");
        // System.out.println(line);
        if (line.contains("Probabilites:")) {
          // System.out.println("At line equals prob");
          while (!line.contains("*** Done with problem. ***")) {
            // System.out.println("Reached while loop");
            // read each line and save here

            probability += line + "\n";

            // System.out.println(probability);

            line = reader.readLine();
          }

          Probability.add(probability);
          stats.append("Probability", Probability);
          elexirCollection.insertOne(stats);
        }
      }

      line = reader.readLine();
    } // end while

    FindIterable<Document> iter = elexirCollection.find();
    System.out.println("Your Documents have been stored into mongoDB ");
  }
Exemplo n.º 19
0
  public static Document meepDocumentBuilder(JsonObject arg, MongoCollection<Document> meepCol) {
    Document meep = new Document();
    if (arg.get("coordinates").isJsonNull()) return null;
    double longi =
        arg.getAsJsonObject("coordinates").getAsJsonArray("coordinates").get(0).getAsDouble();
    double lat =
        arg.getAsJsonObject("coordinates").getAsJsonArray("coordinates").get(1).getAsDouble();
    BasicDBObject aux = getCloseMeepsQuery(lat, longi);
    FindIterable<Document> auxCol = meepCol.find(aux);
    if (auxCol.first() != null) {
      System.out.println("Received valid tweet but too close to another");
      return null;
    }
    meep.append(
        "senderName", arg.getAsJsonObject("user").getAsJsonPrimitive("screen_name").getAsString());
    System.out.println(
        "Received valid tweet at "
            + lat
            + ","
            + longi
            + " posted by "
            + meep.getString("senderName"));
    meep.append("senderId", arg.getAsJsonObject("user").getAsJsonPrimitive("id").getAsInt());
    meep.append(
        "twitterUserPicture",
        arg.getAsJsonObject("user").getAsJsonPrimitive("profile_image_url").getAsString());
    meep.append("message", arg.getAsJsonPrimitive("text").getAsString());
    meep.append("type", "tweet");
    meep.append("isRoot", true);
    meep.append("commentCounter", 0);
    meep.append("likeCounter", 0);
    meep.append("viewCounter", 0);
    /*if(arg.getAsJsonObject("entities").has("media"))
        meep.append("picture", arg.getAsJsonObject("entities").getAsJsonObject("media").get("media_url").getAsString());
    else*/
    meep.append("picture", null);
    BasicDBList list = new BasicDBList();
    list.add(longi);
    list.add(lat);
    Document jobj = new Document();
    jobj.append("type", "Point");
    jobj.append("coordinates", list);

    meep.append("location", jobj);
    BasicDBList comments = new BasicDBList();
    meep.append("comments", comments);
    BasicDBList receipts = new BasicDBList();
    meep.append("receipts", receipts);
    BasicDBList registrees = new BasicDBList();
    meep.append("registrees", registrees);
    BasicDBList likes = new BasicDBList();
    meep.append("likes", likes);

    meep.append("categoryId", Category.TWITTER.getId());

    BasicDBList hashtags = new BasicDBList();
    HashtagController controller = new HashtagController();
    LinkedList<String> aux2 =
        controller.extractHashtags(arg.getAsJsonPrimitive("text").getAsString());
    for (String s : aux2) hashtags.add(s);
    meep.append("hashtags", hashtags);

    meep.append("isPublic", true);
    return meep;
  }