Example #1
0
 public <T extends PersistentObject> int updateObject(
     String sql, BeanSqlSetter<T> sqlSetter, T bean) throws SystemError, LogicError {
   try {
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         sqlSetter.setParams(stm, bean);
         int res = stm.executeUpdate();
         if (res == 1) bean.saved();
         return res;
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
   } catch (LogicError e) {
     logger.error("Error", e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error", e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
  private Query getQueryTotalesPorFuente(
      Session session, Long idPais, Integer anio, boolean excluirSACM) {

    StringBuffer buffer = new StringBuffer();
    buffer
        .append("SELECT new " + MontoPorDerecho.class.getName() + "(")
        .append(
            "dc.idFuente, dc.nombreFuente, dc.nombreDerechoExterno, dc.trimestre, SUM(dc.montoPercibido)) ")
        .append("FROM DatosCancion dc ");

    if (excluirSACM) {
      buffer.append("WHERE dc.companyId != :companyId ");

    } else {
      buffer.append("WHERE dc.companyId = :companyId ");
    }

    buffer
        .append(DaoUtils.getWhereClause(null, anio, idPais, null))
        .append("GROUP BY dc.idFuente, dc.nombreDerechoExterno, dc.trimestre ")
        .append("ORDER BY dc.idFuente, dc.nombreDerechoExterno");

    Query query = session.createQuery(buffer.toString());
    query.setParameter("companyId", Configuracion.SACM_COMPANY_ID);

    DaoUtils.setearParametros(query, idPais, anio, null, null);

    return query;
  }
Example #3
0
 public int update(String sql, Object... params) throws SystemError, LogicError {
   try {
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         setParams(stm, params);
         return stm.executeUpdate();
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
   } catch (LogicError e) {
     logger.error("Error", e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error", e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
  @SuppressWarnings("unchecked")
  @Transactional(value = "transactionManager")
  private List<MontoTotal> getMontosTotalesPorPais(
      Integer anio, Integer trimestre, Pais pais, boolean excluirSACM) {

    Session session = sessionFactory.getCurrentSession();

    StringBuffer buffer = new StringBuffer();
    buffer
        .append("SELECT new " + MontoTotal.class.getName() + "(")
        .append(anio)
        .append(", ")
        .append(trimestre)
        .append(", dc.idPais, dc.nombrePais, SUM(dc.montoPercibido)) ")
        .append("FROM DatosCancion dc ");

    if (excluirSACM) {
      buffer.append("WHERE dc.companyId != :companyId ");

    } else {
      buffer.append("WHERE dc.companyId = :companyId ");
    }

    buffer
        .append(
            DaoUtils.getWhereClause(trimestre, anio, (pais != null) ? pais.getId() : null, null))
        .append("GROUP BY dc.idPais");

    Query query = session.createQuery(buffer.toString());
    query.setParameter("companyId", Configuracion.SACM_COMPANY_ID);

    DaoUtils.setearParametros(query, (pais != null) ? pais.getId() : null, anio, trimestre, null);

    List<MontoTotal> montos = query.list();

    if (pais == null) {

      List<Pais> todosLosPaises = getPaises();
      for (Pais otroPais : todosLosPaises) {

        MontoTotal nuevoMonto = new MontoTotal(anio, trimestre, otroPais, 0.0);
        if (!montos.contains(nuevoMonto)) {
          montos.add(nuevoMonto);
        }
      }
    }

    Collections.sort(montos, new MontoTotal.ComparadorPorPais());

    return montos;
  }
  @Override
  @TransactionalRollbackAllExceptions
  public String create(Event event, EventPreCreateContext context) throws ZepException {
    if (!ZepConstants.CLOSED_STATUSES.contains(event.getStatus())) {
      throw new ZepException("Invalid status for event in event archive: " + event.getStatus());
    }

    TypeConverter<Long> timestampConverter = databaseCompatibility.getTimestampConverter();
    Map<String, Object> occurrenceFields = eventDaoHelper.createOccurrenceFields(event);
    Map<String, Object> fields = new HashMap<String, Object>(occurrenceFields);
    final long created = event.getCreatedTime();
    final long firstSeen = (event.hasFirstSeenTime()) ? event.getFirstSeenTime() : created;
    long updateTime = System.currentTimeMillis();
    final String uuid = this.uuidGenerator.generate().toString();
    fields.put(COLUMN_UUID, uuidConverter.toDatabaseType(uuid));
    fields.put(COLUMN_STATUS_ID, event.getStatus().getNumber());
    fields.put(COLUMN_FIRST_SEEN, timestampConverter.toDatabaseType(firstSeen));
    fields.put(COLUMN_STATUS_CHANGE, timestampConverter.toDatabaseType(created));
    fields.put(COLUMN_LAST_SEEN, timestampConverter.toDatabaseType(created));
    fields.put(COLUMN_EVENT_COUNT, event.getCount());
    fields.put(COLUMN_UPDATE_TIME, timestampConverter.toDatabaseType(updateTime));

    this.template.update(DaoUtils.createNamedInsert(TABLE_EVENT_ARCHIVE, fields.keySet()), fields);
    return uuid;
  }
  /**
   * @param clusterId
   * @param hostName
   */
  @Transactional
  public void removeHost(final long clusterId, String hostName) {

    populateCache();

    Set<HostConfigMapping> set = hostConfigMappingByHost.get(hostName);

    // Remove from cache items with clusterId
    CollectionUtils.filter(
        set,
        new Predicate() {

          @Override
          public boolean evaluate(Object arg0) {
            return !((HostConfigMapping) arg0).getClusterId().equals(clusterId);
          }
        });

    // delete from db
    TypedQuery<HostConfigMappingEntity> query =
        entityManagerProvider
            .get()
            .createQuery(
                "SELECT entity FROM HostConfigMappingEntity entity "
                    + "WHERE entity.clusterId = ?1 AND entity.hostName = ?2",
                HostConfigMappingEntity.class);

    List<HostConfigMappingEntity> list =
        daoUtils.selectList(query, Long.valueOf(clusterId), hostName);

    for (HostConfigMappingEntity entity : list) {
      entityManagerProvider.get().remove(entity);
    }
  }
Example #7
0
  @Test
  public void testOrderEntitiesByPrimaryKeys() {
    final List<Persistable> entities = new ArrayList<Persistable>();
    final Persistable persistable1 = control.createMock(Persistable.class);
    final Persistable persistable2 = control.createMock(Persistable.class);
    final Persistable persistable3 = control.createMock(Persistable.class);
    CollectionUtils.addAll(entities, persistable1, persistable2, persistable3);

    final String pk1 = new String("pk1");
    final String pk2 = new String("pk2");
    final String pk3 = new String("pk3");
    expect(persistable1.getPrimaryKey()).andReturn(pk1);
    expect(persistable2.getPrimaryKey()).andReturn(pk2);
    expect(persistable3.getPrimaryKey()).andReturn(pk3);

    final List<String> primaryKeys = new LinkedList<String>();
    CollectionUtils.addAll(primaryKeys, pk1, pk3, pk2);

    control.replay();
    final List<Persistable> orderedList =
        DaoUtils.orderEntitiesByPrimaryKeys(entities, primaryKeys);
    control.verify();

    assertEquals(orderedList.get(0), persistable1);
    assertEquals(orderedList.get(1), persistable3);
    assertEquals(orderedList.get(2), persistable2);
  }
Example #8
0
  /**
   * Gets all alert definitions stored in the database.
   *
   * @return all alert definitions or an empty list if none exist (never {@code null}).
   */
  public List<AlertDefinitionEntity> findAll() {
    TypedQuery<AlertDefinitionEntity> query =
        entityManagerProvider
            .get()
            .createNamedQuery("AlertDefinitionEntity.findAll", AlertDefinitionEntity.class);

    return daoUtils.selectList(query);
  }
Example #9
0
 public <T extends PersistentObject> T queryForObject(
     String sql, BeanCreator<T> creator, Object... params) throws SystemError, LogicError {
   try {
     T ret = null;
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         setParams(stm, params);
         ResultSet rs = stm.executeQuery();
         try {
           int rowNum = 0;
           while (rs.next()) {
             ret = creator.getBean(rs, rowNum);
             ret.saved();
             if (rowNum > 1)
               throw new LogicError("Error in query execution : il resultSet ha piĆ¹ di una riga");
             rowNum++;
           }
         } finally {
           rs.close();
         }
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
     return ret;
   } catch (LogicError e) {
     logger.error("Error", e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error", e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error", e);
     throw new SystemError("Error in query execution :" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error", e);
     throw new SystemError("Error in esecuzione metodo:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
Example #10
0
 public <T extends PersistentObject> List<T> queryForList(
     String sql, BeanCreator<T> creator, Object... params) throws SystemError, LogicError {
   try {
     List<T> ret = new ArrayList<T>();
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         setParams(stm, params);
         ResultSet rs = stm.executeQuery();
         try {
           int rowNum = 0;
           while (rs.next()) {
             T bean = creator.getBean(rs, rowNum);
             bean.saved();
             ret.add(bean);
             rowNum++;
           }
         } finally {
           rs.close();
         }
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
     return ret;
   } catch (LogicError e) {
     logger.error("Error in sql:" + sql, e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error in sql:" + sql, e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error in sql:" + sql, e);
     throw new SystemError("Error in query execution :" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error in sql:" + sql, e);
     throw new SystemError("Error in esecuzione metodo:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
Example #11
0
 public List<Map<String, Object>> queryFor(String sql, Object... params)
     throws SystemError, LogicError {
   try {
     List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         setParams(stm, params);
         ResultSet rs = stm.executeQuery();
         ResultSetMetaData mt = rs.getMetaData();
         try {
           while (rs.next()) {
             Map<String, Object> row = new HashMap<String, Object>();
             for (int i = 0; i < mt.getColumnCount(); i++)
               row.put(mt.getColumnName(i + 1), rs.getObject(i + 1));
             ret.add(row);
           }
         } finally {
           rs.close();
         }
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
     return ret;
   } catch (LogicError e) {
     logger.error("Error", e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error", e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error", e);
     throw new SystemError("Error in query execution :" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error", e);
     throw new SystemError("Error in esecuzione metodo:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
Example #12
0
  /**
   * Gets all alert definitions stored in the database.
   *
   * @return all alert definitions or empty list if none exist (never {@code null}).
   */
  public List<AlertDefinitionEntity> findAll(long clusterId) {
    TypedQuery<AlertDefinitionEntity> query =
        entityManagerProvider
            .get()
            .createNamedQuery(
                "AlertDefinitionEntity.findAllInCluster", AlertDefinitionEntity.class);

    query.setParameter("clusterId", clusterId);

    return daoUtils.selectList(query);
  }
Example #13
0
  /**
   * Gets an alert definition with the specified name. Alert definition names are unique within a
   * cluster.
   *
   * @param clusterId the ID of the cluster.
   * @param definitionName the name of the definition (not {@code null}).
   * @return the alert definition or {@code null} if none exists.
   */
  public AlertDefinitionEntity findByName(long clusterId, String definitionName) {
    TypedQuery<AlertDefinitionEntity> query =
        entityManagerProvider
            .get()
            .createNamedQuery("AlertDefinitionEntity.findByName", AlertDefinitionEntity.class);

    query.setParameter("clusterId", clusterId);
    query.setParameter("definitionName", definitionName);

    return daoUtils.selectSingle(query);
  }
  @Transactional(value = "transactionManager")
  @Cacheable("cancionesCount")
  public long getCantidadCanciones(
      Long idPais, Integer anio, Integer trimestre, Long idAutor, String filtro) {

    Session session = sessionFactory.getCurrentSession();

    StringBuffer buffer = new StringBuffer();
    buffer
        .append("select count(DISTINCT dc.idCancion) FROM DatosCancion dc ")
        .append("WHERE (dc.companyId = :companyId OR dc.companyId is null) ");

    buffer.append(DaoUtils.getWhereClause(trimestre, anio, idPais, filtro, idAutor));

    Query query = session.createQuery(buffer.toString());
    query.setParameter("companyId", Configuracion.SACM_COMPANY_ID);

    DaoUtils.setearParametros(query, idPais, anio, trimestre, filtro, idAutor);

    Long resultado = (Long) query.uniqueResult();

    return resultado != null ? resultado.longValue() : 0;
  }
  @SuppressWarnings("unchecked")
  @Transactional(value = "transactionManager")
  @Cacheable("canciones")
  public List<RankingCancion> getCanciones(
      Long idPais,
      Integer anio,
      Integer trimestre,
      Long idAutor,
      int inicio,
      int cantidadResultados,
      String filtro) {

    Session session = sessionFactory.getCurrentSession();

    StringBuffer buffer = new StringBuffer();
    buffer
        .append("SELECT new " + RankingCancion.class.getName() + "( ")
        .append("dc.idCancion, dc.nombreCancion, dc.idAutor, dc.nombreAutor, ")
        .append("SUM(dc.cantidadUnidades), SUM(dc.montoPercibido)) ")
        .append("FROM DatosCancion dc ")
        .append("WHERE (dc.companyId = :companyId OR dc.companyId is null) ");

    buffer.append(DaoUtils.getWhereClause(trimestre, anio, idPais, filtro, idAutor));

    buffer.append("GROUP BY dc.idCancion, dc.idAutor ").append("ORDER BY dc.nombreCancion asc");

    Query query = session.createQuery(buffer.toString());
    query.setParameter("companyId", Configuracion.SACM_COMPANY_ID);

    DaoUtils.setearParametros(query, idPais, anio, trimestre, filtro, idAutor);

    query.setFirstResult(inicio);
    query.setMaxResults(cantidadResultados);

    return query.list();
  }
  @Override
  @TransactionalRollbackAllExceptions
  public void importEvent(EventSummary eventSummary) throws ZepException {
    if (!ZepConstants.CLOSED_STATUSES.contains(eventSummary.getStatus())) {
      throw new ZepException(
          "Invalid status for event in event archive: " + eventSummary.getStatus());
    }

    final long updateTime = System.currentTimeMillis();
    final EventSummary.Builder summaryBuilder = EventSummary.newBuilder(eventSummary);
    final Event.Builder eventBuilder = summaryBuilder.getOccurrenceBuilder(0);
    summaryBuilder.setUpdateTime(updateTime);
    EventDaoHelper.addMigrateUpdateTimeDetail(eventBuilder, updateTime);

    final EventSummary summary = summaryBuilder.build();
    final Map<String, Object> fields = this.eventDaoHelper.createImportedSummaryFields(summary);
    this.template.update(DaoUtils.createNamedInsert(TABLE_EVENT_ARCHIVE, fields.keySet()), fields);
  }
  private void populateCache() {

    if (!cacheLoaded) {
      gl.writeLock().lock();
      try {
        gl.writeLock().lock();
        try {
          if (hostConfigMappingByHost == null) {
            hostConfigMappingByHost = new WeakHashMap<String, Set<HostConfigMapping>>();

            TypedQuery<HostConfigMappingEntity> query =
                entityManagerProvider
                    .get()
                    .createQuery(
                        "SELECT entity FROM HostConfigMappingEntity entity",
                        HostConfigMappingEntity.class);

            List<HostConfigMappingEntity> hostConfigMappingEntities = daoUtils.selectList(query);

            for (HostConfigMappingEntity hostConfigMappingEntity : hostConfigMappingEntities) {

              Set<HostConfigMapping> setByHost =
                  hostConfigMappingByHost.get((hostConfigMappingEntity.getHostName()));

              if (setByHost == null) {
                setByHost = new HashSet<HostConfigMapping>();
                hostConfigMappingByHost.put(hostConfigMappingEntity.getHostName(), setByHost);
              }

              HostConfigMapping hostConfigMapping = buildHostConfigMapping(hostConfigMappingEntity);
              setByHost.add(hostConfigMapping);
            }
          }
        } finally {
          gl.writeLock().unlock();
        }
      } finally {
        gl.writeLock().unlock();
      }

      cacheLoaded = true;
    }
  }
  @SuppressWarnings("unchecked")
  private List<Fuente> getFuentes(Long idPais, Session session) {

    StringBuffer buffer = new StringBuffer();
    buffer
        .append("SELECT DISTINCT new ")
        .append(Fuente.class.getName())
        .append("(dc.idFuente, dc.nombreFuente) from DatosCancion dc ")
        .append("WHERE dc.idFuente is not null ");

    if (idPais != null) {
      buffer.append("AND dc.idPais = :idPais ");
    }

    buffer.append("ORDER BY dc.idFuente");

    Query query = session.createQuery(buffer.toString());
    DaoUtils.setearParametros(query, idPais, null, null, null);

    return query.list();
  }
Example #19
0
 public BigDecimal getMaxNid(int fydm) {
   String hql = "select max(N_ID) from T_RYSX_ZDXX";
   return DaoUtils.getMaxIdRyjbxx(getSession(), fydm, hql);
 }
 @RequiresSession
 public List<HostConfigMappingEntity> findAll() {
   return daoUtils.selectAll(entityManagerProvider.get(), HostConfigMappingEntity.class);
 }