Exemplo n.º 1
0
  public static String getEntityName(Class entity) {

    if (mappedName.get(entity) != null) {
      return mappedName.get(entity);
    }

    String name = null;

    Table table = (Table) entity.getAnnotation(Table.class);
    if (table != null && table.name() != null && !table.name().isEmpty()) {
      name = table.name();
    } else {
      Entity entityAnnotation = (Entity) entity.getAnnotation(Entity.class);
      if (entityAnnotation != null
          && entityAnnotation.name() != null
          && !entityAnnotation.name().isEmpty()) {
        name = entityAnnotation.name();
      } else {
        name = entity.getSimpleName();
      }
    }

    mappedName.put(entity, name);

    return name;
  }
Exemplo n.º 2
0
 private Collection<ConversationSummary> fetchCorrespondents(final User user) {
   final Map<String, ConversationSummary> correspondants =
       new HashMap<String, ConversationSummary>();
   {
     final Query query =
         query(
             "select m.sender.name, m.receiver.name, count(m), m.read from PrivateMessageImpl m where (m.receiver=:user OR "
                 + "(m.sender=:user)) AND(m.deleter IS NULL OR m.deleter <> :user) "
                 + "group by m.sender.name, m.receiver.name, m.read");
     query.setParameter("user", user);
     for (final Object[] row : (List<Object[]>) query.getResultList()) {
       final boolean sent = row[0].equals(((UserImpl) user).getBareName());
       final String name = (String) (sent ? row[1] : row[0]);
       final ConversationSummary previous = correspondants.get(name);
       final long count = ((Number) row[2]).longValue();
       final long newCount;
       if (row[3].equals(Boolean.FALSE) && !sent) newCount = count;
       else newCount = 0;
       if (previous != null) {
         correspondants.put(
             name,
             new ConversationSummary(
                 UserStringImpl.valueOf(name),
                 count + previous.messageCount,
                 newCount + previous.newMessageCount));
       } else
         correspondants.put(
             name, new ConversationSummary(UserStringImpl.valueOf(name), count, newCount));
     }
   }
   return new TreeSet<ConversationSummary>(correspondants.values());
 }
Exemplo n.º 3
0
 public boolean isOneToOneCascadeAll(Method method) throws Exception {
   Boolean isOneToOneAll = mappedOneToOneCascadeAll.get(method);
   if (isOneToOneAll != null) {
     return isOneToOneAll;
   }
   OneToOne oneToOne = method.getAnnotation(OneToOne.class);
   if (oneToOne == null) {
     Field field = getDeclaredField(method.getDeclaringClass(), getMethodName(method));
     if (field != null) {
       oneToOne = field.getAnnotation(OneToOne.class);
     }
   }
   CascadeType[] cascadeTypes = null;
   if (oneToOne != null) {
     cascadeTypes = oneToOne.cascade();
   }
   if (oneToOne != null
       && cascadeTypes != null
       && cascadeTypes.length > 0
       && Arrays.asList(cascadeTypes).contains(CascadeType.ALL)) {
     isOneToOneAll = true;
   } else {
     isOneToOneAll = false;
   }
   mappedOneToOneCascadeAll.put(method, isOneToOneAll);
   return isOneToOneAll;
 }
Exemplo n.º 4
0
 public static Map<String, String> typesMap() {
   Map<String, String> theMap = new HashMap<String, String>();
   for (IdentityDocType type : all()) {
     theMap.put(type.id.toString(), type.identityDocTypeName);
   }
   return theMap;
 }
Exemplo n.º 5
0
 @Transient
 public UserScore getCurrentScore() {
   QuestionPackType currentQuestionPack = QuestionPackType.packForToday();
   UserScore score = userScores.get(currentQuestionPack);
   if (score == null) {
     score = new UserScore();
     userScores.put(currentQuestionPack, score);
   }
   return score;
 }
Exemplo n.º 6
0
 public PullRequestMergeResult getPullRequestMergeResult() {
   PullRequestMergeResult mergeResult = null;
   if (!StringUtils.isEmpty(this.fromBranch) && !StringUtils.isEmpty(this.toBranch)) {
     mergeResult = this.attemptMerge();
     Map<String, String> suggestText =
         suggestTitleAndBodyFromDiffCommit(mergeResult.getGitCommits());
     this.title = suggestText.get("title");
     this.body = suggestText.get("body");
   }
   return mergeResult;
 }
