Exemple #1
0
 Field[] keyFields() {
   Class c = clazz;
   try {
     List<Field> fields = new ArrayList<Field>();
     while (!c.equals(Object.class)) {
       for (Field field : c.getDeclaredFields()) {
         // TODO: add cashe field->isAnnotationPresent
         if (InternalCache.isEnableAnnotationPresent()) {
           if (InternalCache.isAnnotationPresent(Id.class, field)
               || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) {
             field.setAccessible(true);
             fields.add(field);
           }
         } else {
           if (field.isAnnotationPresent(Id.class)
               || field.isAnnotationPresent(EmbeddedId.class)) {
             field.setAccessible(true);
             fields.add(field);
           }
         }
       }
       c = c.getSuperclass();
     }
     final Field[] f = fields.toArray(new Field[fields.size()]);
     if (f.length == 0) {
       throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz);
     }
     return f;
   } catch (Exception e) {
     throw new UnexpectedException(
         "Error while determining the object @Id for an object of type " + clazz);
   }
 }
Exemple #2
0
  @Transient
  @JsonIgnore
  public List<String> getAccessableBranch() throws Exception {

    if (NullEmptyChecker.isNullOrEmpty(accessableBranch)) {

      if (getDataAccessRestriction().equals(DataAccessRestriction.AllBranch.getVal())) {

        return null;
      } else if (getDataAccessRestriction().equals(DataAccessRestriction.Subordinate.getVal())) {

        Branch branch = branchRepo.find(getFidBranch());
        System.out.println("branch = " + branch);
        accessableBranch.addAll(branch.getAllSubordinateId());
        accessableBranch.add(getFidBranch());
      } else if (getDataAccessRestriction().equals(DataAccessRestriction.SelfBranch.getVal())) {

        accessableBranch = Arrays.asList(getFidBranch());
      } else {

        String[] accessItem = this.getAccessBranch().split(";");

        for (int x = 0; x < accessItem.length; x++) {
          accessableBranch.add(accessItem[x]);
        }
      }
    }

    return accessableBranch;
  }
Exemple #3
0
 public void addComment(Comment comment) {
   if (!comment.isCommentSet()) {
     List<Comment> commentList = getComments();
     commentList.add(comment);
     comment.commentSet = true;
   }
 }
