protected final int add() {
    Validator validator = FACTORY.getValidator();
    Set<ConstraintViolation<Model>> violations = validator.validate(this);

    if (violations.size() > 0) {
      ValidationUtils.throwException(violations);
    }

    BasicDBObject dbObjectToAdd = toBasicDBObject();

    WriteResult result = MongoDB.getInstance().create(getCollectionName(getClass()), dbObjectToAdd);
    if (!Tools.isBlankOrNull(result.getError())) {
      throw new JCertifException(this.getClass(), result.getError());
    }
    return 1;
  }
  protected final int update() {
    Validator validator = FACTORY.getValidator();
    Set<ConstraintViolation<Model>> violations = validator.validate(this);

    if (violations.size() > 0) {
      ValidationUtils.throwException(violations);
    }

    BasicDBObject dbObjectToUpdate = toBasicDBObject();
    dbObjectToUpdate.append(Constantes.MONGOD_ID_ATTRIBUTE_NAME, _id);
    int newId = increment(dbObjectToUpdate);

    WriteResult result =
        MongoDB.getInstance().update(getCollectionName(getClass()), dbObjectToUpdate);
    if (!Tools.isBlankOrNull(result.getError())) {
      throw new JCertifException(this.getClass(), result.getError());
    }
    return newId;
  }
  @Test
  public void deleteTest() throws Exception {

    DB db = getDb();

    BasicDBObject doc = new BasicDBObject();

    doc.put("name", "nico");
    doc.put("color", "tabby");

    WriteResult result = db.getCollection("deletetests").insert(doc);

    ObjectId savedOid = doc.getObjectId("_id");

    assertNull(result.getError());

    BasicDBObject query = new BasicDBObject();
    query.put("_id", savedOid);

    // now load by the mongo Id. Users will use this the most to read data.

    BasicDBObject returnedObject =
        new BasicDBObject(db.getCollection("deletetests").findOne(query).toMap());

    assertEquals("nico", returnedObject.get("name"));
    assertEquals("tabby", returnedObject.get("color"));

    // TODO uncomment me assertEquals(savedOid,
    // returnedObject.getObjectId("_id"));

    UUID id = UUID.fromString(returnedObject.get("uuid").toString());

    // now delete the object
    db.getCollection("deletetests").remove(returnedObject, WriteConcern.SAFE);

    DBObject searched = db.getCollection("deletetests").findOne(query);

    assertNull(searched);

    // check it has been deleted

    UUID appId = emf.lookupApplication("test-organization/test-app");
    EntityManager em = emf.getEntityManager(appId);

    Entity entity = em.get(id);

    assertNull(entity);
  }
  @Test
  public void insertDuplicateTest() throws Exception {

    DB db = getDb();

    BasicDBObject doc = new BasicDBObject();

    doc.put("username", "insertduplicate");

    WriteResult result = db.getCollection("users").insert(doc);

    assertNull(result.getError());

    // check we've created the collection

    Set<String> colls = db.getCollectionNames();

    assertTrue(colls.contains("users"));

    // iterate the collection to ensure we can retrieve the object
    doc = new BasicDBObject();

    doc.put("username", "insertduplicate");

    String message = null;

    try {
      result = db.getCollection("users").insert(doc);
    } catch (MongoException me) {
      message = me.getMessage();
    }

    assertNotNull(message);
    assertTrue(
        message.contains(
            "Entity users requires that property named username be unique, value of insertduplicate exists"));
  }
  @Test
  public void insertTest() throws Exception {

    DB db = getDb();

    BasicDBObject doc = new BasicDBObject();

    doc.put("name", "nico");
    doc.put("color", "tabby");

    WriteResult result = db.getCollection("inserttests").insert(doc);

    ObjectId savedOid = doc.getObjectId("_id");

    assertNull(result.getError());

    // check we've created the collection

    Set<String> colls = db.getCollectionNames();

    assertTrue(colls.contains("inserttests"));

    // iterate the collection to ensure we can retrieve the object
    DBCollection coll = db.getCollection("inserttests");
    DBCursor cur = coll.find();

    BasicDBObject returnedObject = null;

    assertTrue(cur.hasNext());

    returnedObject = (BasicDBObject) cur.next();

    assertFalse(cur.hasNext());

    UUID id = UUID.fromString(returnedObject.get("uuid").toString());

    // this should work.  Appears to be the type of ObjectId getting lost on column serialization
    ObjectId returnedOid = new ObjectId(returnedObject.getString("_id"));

    assertEquals("nico", returnedObject.get("name"));
    assertEquals("tabby", returnedObject.get("color"));
    assertEquals(savedOid, returnedOid);
    assertNotNull(id);

    BasicDBObject query = new BasicDBObject();
    query.put("_id", savedOid);

    // now load by the mongo Id. Users will use this the most to read data.

    returnedObject = new BasicDBObject(db.getCollection("inserttests").findOne(query).toMap());

    assertEquals("nico", returnedObject.get("name"));
    assertEquals("tabby", returnedObject.get("color"));

    assertEquals(savedOid, new ObjectId(returnedObject.getString("_id")));
    assertEquals(id.toString(), returnedObject.get("uuid"));

    // check we can find it when using the native entity manager

    UUID appId = emf.lookupApplication("test-organization/test-app");
    EntityManager em = emf.getEntityManager(appId);

    Entity entity = em.get(id);

    assertNotNull(entity);
    assertEquals("nico", entity.getProperty("name"));
    assertEquals("tabby", entity.getProperty("color"));
  }