Exemplo n.º 7
0
  // SELECT DOCTOR .id as id, concat(surname, ' ', name, ' ', patronymic) as fio, doctor_type_name
  // as type FROM DOCTOR LEFT JOIN DOCTOR_TYPE ON DOCTOR_TYPE.ID = DOCTOR.DOCTOR_TYPE_ID
  public static Map<String, String> fioMapByType(Long doctorTypeNameId) {
    // TODO: check this statement at latest version of PostgreSQL
    Map<String, String> theMap = new HashMap<String, String>();
    String sql =
        "SELECT DOCTOR.id as id, concat(surname, ' ', name, ' ', patronymic) as fio FROM DOCTOR LEFT JOIN DOCTOR_TYPE ON DOCTOR_TYPE.ID = DOCTOR.DOCTOR_TYPE_ID WHERE doctor_type.id=:type_id";
    SqlQuery sqlQuery = Ebean.createSqlQuery(sql).setParameter("type_id", doctorTypeNameId);
    List<SqlRow> rows = sqlQuery.findList();
    for (SqlRow row : rows) {
      theMap.put(row.getString("id"), row.getString("fio"));
    }

    return theMap;
  }
Exemplo n.º 8
0
 public boolean equals(Object o) {
   Employee e = (Employee) o;
   Map<String, PhoneNumber> map = e.getPhoneNumbers();
   if (map.size() != phones.size()) return false;
   Collection<Map.Entry<String, PhoneNumber>> entries =
       (Collection<Map.Entry<String, PhoneNumber>>) phones.entrySet();
   for (Map.Entry<String, PhoneNumber> entry : entries) {
     String key = entry.getKey();
     PhoneNumber p = entry.getValue();
     PhoneNumber p0 = map.get(key);
     if (p.getNumber() != p0.getNumber()) return false;
   }
   return true;
 }
Exemplo n.º 9
0
  /** @param args */
  public static void main(String[] args) {
    EntityManagerFactory emf = null;
    EntityManager em = null;

    Map<String, String> properties = new HashMap<String, String>();

    properties.put(DDL_GENERATION, DROP_AND_CREATE);
    properties.put(DDL_GENERATION_MODE, DDL_BOTH_GENERATION);
    properties.put(TARGET_DATABASE, TargetDatabase.Oracle);

    emf = PersistenceService.createEMF(properties, true, new EclipseLinkServiceFactory(), true);
    em = emf.createEntityManager();
    em.close();
    emf.close();
  }
Exemplo n.º 10
0
 public int getVotes() {
   votes = 0;
   for (Map.Entry<User, Integer> entry : userVotes.entrySet()) {
     votes += entry.getValue();
   }
   return votes;
 }
Exemplo n.º 11
0
 /** Initialise JPA entity manager factories. */
 public JPAApi start() {
   for (JPAConfig.PersistenceUnit persistenceUnit : jpaConfig.persistenceUnits()) {
     emfs.put(
         persistenceUnit.name, Persistence.createEntityManagerFactory(persistenceUnit.unitName));
   }
   return this;
 }
Exemplo n.º 12
0
 @Transient
 public Map<Integer, String> getDivisionMap() {
   Map<Integer, String> result = new LinkedHashMap<Integer, String>();
   if (null != this.getDivisions()) {
     String[] temp = this.getDivisions().replaceAll("[\\]\\[]", "").split(",");
     for (int i = 0; i < temp.length; i++) {
       String divis = temp[i];
       if (divis.matches("\\d+")) {
         Integer id = Integer.parseInt(divis);
         result.put(Integer.parseInt(divis), JTZSConstants.Division.getName(id));
       }
     }
   }
   ;
   return result;
 }
Exemplo n.º 13
0
 /**
  * Get the EntityManager for the specified persistence unit name.
  *
  * @param name The persistence unit name
  */
 public EntityManager em(String name) {
   EntityManagerFactory emf = emfs.get(name);
   if (emf == null) {
     return null;
   }
   return emf.createEntityManager();
 }