Exemple #4
0
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new LinkedHashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     int mod = f.getModifiers();
     if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class)) {
       continue;
     }
     if (f.isAnnotationPresent(NoBinding.class)) {
       NoBinding a = f.getAnnotation(NoBinding.class);
       List<String> values = Arrays.asList(a.value());
       if (values.contains("*")) {
         continue;
       }
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
Exemple #5
0
 public static List<String> fioList() {
   List<String> theList = new ArrayList<String>();
   for (Doctor doctor : allDoctors()) {
     theList.add(doctor.getFullName());
   }
   return theList;
 }
 public static List<String> typesList() {
   List<String> theList = new ArrayList<String>();
   for (IdentityDocType type : all()) {
     theList.add(type.identityDocTypeName);
   }
   return theList;
 }
Exemple #7
0
  /**
   * Generate license plates from a file.
   *
   * @param filename
   */
  private void generateLicensePlates(String filename) {
    File licenseplatefile = getResourceFile(filename);
    BufferedReader in = null;
    try {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(licenseplatefile)));
    } catch (FileNotFoundException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<String> licensePlates = new ArrayList();
    String line;

    try {
      while ((line = in.readLine()) != null) {
        licensePlates.add(line);
      }
    } catch (IOException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        in.close();
      } catch (IOException ex) {
        Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    itLicensePlates = licensePlates.iterator();
  }
 @Transient
 private List<ArticlePageEntityDTO> getPagesAsDTOs() {
   List<ArticlePageEntityDTO> pageDTOs = new ArrayList<>();
   for (ArticlePage page : pages) {
     pageDTOs.add(page.toDTO());
   }
   return pageDTOs;
 }
Exemple #9
0
  /**
   * Will return SiteResearchStaff having at least one active role provided in roleCodes parameter.
   *
   * @param roleCodes - roles to check
   * @return A list of SiteResearchStaff
   */
  public List<SiteResearchStaff> findSiteResearchStaffByRoles(final String... roleCodes) {
    List<SiteResearchStaff> srsList = new ArrayList<SiteResearchStaff>();
    for (SiteResearchStaff srs : getSiteResearchStaffs()) {
      if (srs.hasActiveRolesOfType(roleCodes)) srsList.add(srs);
    }

    return srsList;
  }
Exemple #10
0
 /**
  * Will return all the SiteResearchStaff which are currently active.
  *
  * @return the in active site research staff
  */
 @Transient
 public List<SiteResearchStaff> getInActiveSiteResearchStaff() {
   List<SiteResearchStaff> srsList = new ArrayList<SiteResearchStaff>();
   for (SiteResearchStaff srs : getSiteResearchStaffs()) {
     if (!srs.isActive()) srsList.add(srs);
   }
   return srsList;
 }
 @Override
 public List<ICompetition> getCompetitions() {
   List<ICompetition> cl = new LinkedList<>();
   for (Competition c : competitions) {
     cl.add(c);
   }
   return cl;
 }
Exemple #12
0
  /**
   * Get a vehicle by cartracker id from the cached list, if the vehicle does not exist it will be
   * created.
   *
   * @param cartrackerID
   * @return The found or newly created vehicle.
   */
  @Override
  public Vehicle getOrCreateVehicleById(String cartrackerID) {
    Vehicle returnVehicle = null;

    Iterator<Vehicle> it = vehicles.iterator();
    while (it.hasNext()) {
      Vehicle vehicle = it.next();
      if (cartrackerID.equals(vehicle.getCarTrackerID())) {
        returnVehicle = vehicle;
        break;
      }
    }

    /* Vehicle does not exist, lets create a new one */
    if (returnVehicle == null) {
      try {
        /* Also create a vehicle ownership */
        GregorianCalendar registerdate = new GregorianCalendar();
        registerdate.add(Calendar.YEAR, -3);
        VehicleOwnership vehicleOwnership = new VehicleOwnership();
        vehicleOwnership.setContributeGPSData(true);
        vehicleOwnership.setRegistrationdate((GregorianCalendar) registerdate.clone());
        vehicleOwnership.setRegistrationExperationDate(null);
        try {
          // create new user with incrementing name
          userDAO = new UserDAOImpl(emf);
          loginDAO = new LoginDAOImpl(em);
          UserDto user =
              userDAO.register(
                  "user" + USER_ID++ + "name", "aidas123", "*****@*****.**");
          MovementUser mUser = loginDAO.register(user.getUsername(), user.getEmail());
          vehicleOwnership.setUser(mUser);
        } catch (UserSystemException ex) {
          Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        // create car
        returnVehicle = new Vehicle(cartrackerID);
        returnVehicle.setLicensePlate(itLicensePlates.next());
        List<VehicleOwnership> owners = new ArrayList();
        owners.add(vehicleOwnership);
        returnVehicle.setVehicleOwners(owners);
        em.persist(returnVehicle);

        vehicleOwnership.setVehicle(returnVehicle);
        em.persist(vehicleOwnership);
        Logger.getLogger(MovementsDAOImpl.class.getName())
            .log(Level.WARNING, "Created new vehicle with ID" + cartrackerID);

        this.vehicles.add(returnVehicle);
      } catch (Exception ex) {
        Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    return returnVehicle;
  }
 /**
  * Validates Response object.
  *
  * <p>Returns List of validation errors if the object is not valid. Main rules: if field is
  * required, response answer on that field should not be empty, if field type is date, response
  * answer on that field should match DATE_REGEX.
  *
  * @return List of validation errors or null if Response object is valid
  */
 public List<ValidationError> validate() {
   List<ValidationError> errors = new ArrayList<>();
   if (answers != null) {
     for (Answer answer : answers) {
       if (answer.field.required && answer.isEmptyAnswer()) {
         errors.add(new ValidationError(answer.field.label, "Field is required."));
       }
       if (answer.field.fieldType.equals(FieldType.DATE)
           && !answer.value.isEmpty()
           && !isValidDate(answer.value)) {
         errors.add(
             new ValidationError(
                 answer.field.label, "Wrong date format. Please, use yyyy-mm-dd format."));
       }
     }
   }
   return errors.isEmpty() ? null : errors;
 }
Exemple #14
0
 /**
  * groupKey를 통해 같은 코멘트그룹을 반환한다.
  *
  * @param groupKey
  * @param codeComments
  * @return
  */
 private List<CommitComment> commitCommentsGroupByKey(
     String groupKey, List<CommitComment> codeComments) {
   List<CommitComment> commitCommentGroups = new ArrayList<>();
   for (CommitComment commitComment : codeComments) {
     if (commitComment.groupKey().equals(groupKey)) {
       commitCommentGroups.add(commitComment);
     }
   }
   return commitCommentGroups;
 }
  @Override
  public void setCompetitions(List<ICompetition> competitions) {
    List<Competition> result = new LinkedList<>();

    for (ICompetition d : competitions) {
      result.add((Competition) d);
    }

    this.competitions = result;
  }
  @Override
  public void setTeamList(List<ITeam> teamList) {
    List<Team> result = new LinkedList<>();

    for (ITeam d : teamList) {
      result.add((Team) d);
    }

    this.teamList = result;
  }
  @XmlTransient
  @Override
  public List<ITeam> getTeamList() {
    List<ITeam> result = new LinkedList<>();

    for (Team d : teamList) {
      result.add(d);
    }

    return result;
  }
Exemple #18
0
  /**
   * 답글목록을 부모글의 필드로 재할당한다.
   *
   * <p>commentGroup은 등록일순으로 오름차순 정렬되어 있는 상태이며 목록의 첫번째 코멘트를 부모글로 판단한다.
   *
   * @param commentGroup
   * @return
   */
  private List<CommitComment> reAssignReplyComments(Map<String, List<CommitComment>> commentGroup) {
    List<CommitComment> parentCommitComments = new ArrayList<>();

    for (List<CommitComment> commitComments : commentGroup.values()) {
      CommitComment parentComment = commitComments.get(0);
      if (hasReply(commitComments)) {
        parentComment.replies = replies(commitComments);
      }
      parentCommitComments.add(parentComment);
    }
    return parentCommitComments;
  }
Exemple #19
0
 public static List<Room> findJoinedRoomsByUser(User user) {
   // ユーザが所属するルーム一覧の取得.
   // FIXME JOINとか使わないとどう考えてもだめだよー。HQLとJPAがわからないので一旦放置.
   List<Room> rooms = findAll();
   List<Room> ret = new ArrayList<Room>();
   for (Room room : rooms) {
     if (room.members.contains(user)) {
       ret.add(room);
     }
   }
   return ret;
 }
 /**
  * Obtiene las columnas de la clave primaria de la entidad.
  *
  * @param object Entidad de donde se obtendrán las columnas clave
  * @return Retorna una lista con las columnas de la clave primaria de la entidad
  */
 @SuppressWarnings("unchecked")
 protected List<String> obtenerId(Object object) {
   Class<T> classe = (Class<T>) object.getClass();
   Field[] fields = classe.getDeclaredFields();
   List<String> id = new ArrayList<String>();
   for (Field field : fields) {
     Annotation[] anotaciones = field.getAnnotations();
     for (Annotation annotation : anotaciones) {
       if ("@javax.persistence.Id()".equals(annotation.toString())) {
         id.add(field.getName());
         break;
       } else if ("@javax.persistence.EmbeddedId()".equals(annotation.toString())) {
         String fieldName = field.getName();
         String methodName =
             "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
         try {
           Method method = classe.getMethod(methodName, new Class[] {});
           Object result = method.invoke(object, new Object[] {});
           Class<T> classe1 = (Class<T>) result.getClass();
           Field[] fields1 = classe1.getDeclaredFields();
           for (Field fieldPK : fields1) {
             if (!"serialVersionUID".equals(fieldPK.getName())) {
               id.add(fieldName + "." + fieldPK.getName());
             }
           }
         } catch (RuntimeException e) {
           continue;
         } catch (NoSuchMethodException e) {
           continue;
         } catch (IllegalAccessException e) {
           continue;
         } catch (InvocationTargetException e) {
           continue;
         }
       }
     }
   }
   return id;
 }
Exemple #21
0
 public List<Group> getGroups() {
   List<Group> allGroups = Group.findAll();
   List<Group> answer = new ArrayList<Group>();
   for (Group g : allGroups) {
     for (User u : g.members) {
       if (u.equals(this)) {
         answer.add(g);
         break;
       }
     }
   }
   return answer;
 }
Exemple #22
0
 /**
  * Gets the site roles mapping.
  *
  * @return the site roles mapping
  */
 @Transient
 public Map<String, List<String>> getSiteRolesMapping() {
   Map<String, List<String>> siteRolesMap = new HashMap<String, List<String>>();
   List<String> roleCodeList = null;
   for (SiteResearchStaff siteResearchStaff : getSiteResearchStaffs()) {
     for (SiteResearchStaffRole siteResearchStaffRole :
         siteResearchStaff.getSiteResearchStaffRoles()) {
       roleCodeList = new ArrayList<String>();
       roleCodeList.add(siteResearchStaffRole.getRoleCode());
     }
     siteRolesMap.put(siteResearchStaff.getOrganization().getNciInstituteCode(), roleCodeList);
   }
   return siteRolesMap;
 }
Exemple #23
0
  public List<Method> getMethods(Object objeto) {

    List<Method> methodGet = mappedMethods.get(objeto.getClass());

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

    methodGet = new ArrayList<Method>();
    Method methods[] = objeto.getClass().getMethods();

    List exclude = Arrays.asList(EXCLUDED_FIELDS);

    try {
      Field field;
      String fieldName;
      for (int j = 0; j < methods.length; j++) {
        field = null;
        fieldName = "";
        try {
          if (methods[j] != null
              && !methods[j].isAnnotationPresent(Transient.class)
              && !methods[j].isAnnotationPresent(NotAudited.class)
              && !methods[j].isAnnotationPresent(Id.class)
              && !exclude.contains(methods[j].getName())) {
            fieldName = getMethodName(methods[j]);
          }
          if (fieldName != null && !fieldName.equals("")) {
            try {
              field = getDeclaredField(methods[j].getDeclaringClass(), fieldName);
            } catch (NoSuchFieldException ex) {
              continue;
            }
            if (field != null
                && !field.isAnnotationPresent(Transient.class)
                && !field.isAnnotationPresent(NotAudited.class)
                && !field.isAnnotationPresent(Id.class)) {
              methodGet.add(methods[j]);
            }
          }
        } catch (Exception ex) {
          logger.log(Level.SEVERE, ex.getMessage(), ex);
        }
      }
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getMessage(), ex);
    }
    mappedMethods.put(objeto.getClass(), methodGet);
    return methodGet;
  }
Exemple #24
0
  public static List<String> fioSQLListByType(String doctorTypeName) {
    // TODO: check this statement at latest version of PostgreSQL
    List<String> theList = new ArrayList<String>();
    String sql =
        "SELECT concat(surname, ' ', name, ' ', patronymic) as fio FROM DOCTOR LEFT JOIN DOCTOR_TYPE ON DOCTOR_TYPE.ID = DOCTOR.DOCTOR_TYPE_ID WHERE DOCTOR_TYPE_NAME=:DOCTOR_TYPE_NAME";
    SqlQuery sqlQuery = Ebean.createSqlQuery(sql).setParameter("DOCTOR_TYPE_NAME", doctorTypeName);
    List<SqlRow> rows = sqlQuery.findList();
    // List<SqlRow> rows = Doctor.fioSQLListByType("Терапевт");
    for (SqlRow row : rows) {
      // Logger.info("row: "+ row);
      theList.add(row.getString("fio"));
    }

    return theList;
  }
 private void addListener(
     Map<Class, List<ClassMethodEntry>> listeners,
     Class clazz,
     Method method,
     java.lang.annotation.Annotation annotation,
     Class<? extends Annotation> annotationClass) {
   if (annotation != null) {
     List<ClassMethodEntry> entryList = listeners.get(annotationClass);
     if (entryList == null) {
       entryList = new ArrayList<ClassMethodEntry>();
       listeners.put(annotationClass, entryList);
     }
     //            System.out.println("adding " + method + " for " + annotation);
     entryList.add(new ClassMethodEntry(clazz, method));
   }
 }
Exemple #26
0
 private void completeCalendar() {
   List<DayEnum> dayEnums = DayEnum.getDayEnums();
   Date fromHour = new Date();
   fromHour.setHours(0);
   fromHour.setMinutes(0);
   fromHour.setSeconds(0);
   Date toHour = new Date();
   toHour.setHours(23);
   toHour.setMinutes(0);
   toHour.setSeconds(0);
   for (DayEnum dayEnum : dayEnums) {
     DayRange aux = new DayRange();
     aux.setDayEnum(dayEnum);
     aux.setRange(fromHour, toHour);
     calendar.add(aux);
   }
 }
Exemple #27
0
  private List<Class> findEntityClassesForThisConfig(String configName, String propPrefix) {
    // look and see if we have any Entity-objects for this db config
    List<Class> classes = Play.classloader.getAnnotatedClasses(Entity.class);

    // filter list on Entities meant for us..
    List<Class> filteredClasses = new ArrayList<Class>(classes.size());
    for (Class clazz : classes) {
      if (configName.equals(Entity2JPAConfigResolver.getJPAConfigNameForEntityClass(clazz))) {
        filteredClasses.add(clazz);
      }
    }

    if (!Play.configuration.getProperty(propPrefix + "jpa.entities", "").equals("")) {
      return filteredClasses;
    }

    if (filteredClasses.isEmpty()) {
      return null;
    }

    return filteredClasses;
  }
Exemple #28
0
  // TODO: repair choosing doctor by typename
  public static List<String> fioListByType(String doctorTypeName) {
    /*String query = "find doctor fetch doctor_type.doctor_type_id";
    List<Doctor> doctors = Ebean.find(Doctor.class)
      .setQuery(query)
      .setParameter("doctor_type_id", new Long(1))
      .findList(); */
    String sql =
        "SELECT * FROM DOCTOR LEFT JOIN DOCTOR_TYPE ON DOCTOR_TYPE.ID = DOCTOR.DOCTOR_TYPE_ID";
    SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
    List<SqlRow> list = sqlQuery.findList();
    /*RawSql rawSql = RawSqlBuilder.parse(sql).create();
    javax.persistence.Query<Doctor> query = Ebean.find(Doctor.class);
      query.setRawSql(rawSql);
      //.columnMapping("id",  "doctor.id")
      //.columnMapping("name",  "doctor.name")
      //.columnMapping("surname",  "doctor.surname")
      //.columnMapping("patronymic",  "doctor.patronymic")
      //.columnMapping("patronymic",  "doctor_type.doctor_type_name");
      List<Doctor> doctors = query.findList();  */

    // List<Doctor> doctors = Ebean.find(Doctor.class)
    // .fetch("doctor_type","doctor.doctor_type_id")
    // .findList();
    // List<Doctor> doctors = find.fetch("doctor_type")
    // .where().eq("doctor.doctor_type_name", doctorTypeName)
    // .findList();
    /*com.avaje.ebean.Query q = Ebean.createQuery(Doctor.class);
    q.join("doctor_type");
    final List<Doctor> eventList = q.findList();*/
    List<Doctor> doctors = find.where().eq("doctor_type_id", new Long(1)).findList();
    List<String> theList = new ArrayList<String>();
    for (Doctor doctor : doctors) {
      theList.add(doctor.getFullName());
    }
    return theList;
  }
  public Query buildQuery(Integer type, T example, String... orden) {
    StringBuilder qry;
    List<String> ids = new ArrayList<String>();
    if (type == 1) {
      qry = new StringBuilder(SELECT_COUNT);
      qry.append(example.getClass().getSimpleName());
    } else {
      qry = new StringBuilder(SELECT);
      qry.append(example.getClass().getSimpleName());
      ids = this.obtenerId(example);
    }
    qry.append(FROM);
    qry.append(WHERE);
    List<Object> parametros = new ArrayList();
    Criterio criterio = new Criterio();
    Map<String, Object> propiedades = this.obtenerPropiedades(example);
    criterio.contruccion(propiedades);
    Set<String> igualdad = criterio.igualdad.keySet();
    Integer idx = 1;
    for (String key : igualdad) {
      if (idx > 1) {
        qry.append(AND);
      }
      qry.append(OBJ);
      qry.append(key);
      qry.append(EQ);
      qry.append(idx);
      parametros.add(criterio.igualdad.get(key));
      idx++;
    }

    Set<String> likeKeys = criterio.like.keySet();
    for (String key : likeKeys) {
      if (idx > 1) {
        qry.append(AND);
      }
      Object valor = criterio.like.get(key);
      if (valor instanceof String) {
        qry.append(LOWER);
        qry.append(OBJ);
        qry.append(key);
        qry.append(")");
        qry.append(LIKE);
        qry.append(idx);
        parametros.add(((String) valor).toLowerCase());
      } else {
        qry.append(OBJ);
        qry.append(key);
        qry.append(LIKE);
        qry.append(idx);
        parametros.add(valor);
      }
      idx++;
    }

    Set<String> compositeKeys = criterio.compuesto.keySet();
    for (String key : compositeKeys) {
      Object value = criterio.compuesto.get(key);
      try {
        if (value.toString().startsWith("class java.util")) {
          continue;
        } else if (StringUtils.containsIgnoreCase(key, "pk")) {
          Map<String, Object> propsComposites = this.obtenerPropiedades(value, key);
          Criterio criterioCompuesto = new Criterio();
          criterioCompuesto.contruccion(propsComposites);
          if (!criterioCompuesto.igualdad.isEmpty()) {
            Set<String> eqKeysPK = criterioCompuesto.igualdad.keySet();
            for (String keyPK : eqKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              qry.append(OBJ);
              qry.append(keyPK);
              qry.append(EQ);
              qry.append(idx);
              parametros.add(criterioCompuesto.igualdad.get(keyPK));
              idx++;
            }
          }
          if (!criterioCompuesto.like.isEmpty()) {
            Set<String> likeKeysPK = criterioCompuesto.like.keySet();
            for (String keyPK : likeKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              Object valor = criterioCompuesto.like.get(keyPK);
              if (valor instanceof String) {
                qry.append(LOWER);
                qry.append(OBJ);
                qry.append(keyPK);
                qry.append(")");
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(((String) valor).toLowerCase());
              } else {
                qry.append(OBJ);
                qry.append(keyPK);
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(valor);
              }
              idx++;
            }
          }
        } else {
          Map<String, Object> propsComposites = this.obtenerPropiedades(value);
          Criterio criterioCompuesto = new Criterio();
          criterioCompuesto.contruccion(propsComposites);
          if (!criterioCompuesto.igualdad.isEmpty()) {
            Set<String> eqKeysPK = criterioCompuesto.igualdad.keySet();
            for (String keyPK : eqKeysPK) {
              if (idx > 1) {
                qry.append(AND);
              }
              qry.append(OBJ);
              qry.append(key);
              qry.append(".");
              qry.append(keyPK);
              qry.append(EQ);
              qry.append(idx);
              parametros.add(criterioCompuesto.igualdad.get(keyPK));
              idx++;
            }
          }
          if (!criterioCompuesto.like.isEmpty()) {
            Set<String> likeKeysPK = criterioCompuesto.like.keySet();
            for (String keyPK : likeKeysPK) {
              System.out.println(
                  "Compuesto LIKE: " + keyPK + ", " + criterioCompuesto.igualdad.get(keyPK));
              if (idx > 1) {
                qry.append(AND);
              }
              Object valor = criterioCompuesto.like.get(keyPK);
              if (valor instanceof String) {
                qry.append(LOWER);
                qry.append(OBJ);
                qry.append(key);
                qry.append(".");
                qry.append(keyPK);
                qry.append(")");
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(((String) valor).toLowerCase());
              } else {
                qry.append(OBJ);
                qry.append(key);
                qry.append(".");
                qry.append(keyPK);
                qry.append(LIKE);
                qry.append(idx);
                parametros.add(valor);
              }
              idx++;
            }
          }
        }
      } catch (RuntimeException e) {
        continue;
      }
    }

    if (idx == 1) {
      qry.append(" 1=1");
    }
    if (!ids.isEmpty()) {
      qry.append(ORDER);
    } else {
      qry.append("  ");
    }
    if (orden.length > 0) {
      for (String ord : orden) {
        qry.append(OBJ);
        qry.append(ord.substring(2));
        if (ord.startsWith("A,")) {
          qry.append(ASC);
        } else if (ord.startsWith("D,")) {
          qry.append(DESC);
        }
      }
    } else {
      for (String id : ids) {
        if (!id.contains("_persistence")) {
          qry.append(OBJ);
          qry.append(id);
          qry.append(ASC);
        }
      }
    }

    System.out.println(qry.substring(0, qry.length() - 2));
    Query query = this.em.createQuery(qry.substring(0, qry.length() - 2));
    if (!parametros.isEmpty()) {
      int i = 1;
      for (Object obj : parametros) {
        query.setParameter(i, obj);
        i++;
      }
    }
    return query;
  }
Exemple #30
0
 public Boulder tick(String name) {
   haveSent.add(Climber.find.ref(name));
   this.update();
   return this;
 }