示例#6
0
  /**
   * Encargado de guardar la informacion suministrada por el usuario para una finca
   *
   * @return Estado del proceso
   */
  public String saveData() throws SQLException {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "farm/create")
        || !usrDao.getPrivilegeUser(idUsrSystem, "farm/modify")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    String action = "";
    /*
     * Se evalua dependiendo a la accion realizada:
     * 1) create: Al momento de guardar un registro por primera ves
     * 2) modify: Al momento de modificar un registro
     * 3) delete: Al momento de borrar un registro
     */
    if (actExe.equals("create")) {
      action = "C";
    } else if (actExe.equals("modify")) {
      action = "M";
    }

    ProducersDao proDao = new ProducersDao();
    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;
    HashMap proData = proDao.findById(idProducer);

    Double altPro = Double.parseDouble(altitude_property.replace(',', '.'));
    Double latPro = Double.parseDouble(latitude_property.replace(',', '.'));
    Double lonPro = Double.parseDouble(length_property.replace(',', '.'));
    //        Double altPro = Double.parseDouble(altitude_property);
    //        Double latPro = Double.parseDouble(latitude_property);
    //        Double lonPro = Double.parseDouble(length_property);

    if (option_geo == 2) {
      latPro = (latitude_minutes_property / 60) + (latitude_seconds_property / 3600);
      latPro =
          (latitude_degrees_property < 0)
              ? ((Math.abs(latitude_degrees_property)) + latPro) * -1
              : (latitude_degrees_property + latPro);

      lonPro = (length_minutes_property / 60) + (length_seconds_property / 3600);
      lonPro =
          (length_degrees_property < 0)
              ? ((Math.abs(length_degrees_property)) + lonPro) * -1
              : (length_degrees_property + lonPro);
    }

    try {
      tx = session.beginTransaction();
      SfGuardUserDao sfDao = new SfGuardUserDao();
      SfGuardUser sfUser = sfDao.getUserByLogin(user.getCreatedBy(), user.getNameUserUsr(), "");
      Farms far = null;
      int idProOld = 0;
      if (idFarm <= 0) {
        far = new Farms();
        far.setIdFar(null);
        far.setGeorefFar(true);
        far.setIdProjectFar("1");
        far.setStatus(true);
      } else {
        HashMap fieldInfo = farDao.findById(idFarm);
        idProOld = Integer.parseInt(String.valueOf(fieldInfo.get("id_producer")));
        far = farDao.objectById(idFarm);
      }
      far.setNameFar(name_property);
      far.setAddressFar(direction_property);
      far.setLatitudeFar(latPro);
      far.setLongitudeFar(lonPro);
      far.setAltitudeFar(altPro);
      far.setNameCommuneFar(lane_property);
      far.setMunicipalities(new Municipalities(Integer.parseInt(cityFar)));
      Integer idUserMobile = null;
      if (sfUser != null) {
        idUserMobile = sfUser.getId().intValue();
      }
      far.setCreatedBy(idUserMobile);
      session.saveOrUpdate(far);
      depFar = String.valueOf(MunicipalitiesDao.getDepartmentId(Integer.parseInt(cityFar)));

      //            farDao.save(far);
      //            System.out.println("valId->"+far.getIdFar());

      if (far.getIdFar() > 0 && action.equals("M")) {
        if (idProOld != idProducer) {
          FarmsProducers farTemp = farDao.checkFarmProducer(far.getIdFar(), idProOld);
          session.delete(farTemp);
        }
        //                System.out.println("id field->"+fiePro.getFields().getIdFie());
        //                fiePro = new FieldsProducers();
        //                fiePro.setId(new FieldsProducersId(lot.getIdFie(), idProducer));
        //                fiePro.setFields(lot);
        //                fiePro.setProducers(proDao.objectById(idProducer));
        //                fiePro.setFieldTypes(new FieldTypes(typeLot));
        //                session.saveOrUpdate(fiePro);
      }

      if (idProOld != idProducer) {
        FarmsProducers farPro = new FarmsProducers();
        farPro.setId(new FarmsProducersId(far.getIdFar(), idProducer));
        farPro.setFarms(far);
        farPro.setProducers(proDao.objectById(idProducer));
        session.saveOrUpdate(farPro);
      }

      /*LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem); //Colocar el usuario registrado en el sistema
      log.setIdObjectLogEnt(far.getIdFar());
      log.setTableLogEnt("farms");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt(action);
      session.saveOrUpdate(log);*/
      //            logDao.save(log);

      /*
      "102": "Nombre de la finca" => nameFarm
      "103": "-30.98664622,-64.10017675,601" Capturar posicion => lat, lng, alt
      "105": "Vereda" => district
      "108": "Indicación (como llegar)" => address
      "241": "Seleccione el productor asociado" => Seleccion (solo dato seleccionado) => prodId
      "336": "Departamento" => department
      "338": "Municipio (Amazonas)" => municipality
      */

      // Manejo para ingresar datos en MongoDB

      HashMap valInfo = new HashMap();
      valInfo.put("farmId", far.getIdFar());
      valInfo.put("nameFarm", far.getNameFar());
      valInfo.put("prodId", idProducer);
      valInfo.put("nameProd", proData.get("name"));
      valInfo.put("district", far.getNameCommuneFar());
      valInfo.put("address", far.getAddressFar());
      valInfo.put("lat", latPro);
      valInfo.put("lng", lonPro);
      valInfo.put("alt", altPro);
      valInfo.put("department", depFar);
      valInfo.put("municipality", cityFar);
      valInfo.put("userMobileId", idUserMobile);
      //            System.out.println("valInfo=>"+valInfo);

      BasicDBObject query = new BasicDBObject();
      query.put("InsertedId", "" + far.getIdFar());
      query.put("form_id", "3");

      MongoClient mongo = null;
      try {
        mongo = new MongoClient("localhost", 27017);
      } catch (UnknownHostException ex) {
        Logger.getLogger(ActionField.class.getName()).log(Level.SEVERE, null, ex);
      }
      DB db = mongo.getDB("ciat");
      DBCollection col = db.getCollection("log_form_records");

      DBCursor cursor = col.find(query);
      WriteResult result = null;
      BasicDBObject jsonField = GlobalFunctions.generateJSONFarm(valInfo);

      if (cursor.count() > 0) {
        System.out.println("actualizo mongo");
        result = col.update(query, jsonField);
      } else {
        System.out.println("inserto mongo");
        result = col.insert(jsonField);
      }

      if (result.getError() != null) {
        throw new HibernateException("");
      }

      mongo.close();
      tx.commit();
      state = "success";
      if (action.equals("C")) {
        info = "La finca ha sido agregada con exito";
        //                return "list";
      } else if (action.equals("M")) {
        info = "La finca ha sido modificada con exito";
      }
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      state = "failure";
      info = "Fallo al momento de agregar una finca";
    } finally {
      session.close();
    }

    return "states";
    //        return ERROR;
  }
