Ejemplo n.º 1
0
  /**
   * Persists a Audit
   *
   * @param object
   * @param persisted
   * @param auditingType
   */
  public void audit(Object object, Object persisted, AuditingType auditingType) {

    try {

      if (isEntity(object)) {

        Field[] fields = object.getClass().getDeclaredFields();
        Method[] methods = object.getClass().getDeclaredMethods();
        Method.setAccessible(methods, true);
        Field.setAccessible(fields, true);

        AbstractAuditing auditing = Configuration.getAbstractAuditing();
        auditing.setIdentifier(Long.valueOf(getId(object).toString()));
        auditing.setEntity(getEntityName(object.getClass()));
        auditing.setAuditingType(auditingType);
        auditing.setEventDate(new Date());
        if (FacesContext.getCurrentInstance() != null) {
          auditing.setIp(FacesUtils.getIP());
        }
        auditing.setAuditClass(object.getClass());
        AbstractAuditingListener listener = Configuration.getAuditingListener();
        if (listener != null) {
          listener.onSave(auditing);
        }

        List<AbstractMetadata> metadatas = null;
        boolean auditPersited = false;
        if (auditingType.equals(AuditingType.INSERT) || auditingType.equals(AuditingType.DELETE)) {
          entityManager.persist(auditing);
          metadatas = getMetadata(object, null, auditing);
          auditPersited = true;
        } else if (auditingType.equals(AuditingType.UPDATE)) {
          metadatas = getMetadata(object, persisted, auditing);
          if (metadatas != null && !metadatas.isEmpty()) {
            entityManager.persist(auditing);
            auditPersited = true;
          }
        }

        auditing.setMetadatas(metadatas);
        // add to context
        if (auditPersited == true) {
          AuditContext context = AuditContext.getCurrentInstance();
          if (context != null) {
            context.setAuditing(object, auditing);
          }
        }

        if (metadatas != null && !metadatas.isEmpty()) {
          for (AbstractMetadata metadata : metadatas) {
            entityManager.persist(metadata);
          }
        }
      }
    } catch (Throwable t) {
      logger.log(Level.SEVERE, t.getMessage(), t);
    }
  }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 3
0
 public void forgotPassword(final String email) throws UserNotFoundException, MailException {
   final Query query =
       entityManager.createQuery("select u from UserImpl u where u.email=:cryptedMail");
   query.setParameter("cryptedMail", CipherHelper.cipher(email));
   final List<UserImpl> list = query.getResultList();
   if (list.isEmpty()) throw new UserNotFoundException();
   for (final UserImpl user : list) {
     final String password = Helper.randomstring();
     user.setPassword(password);
     MailSender.forgotPasswordMail(user.getName(), password, email);
     entityManager.merge(user);
   }
 }