Exemplo n.º 14
0
  /**
   * Obtiene las propiedades de la entidad a la cual pertenece el DAO.
   *
   * @param object entidad a la que pertenece el DAO.
   * @param clave la entidad embebida que contiene la clave primaria
   * @return Mapa con las propiedades y los valores, el cual será utilizado para la construcción de
   *     los criterios en la ejecución de la búsqueda.
   */
  @SuppressWarnings("unchecked")
  private Map<String, Object> obtenerPropiedades(Object object, String... clave) {
    Class<T> classe = (Class<T>) object.getClass();
    Field[] fields = classe.getDeclaredFields();
    Map<String, Object> mapa = new HashMap<String, Object>(fields.length);
    for (Field field : fields) {
      Boolean isClob = Boolean.FALSE;
      Annotation[] anotaciones = field.getAnnotations();
      for (Annotation annotation : anotaciones) {
        if ("@javax.persistence.Lob()".equals(annotation.toString())
            || "@javax.persistence.Transient()".equals(annotation.toString())) {
          isClob = Boolean.TRUE;
          break;
        }
      }
      if (!isClob) {
        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[] {});

          if (result != null) {
            if (clave != null && clave.length == 1) {
              mapa.put(clave[0] + "." + field.getName(), result);
            } else {
              mapa.put(field.getName(), result);
            }
          }
        } catch (RuntimeException e) {
          continue;
        } catch (NoSuchMethodException e) {
          continue;
        } catch (IllegalAccessException e) {
          continue;
        } catch (InvocationTargetException e) {
          continue;
        }
      }
    }
    return mapa;
  }
Exemplo n.º 15
0
  /**
   * Gets all the annotation info for a particular class and puts it in our annotation info cache.
   *
   * @param c
   * @return
   */
  public AnnotationInfo putAnnotationInfo(Class c) {
    {
      Entity entity = (Entity) c.getAnnotation(Entity.class);
      if (entity == null) {
        throw new PersistenceException("Class not marked as an @Entity: " + c.getName());
      }
    }
    AnnotationInfo ai = new AnnotationInfo();
    ai.setClassAnnotations(c.getAnnotations());
    ai.setMainClass(c);
    Class superClass = c;
    Class rootClass = null;
    while ((superClass = superClass.getSuperclass()) != null) {
      MappedSuperclass mappedSuperclass =
          (MappedSuperclass) superClass.getAnnotation(MappedSuperclass.class);
      Entity entity = (Entity) superClass.getAnnotation(Entity.class);
      Inheritance inheritance = (Inheritance) superClass.getAnnotation(Inheritance.class);
      if (mappedSuperclass != null || entity != null) {
        putProperties(ai, superClass);
        putMethods(ai, superClass);
        if (entity != null) {
          rootClass = superClass;
        }
        putEntityListeners(ai, superClass);
      }
    }
    if (rootClass != null) {
      ai.setRootClass(rootClass);
      DiscriminatorValue dv = (DiscriminatorValue) c.getAnnotation(DiscriminatorValue.class);
      String discriminatorValue;
      if (dv != null) {
        discriminatorValue = dv.value();
        if (discriminatorValue == null) {
          throw new PersistenceException(
              "You must specify a value= for @DiscriminatorValue on " + c.getName());
        }
      } else {
        discriminatorValue = c.getSimpleName();
      }
      ai.setDiscriminatorValue(discriminatorValue);
      discriminatorMap.put(discriminatorValue, ai);
    } else {
      ai.setRootClass(c);
    }
    putTableDeclaration(ai, c);
    putProperties(ai, c);
    putMethods(ai, c);
    if (ai.getIdMethod() == null) {
      throw new PersistenceException("No ID method specified for: " + c.getName());
    }
    putEntityListeners(ai, c);

    getAnnotationMap().put(c.getName(), ai);
    return ai;
  }