示例#7
0
  /**
   * Encargado de borrar la informacion de una finca apartir de su identificacion
   *
   * @param idFar: Identificacion de la finca
   * @return Estado del proceso
   */
  public String delete() {
    if (!usrDao.getPrivilegeUser(idUsrSystem, "farm/delete")) {
      return BaseAction.NOT_AUTHORIZED;
    }
    Integer idFar = 0;
    try {
      idFar = Integer.parseInt(this.getRequest().getParameter("idFar"));
    } catch (NumberFormatException e) {
      idFar = -1;
    }

    if (idFar == -1) {
      state = "failure";
      info = "Fallo al momento de obtener la informacion a borrar";
      return "states";
    }

    SessionFactory sessions = HibernateUtil.getSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;

    try {
      tx = session.beginTransaction();
      Farms far = farDao.objectById(idFar);
      far.setStatus(false);
      session.saveOrUpdate(far);
      //            session.delete(far);
      //            farDao.delete(far);

      LogEntities log = new LogEntities();
      log.setIdLogEnt(null);
      log.setIdEntityLogEnt(idEntSystem); // Colocar el usuario registrado en el sistema
      log.setIdObjectLogEnt(far.getIdFar());
      log.setTableLogEnt("farms");
      log.setDateLogEnt(new Date());
      log.setActionTypeLogEnt("D");
      session.saveOrUpdate(log);
      //            logDao.save(log);

      BasicDBObject query = new BasicDBObject();
      query.put("InsertedId", "" + far.getIdFar());
      query.put("form_id", "3");

      MongoClient mongo = null;
      try {
        mongo = new MongoClient("localhost", 27017);
      } catch (UnknownHostException ex) {
        Logger.getLogger(ActionField.class.getName()).log(Level.SEVERE, null, ex);
      }
      DB db = mongo.getDB("ciat");
      DBCollection col = db.getCollection("log_form_records");
      WriteResult result = null;

      System.out.println("borro mongo");
      result = col.remove(query);

      if (result.getError() != null) {
        throw new HibernateException("");
      }
      mongo.close();

      FieldsDao fieDao = new FieldsDao();
      fieDao.deleteFieldsMongo(far.getIdFar());

      tx.commit();
      state = "success";
      info = "La finca ha sido borrada con exito";
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
      }
      e.printStackTrace();
      state = "failure";
      info = "Fallo al momento de borrar una finca";
    } finally {
      session.close();
    }

    return "states";
    //        return SUCCESS;
  }