Ejemplo n.º 4
0
 String getSearchQuery(List<String> searchFields) {
   String q = "";
   for (Model.Property property : listProperties()) {
     if (property.isSearchable
         && (searchFields == null || searchFields.isEmpty()
             ? true
             : searchFields.contains(property.name))) {
       if (!q.equals("")) {
         q += " or ";
       }
       q += "lower(" + property.name + ") like ?1";
     }
   }
   return q;
 }
 /**
  * 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;
 }
Ejemplo n.º 6
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;
  }
Ejemplo n.º 7
0
  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;
  }
Ejemplo n.º 8
0
  public List<AbstractMetadata> getMetadata(
      Object object, Object persisted, AbstractAuditing auditing) throws Exception {
    List<Method> methodsGet = getMethods(object);
    List<AbstractMetadata> metadatas = new ArrayList<AbstractMetadata>();
    boolean isDelete =
        auditing.getAuditingType() != null
            && auditing.getAuditingType().equals(AuditingType.DELETE);
    for (Method method : methodsGet) {
      try {
        Object fieldValue = method.invoke(object);
        Object fieldOld = null;
        if (persisted != null) {
          fieldOld = method.invoke(persisted);
        }
        AbstractMetadata metadata = Configuration.getAbstractMetadata();
        if (fieldValue != null && fieldValue.getClass().isAnnotationPresent(Embeddable.class)) {
          List<AbstractMetadata> embedableMetadata = getMetadata(fieldValue, persisted, auditing);
          if (embedableMetadata != null && !embedableMetadata.isEmpty()) {
            metadatas.addAll(embedableMetadata);
          }
        } else {
          boolean addMetadata = persisted == null;
          if (fieldValue instanceof Collection) { // para as coleções
            Collection collectionNew = (Collection<Object>) fieldValue;
            Collection collectionOld = (Collection<Object>) fieldOld;
            StringBuilder newValue = new StringBuilder();
            if (fieldOld == null) {
              for (Object item : collectionNew) {
                newValue.append(item.toString()).append("; ");
              }
              addMetadata = true;
            } else {
              StringBuilder oldValue = new StringBuilder();
              if ((!(collectionNew instanceof PersistentBag)
                      && !(collectionNew instanceof PersistentCollection))
                  || isDelete == true) {
                if ((collectionNew == null && collectionOld != null)
                    || (collectionNew != null && collectionOld == null)
                    || (collectionNew.size() != collectionOld.size())) {
                  addMetadata = true;
                } else {
                  for (Object current : collectionNew) {
                    if (collectionOld != null && !collectionOld.contains(current)) {
                      for (Object currentOld : collectionOld) {
                        if (!currentOld.equals(current)) {
                          addMetadata = true;
                          break;
                        }
                      }
                    }
                  }
                }
                for (Object old : collectionOld) {
                  oldValue.append(old).append("; ");
                }
                for (Object item : collectionNew) {
                  newValue.append(item.toString()).append("; ");
                }
                metadata.setOldValue(oldValue.toString());
              }
            }
            metadata.setNewValue(newValue.toString());
          } else if (isEntity(method.getReturnType())) {
            Object newId = getId(fieldValue);
            // a proxy doesnt has value changed
            if (!(fieldValue instanceof HibernateProxy) || isDelete == true) {
              /** One to One cascade ALL */
              if (isOneToOneCascadeAll(method)) {
                List<AbstractMetadata> embedableMetadata = null;
                // add metadata for oneToOne cascade all based on new object
                if (persisted == null) {
                  embedableMetadata = getMetadata(fieldValue, null, auditing);
                } else {
                  embedableMetadata = getMetadata(fieldValue, getPersisted(fieldValue), auditing);
                }

                if (embedableMetadata != null && !embedableMetadata.isEmpty()) {
                  metadatas.addAll(embedableMetadata);
                }
              }

              Object oldId = null;
              if (fieldOld instanceof HibernateProxy) {
                oldId = ((HibernateProxy) fieldOld).getHibernateLazyInitializer().getIdentifier();
              } else {
                oldId = getId(fieldOld);
              }
              metadata.setOldIdentifier(oldId == null ? null : Long.valueOf(oldId.toString()));
              metadata.setOldValue(fieldOld == null ? "" : fieldOld.toString());
              if ((oldId == null && newId != null)
                  || (oldId != null && newId == null)
                  || (oldId != null && !oldId.equals(newId))) {
                addMetadata = true;
              }
              metadata.setEntity(method.getDeclaringClass().getName());
              metadata.setNewIdentifier(newId == null ? null : Long.valueOf(newId.toString()));
              metadata.setNewValue(fieldValue == null ? "" : fieldValue.toString());
            }
          } else {
            if (fieldOld != null) {
              metadata.setOldValue(getToString(fieldOld));
            }
            if (fieldValue != null) {
              metadata.setNewValue(getToString(fieldValue));
            }
            // verify empty String
            if (fieldValue instanceof String) {
              if ((fieldOld == null && fieldValue != null && !fieldValue.toString().isEmpty())
                  || (fieldOld != null && !fieldOld.toString().isEmpty() && fieldValue == null)
                  || (fieldOld != null && !fieldOld.equals(fieldValue))) {
                addMetadata = true;
              }
            } else {
              if ((fieldOld == null && fieldValue != null)
                  || (fieldOld != null && fieldValue == null)
                  || (fieldOld != null && !fieldOld.equals(fieldValue))) {
                addMetadata = true;
              }
            }
          }
          metadata.setField(getMethodName(method));
          metadata.setAuditing(auditing);
          if (addMetadata) {
            metadatas.add(metadata);
          }
        }
      } catch (Throwable t) {
        logger.log(Level.SEVERE, t.getMessage(), t);
      }
    }
    return metadatas;
  }