Exemplo n.º 16
0
  /**
   * diff commit message로 pull request의 title과 body를 채운다.<br>
   * <br>
   * case 1 : commit이 한개이고 message가 한줄일 경우 title에 추가한다.<br>
   * case 2 : commit이 한개이고 message가 여러줄일 경우 첫번째줄 mesage는 title 나머지 message는 body에 추가<br>
   * case 3 : commit이 여러개일 경우 각 commit의 첫번째줄 message들을 모아서 body에 추가 <br>
   *
   * @param commits
   * @return
   */
  private Map<String, String> suggestTitleAndBodyFromDiffCommit(List<GitCommit> commits) {
    Map<String, String> messageMap = new HashMap<>();

    String message;

    if (commits.isEmpty()) {
      return messageMap;

    } else if (commits.size() == 1) {
      message = commits.get(0).getMessage();
      String[] messages = message.split(Constants.NEW_LINE_DELIMETER);

      if (messages.length > 1) {
        String[] msgs = Arrays.copyOfRange(messages, 1, messages.length);
        messageMap.put("title", messages[0]);
        messageMap.put("body", StringUtils.join(msgs, Constants.NEW_LINE_DELIMETER));

      } else {
        messageMap.put("title", messages[0]);
        messageMap.put("body", StringUtils.EMPTY);
      }

    } else {
      String[] firstMessages = new String[commits.size()];
      for (int i = 0; i < commits.size(); i++) {
        String[] messages = commits.get(i).getMessage().split(Constants.NEW_LINE_DELIMETER);
        firstMessages[i] = messages[0];
      }
      messageMap.put("body", StringUtils.join(firstMessages, Constants.NEW_LINE_DELIMETER));
    }

    return messageMap;
  }
Exemplo n.º 17
0
 private void initProperties() {
   synchronized (this) {
     if (properties != null) return;
     properties = new HashMap<String, Model.Property>();
     Set<Field> fields = getModelFields(clazz);
     for (Field f : fields) {
       int mod = f.getModifiers();
       if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) {
         continue;
       }
       if (f.isAnnotationPresent(Transient.class)) {
         continue;
       }
       Model.Property mp = buildProperty(f);
       if (mp != null) {
         properties.put(mp.name, mp);
       }
     }
   }
 }
Exemplo n.º 18
0
 /**
  * Método que inspecciona las propiedades de una entidad y los valores asignados a cada
  * propiedad para la construcción de los criterios a ser aplicados al momento de ejecutar una
  * búsqueda.
  *
  * @param propiedades Mapa de propiedades de una entidad con los valores que serán utilizados
  *     como criterios para la ejecución de una búsqueda.
  */
 public void contruccion(Map<String, Object> propiedades) {
   Set<String> keys = propiedades.keySet();
   for (String key : keys) {
     Object value = propiedades.get(key);
     if (value.getClass().toString().startsWith("class java.sql")) {
       continue;
     } else if (value.getClass().toString().startsWith("class java.lang")) {
       if (value.toString().indexOf('%') >= 0) {
         like.put(key, value);
       } else if (value.toString().length() > 0) {
         igualdad.put(key, value);
       }
     } else if (value.getClass().toString().startsWith("class java.util.Date")
         && value instanceof Date) {
       // Fechas solo puede realizar igualdad
       igualdad.put(key, value);
     } else {
       compuesto.put(key, value);
     }
   }
 }
Exemplo n.º 19
0
 public void setCurrentScore(UserScore score) {
   userScores.put(QuestionPackType.packForToday(), score);
 }
Exemplo n.º 20
0
 public void removePhoneNumber(String str) {
   phones.remove(str);
 }
Exemplo n.º 21
0
 public void setPhoneNumbers(PhoneType type, String number) {
   phoneNumbers.put(type, number);
 }
Exemplo n.º 22
0
 public AnnotationInfo getAnnotationInfoByDiscriminator(String discriminatorValue) {
   return discriminatorMap.get(discriminatorValue);
 }
Exemplo n.º 23
0
 public void addPhoneNumber(String str, PhoneNumber phoneNumber) {
   phones.put(str, phoneNumber);
 }
Exemplo n.º 24
0
 /** Close all entity manager factories. */
 public void shutdown() {
   for (EntityManagerFactory emf : emfs.values()) {
     emf.close();
   }
 }