Esempio n. 1
0
  public void importarClientesPendientes(final Date desde) {
    for (Long sucursal : getSucursales()) {

      JdbcTemplate sucursalTemplate = ReplicaServices.getInstance().getJdbcTemplate(sucursal);
      String sql = "select CLIENTE_ID from sx_clientes where date(creado)>=?";
      Object args[] = {new SqlParameterValue(Types.DATE, desde)};
      final List<Long> ids = sucursalTemplate.queryForList(sql, args, Long.class);
      System.out.println("Clientes: " + ids.size());
      for (Long id : ids) {
        System.out.println("Validando: " + id + " En sucursal: " + sucursal);
        Cliente c = Services.getInstance().getClientesManager().get(id);
        if (c == null) {
          System.out.println("Faltante: " + id + " importandolo...");
          HibernateTemplate target = Services.getInstance().getHibernateTemplate();
          HibernateTemplate source = ReplicaServices.getInstance().getHibernateTemplate(sucursal);
          List<Cliente> clientes =
              source.find(
                  "from Cliente c left join fetch c.credito "
                      + " left join fetch c.direcciones d"
                      + " left join fetch c.telefonos t"
                      + " where c.id=?",
                  id);
          c = clientes.get(0);
          target.replicate(c, ReplicationMode.EXCEPTION);
        }
      }
    }
  }
Esempio n. 2
0
  @SuppressWarnings("unchecked")
  public List<Team> getTeam(int userId, TeamType type) {
    boolean isAdmin = false;
    HibernateTemplate template = getHibernateTemplate();
    Object obj = template.get(Employee.class, userId);
    List<Team> list = new ArrayList<Team>();
    if (null == obj) return list;
    else {
      Employee employee = (Employee) obj;
      isAdmin = employee.getIsAdmin();
      if (isAdmin) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Team.class);

        if (type == TeamType.Product) criteria.add(Restrictions.eq("isProduct", true));
        else if (type == TeamType.Sales) criteria.add(Restrictions.eq("isSales", true));
        else if (type == TeamType.Operator) criteria.add(Restrictions.eq("isOperator", true));

        criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

        list = getHibernateTemplate().findByCriteria(criteria);
      } else {
        Set<Team> team = employee.getTeamMemberships();
        for (Team team2 : team) {
          if (type == TeamType.Operator && team2.getIsOperator()) list.add(team2);
          else if (type == TeamType.Sales && team2.getIsSales()) list.add(team2);
          else if (type == TeamType.Product && team2.getIsProduct()) list.add(team2);
        }
      }

      return list;
    }
  }
  private ContentKey storeSimpleContent(String title) {

    ContentEntity content = factory.createContent("MyCategory", "en", "testuser", "0", new Date());
    ContentVersionEntity version = factory.createContentVersion("0", "testuser");

    ContentTypeConfig contentTypeConfig =
        ContentTypeConfigParser.parse(ContentHandlerName.CUSTOM, createSimpleContentTypeConfig());

    CustomContentData contentData = new CustomContentData(contentTypeConfig);

    TextDataEntryConfig titleConfig =
        new TextDataEntryConfig("myTitle", true, title, "contentdata/mytitle");
    contentData.add(new TextDataEntry(titleConfig, "relatedconfig"));

    version.setContentData(contentData);

    UserEntity runningUser = fixture.findUserByName("testuser");

    CreateContentCommand createContentCommand = new CreateContentCommand();
    createContentCommand.setCreator(runningUser);

    createContentCommand.populateCommandWithContentValues(content);
    createContentCommand.populateCommandWithContentVersionValues(version);

    createContentCommand.setBinaryDatas(new ArrayList<BinaryDataAndBinary>());
    createContentCommand.setUseCommandsBinaryDataToAdd(true);

    ContentKey contentKey = contentService.createContent(createContentCommand);

    hibernateTemplate.flush();
    hibernateTemplate.clear();

    return contentKey;
  }
  /** Load this DAO from the data source */
  public void load() throws DataAccessException {

    HibernateTemplate ht;
    ht = new HibernateTemplate(getSessionFactory());
    teeName = (TeeName) ht.load(TeeName.class, getId());
    ht.initialize(teeName);
  }
  public void saveDocumentMapping(JSONObject jobj) throws ServiceException {
    try {
      Docmap docMap = new Docmap();

      if (jobj.has("docid") && !StringUtil.isNullOrEmpty(jobj.getString("docid"))) {
        Docs doc = (Docs) hibernateTemplate.get(Docs.class, jobj.getString("docid"));
        docMap.setDocid(doc);
        if (jobj.has("companyid") && !StringUtil.isNullOrEmpty(jobj.getString("companyid"))) {
          Company company =
              (Company) hibernateTemplate.get(Company.class, jobj.getString("companyid"));
          doc.setCompany(company);
        }
        if (jobj.has("userid") && !StringUtil.isNullOrEmpty(jobj.getString("userid"))) {
          User user = (User) hibernateTemplate.get(User.class, jobj.getString("userid"));
          doc.setUserid(user);
        }
      }
      if (jobj.has("refid")) {
        docMap.setRecid(jobj.getString("refid"));
      }
      if (jobj.has("map")) {
        docMap.setRelatedto(jobj.getString("map"));
      }
      hibernateTemplate.save(docMap);
    } catch (Exception ex) {
      throw ServiceException.FAILURE("documentDAOImpl.saveDocumentMapping", ex);
    }
  }
  /**
   * Tests <code>{@link CopilotProjectDAOImpl#retrieveAll()}</code> method.
   *
   * @throws CopilotDAOException if any error occurs
   */
  @Test
  public void testRetrieveAll2() throws CopilotDAOException {

    CopilotProfile copilotProfile1 = TestHelper.createCopilotProfile();
    CopilotProject copilotProject1 = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(
        hibernateTemplate, copilotProfile1, copilotProject1);
    hibernateTemplate.save(copilotProject1);

    CopilotProfile copilotProfile2 = TestHelper.createCopilotProfile();
    CopilotProject copilotProject2 = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(
        hibernateTemplate, copilotProfile2, copilotProject2);
    hibernateTemplate.save(copilotProject2);

    List<CopilotProject> result = instance.retrieveAll();

    Assert.assertEquals("Two entities were expected.", 2, result.size());
    assertCopilotProject(copilotProject1, result.get(0));
    assertCopilotProject(copilotProject2, result.get(1));

    hibernateTemplate.delete(copilotProject1);

    result = instance.retrieveAll();

    Assert.assertEquals("One entity was expected.", 1, result.size());
    assertCopilotProject(copilotProject2, result.get(0));

    hibernateTemplate.delete(copilotProject2);

    Assert.assertEquals("No entities were expected.", 0, instance.retrieveAll().size());
  }
  @Transactional(rollbackFor = Throwable.class)
  @Override
  public void saveOrUpdateRecords(ArchivedInferredLocationRecord... records) {
    List<ArchivedInferredLocationRecord> list =
        new ArrayList<ArchivedInferredLocationRecord>(records.length);
    for (ArchivedInferredLocationRecord record : records) list.add(record);
    _template.saveOrUpdateAll(list);

    // LastKnownRecord
    LinkedHashMap<Integer, CcAndInferredLocationRecord> lastKnownRecords =
        new LinkedHashMap<Integer, CcAndInferredLocationRecord>(records.length);
    for (ArchivedInferredLocationRecord record : records) {
      CcLocationReportRecord cc = findRealtimeRecord(record);
      if (cc != null) {
        CcAndInferredLocationRecord lastKnown = new CcAndInferredLocationRecord(record, cc);
        if (validationService.validateLastKnownRecord(lastKnown)) {
          lastKnownRecords.put(lastKnown.getVehicleId(), lastKnown);
        } else {
          discardRecord(lastKnown);
        }
      }
    }
    _template.saveOrUpdateAll(lastKnownRecords.values());
    _template.flush();
    _template.clear();
  }
  /**
   * Tests <code>{@link CopilotProjectDAOImpl#getCopilotProjects(long)}</code> method.
   *
   * @throws CopilotDAOException if any error occurs
   */
  @Test
  public void testGetCopilotProjects1() throws CopilotDAOException {

    CopilotProfile copilotProfile1 = TestHelper.createCopilotProfile();
    CopilotProject copilotProject1 = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(
        hibernateTemplate, copilotProfile1, copilotProject1);
    hibernateTemplate.save(copilotProject1);

    CopilotProfile copilotProfile2 = TestHelper.createCopilotProfile();
    CopilotProject copilotProject2 = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(
        hibernateTemplate, copilotProfile2, copilotProject2);
    hibernateTemplate.save(copilotProject2);

    List<CopilotProject> result =
        instance.getCopilotProjects(copilotProject1.getCopilotProfileId());

    Assert.assertEquals("Only one result was expected.", 1, result.size());
    assertCopilotProject(copilotProject1, result.get(0));

    result = instance.getCopilotProjects(copilotProject2.getCopilotProfileId());

    Assert.assertEquals("Only one result was expected.", 1, result.size());
    assertCopilotProject(copilotProject2, result.get(0));
  }
  /**
   * Tests <code>{@link CopilotProjectDAOImpl#delete(long)}</code> method.
   *
   * @throws CopilotDAOException if any error occurs
   */
  @Test
  @SuppressWarnings("unchecked")
  public void testDelete2() throws CopilotDAOException {

    CopilotProfile copilotProfile = TestHelper.createCopilotProfile();
    CopilotProject copilotProject = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(hibernateTemplate, copilotProfile, copilotProject);

    CopilotProjectInfoType copilotProjectInfoType = TestHelper.createCopilotProjectInfoType();
    hibernateTemplate.save(copilotProjectInfoType);

    CopilotProjectInfo copilotProjectInfo = TestHelper.createCopilotProjectInfo();
    copilotProjectInfo.setCopilotProjectId(copilotProject.getId());
    copilotProjectInfo.setInfoType(copilotProjectInfoType);
    copilotProject.getProjectInfos().add(copilotProjectInfo);
    hibernateTemplate.save(copilotProject);

    instance.delete(copilotProject.getId());

    Assert.assertEquals(
        "None entity in database should exist.",
        0,
        hibernateTemplate.find("from CopilotProject").size());
    Assert.assertEquals(
        "None entity in database should exist.",
        0,
        hibernateTemplate.find("from CopilotProjectInfo").size());
  }
  /**
   * Tests <code>{@link CopilotProjectDAOImpl#retrieve(long)}</code> method.
   *
   * @throws CopilotDAOException if any error occurs
   */
  @Test
  public void testRetrieve1() throws CopilotDAOException {

    CopilotProfile copilotProfile1 = TestHelper.createCopilotProfile();
    CopilotProject copilotProject1 = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(
        hibernateTemplate, copilotProfile1, copilotProject1);
    hibernateTemplate.save(copilotProject1);

    CopilotProfile copilotProfile2 = TestHelper.createCopilotProfile();
    CopilotProject copilotProject2 = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(
        hibernateTemplate, copilotProfile2, copilotProject2);
    hibernateTemplate.save(copilotProject2);

    CopilotProject result = instance.retrieve(copilotProject1.getId());

    assertCopilotProject(copilotProject1, result);

    result = instance.retrieve(copilotProject2.getId());

    assertCopilotProject(copilotProject2, result);
  }
  /**
   * Tests <code>{@link
   * CopilotProjectDAOImpl#update(com.topcoder.direct.services.copilot.model.IdentifiableEntity)}
   * </code> method.
   *
   * @throws CopilotDAOException if any error occurs
   */
  @Test
  @SuppressWarnings("unchecked")
  public void testUpdate() throws CopilotDAOException {

    CopilotProfile copilotProfile = TestHelper.createCopilotProfile();
    CopilotProject copilotProject = TestHelper.createCopilotProject();

    TestHelper.persistCopilotProjectDependencies(hibernateTemplate, copilotProfile, copilotProject);
    hibernateTemplate.save(copilotProject);

    copilotProject.setCompletionDate(new Date());
    copilotProject.setCustomerFeedback("test customer feedback");
    copilotProject.setCustomerRating(0.9F);
    copilotProject.setPmFeedback("test pm feedback");
    copilotProject.setPmRating(0.9F);

    CopilotProjectInfoType copilotProjectInfoType = TestHelper.createCopilotProjectInfoType();
    hibernateTemplate.save(copilotProjectInfoType);

    CopilotProjectInfo copilotProjectInfo = TestHelper.createCopilotProjectInfo();
    copilotProjectInfo.setInfoType(copilotProjectInfoType);
    copilotProject.getProjectInfos().add(copilotProjectInfo);

    instance.update(copilotProject);

    List<CopilotProject> result =
        (List<CopilotProject>)
            hibernateTemplate.find("from CopilotProject where id = ?", copilotProject.getId());

    assertCopilotProject(copilotProject, result.get(0));
  }
  @Override
  @Transactional(readOnly = true)
  public List<Ticket> searchTicketByKeyword(String keyword) {

    HibernateTemplate ht = getHibernateTemplate();

    List<Ticket> resultList = new ArrayList<Ticket>();

    List<Ticket> titleList =
        ht.find("from Ticket t where t.title like ? order by t.id desc", wildCardKeyword(keyword));
    List<Ticket> creatorList =
        ht.find(
            "from Ticket t where t.creator.username like ? order by t.id desc",
            wildCardKeyword(keyword)); // searchTicket By Creator;
    List<Ticket> assigneeList =
        ht.find(
            "from Ticket t where t.assignee.username like ? order by t.id desc",
            wildCardKeyword(keyword));
    List<Ticket> custList =
        ht.find(
            "from Ticket t where t.customer.username like ? order by t.id desc",
            wildCardKeyword(keyword)); // searchTicketByCustomer(keyword);
    // List<Ticket> noteList   = ht.find("from Ticket t where t.notes.note like ?",
    // wildCardKeyword(keyword));

    resultList.addAll(titleList);
    resultList.addAll(creatorList);
    resultList.addAll(assigneeList);
    resultList.addAll(custList);
    // resultList.addAll(noteList);

    return resultList;
  }
 @Override
 @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
 public boolean delete(Guardian guardian) {
   hibernateTemplate.delete(guardian);
   hibernateTemplate.flush();
   return true;
 }
Esempio n. 14
0
 /**
  * Replica los clientes faltantes de enviar a las sucursales
  *
  * <p>Util para tareas especiales
  */
 public void replicarFaltantes() {
   final JdbcTemplate template = Services.getInstance().getJdbcTemplate();
   String sql =
       "select distinct clave from sx_clientes_log where tx_replicado is null order by modificado desc";
   List<Map<String, Object>> rows = template.queryForList(sql);
   if (rows.size() > 0) {
     logger.info("Clientes pendiente de replicado: " + rows.size());
   }
   for (Map<String, Object> row : rows) {
     String clave = (String) row.get("CLAVE");
     Cliente c = Services.getInstance().getClientesManager().buscarPorClave(clave);
     if (c != null) {
       logger.info("Replicando :" + c.getClave());
       for (Long sucursalId : getSucursales()) {
         HibernateTemplate target = ReplicaServices.getInstance().getHibernateTemplate(sucursalId);
         try {
           target.replicate(c, ReplicationMode.OVERWRITE);
           logger.info("Cliente replicado: " + c.getClave());
         } catch (Exception e) {
           logger.error(
               "Error replicando cliente: "
                   + c.getClave()
                   + " A sucursal: "
                   + sucursalId
                   + "  "
                   + ExceptionUtils.getRootCauseMessage(e));
         }
       }
     }
   }
 }
Esempio n. 15
0
  public void importarPendientes(Long sucursalId) {
    String sql = "select * from sx_clientes_log where tx_importado is null";
    JdbcTemplate template = ReplicaServices.getInstance().getJdbcTemplate(sucursalId);
    List<Map<String, Object>> rows = template.queryForList(sql);
    for (Map<String, Object> row : rows) {
      System.out.println("Importando: " + row);

      try {
        Number cliente_id = (Number) row.get("CLIENTE_ID");
        HibernateTemplate source = ReplicaServices.getInstance().getHibernateTemplate(sucursalId);
        List<Cliente> clientes =
            source.find(
                "from Cliente c "
                    + " left join fetch c.direcciones d"
                    + " left join fetch c.telefonos t"
                    + " where c.id=?",
                cliente_id.longValue());
        Cliente c = clientes.get(0);
        Services.getInstance().getHibernateTemplate().replicate(c, ReplicationMode.IGNORE);
      } catch (Exception e) {
        logger.error("Error importando cliente: " + row, e);
      }
      try {
        Number id = (Number) row.get("ID");
        String update = "UPDATE SX_CLIENTES_LOG SET TX_IMPORTADO=NOW() WHERE ID=?";
        template.update(update, new Object[] {id.longValue()});
      } catch (Exception e) {
        logger.error("Error actualizando importado: " + row);
      }
    }
  }
Esempio n. 16
0
 @Test
 @Transactional(value = "hibernateTransactionManager", readOnly = true)
 public void shouldLoadAuthoritiesWhichUserHave() {
   User user = hibernateTemplate.load(User.class, 1);
   Authority authority = hibernateTemplate.load(Authority.class, 1);
   assertFalse(user.getAuthorities().isEmpty());
   assertTrue(user.getAuthorities().contains(authority));
 }
Esempio n. 17
0
 /**
  * creates user in database
  *
  * @param user user reference
  */
 @Override
 public User create(User user) {
   Page page = new Page();
   hibernateTemplate.save(page);
   user.setPageId(page.getPageId());
   hibernateTemplate.save(user);
   return user;
 }
Esempio n. 18
0
 @Bean
 public HibernateTemplate hibernateTemplate() throws Exception {
   // for Hibernate 4, Spring team thought it's transaction is very well so encourage to use
   // Session and don't need HibernateTemplate
   HibernateTemplate hibernateTemplate = new HibernateTemplate();
   hibernateTemplate.setSessionFactory(sessionFactory());
   return hibernateTemplate;
 }
 @SuppressWarnings("unchecked")
 public Integer getExecutionTestId(String executionId) {
   String hql = "from " + TestExecution.class.getName() + " t where t.id = :id";
   hibernateTemplate.setMaxResults(1);
   List<TestExecution> l = hibernateTemplate.findByNamedParam(hql, "id", executionId);
   hibernateTemplate.setMaxResults(0);
   return l.size() > 0 ? ((TestExecution) l.get(0)).getTestId() : null;
 }
Esempio n. 20
0
  public List<Address2> retrieveFromId(String userId) {

    List<Address> listUser =
        (List<Address>)
            hibernateTemplate.findByNamedQueryAndNamedParam(
                "Address.findByUserId", "userId", userId);

    List<Address2> listUser2 = new ArrayList<Address2>();

    for (int i = 0; i < listUser.size(); i++) {
      Address2 add = new Address2();
      add.setAddressId(listUser.get(i).getAddressId());
      add.setAddressLine1(listUser.get(i).getAddressLine1());
      add.setAddressLine2(listUser.get(i).getAddressLine2());
      add.setCityId(listUser.get(i).getCityId());
      add.setCountryId(listUser.get(i).getCountryId());
      add.setCreatedDate(listUser.get(i).getCreatedDate());
      add.setIsActive(listUser.get(i).getIsActive());
      add.setName(listUser.get(i).getName());
      add.setPhone(listUser.get(i).getPhone());
      add.setPostalCode(listUser.get(i).getPostalCode());
      add.setUpdatedDate(listUser.get(i).getUpdatedDate());
      add.setUserId(listUser.get(i).getUserId());
      add.setStateId(listUser.get(i).getStateId());
      listUser2.add(add);
    }

    /*
     *Method for fetching CityName using cityId
     */
    for (int i = 0; i < listUser.size(); i++) {
      List<?> cityList =
          (List<?>)
              hibernateTemplate.findByNamedQueryAndNamedParam(
                  "City.findByCityId", "cityId", listUser.get(i).getCityId());
      if (cityList.size() > 0) {
        City city = (City) cityList.get(0);
        String cityName = city.getCityName();
        (listUser2.get(i)).setCityName(cityName);
      }
    }
    /*
     * Method for fetching StateName using stateId
     */
    for (int i = 0; i < listUser.size(); i++) {
      List<?> stateList =
          (List<?>)
              hibernateTemplate.findByNamedQueryAndNamedParam(
                  "State.findByStateId", "stateId", listUser.get(i).getStateId());
      if (stateList.size() > 0) {
        State state = (State) stateList.get(0);
        String stateName = state.getStateName();
        (listUser2.get(i)).setStateName(stateName);
      }
    }

    return listUser2;
  }
 public List<ExaminationDetail> loadByExamination(final Examination examination) {
   HibernateTemplate hibernateTemplate = getHibernateTemplate();
   List<ExaminationDetail> result =
       hibernateTemplate.findByNamedParam(
           "from " + entityBeanType.getSimpleName() + " exd where exd.examination=:examination",
           "examination",
           examination);
   return result;
 }
  public final void createSample(final SamplePE sample) throws DataAccessException {
    assert sample != null : "Unspecified sample";

    final HibernateTemplate hibernateTemplate = getHibernateTemplate();

    internalCreateSample(
        sample, hibernateTemplate, new ClassValidator<SamplePE>(SamplePE.class), true);
    hibernateTemplate.flush();
  }
 @Override
 @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
 public void handleException(String content, Throwable error, Date timeReceived) {
   InvalidLocationRecord ilr = new InvalidLocationRecord(content, error, timeReceived);
   _template.saveOrUpdate(ilr);
   // clear from level one cache
   _template.flush();
   _template.evict(ilr);
 }
Esempio n. 24
0
 public boolean delUser(String userId) {
   User user = hibernateTemplate.get(User.class, userId);
   try {
     hibernateTemplate.delete(user);
   } catch (Exception e) {
     result = false;
   }
   return result;
 }
Esempio n. 25
0
 /* (non-Javadoc)
  * @see cn.believeus.dao.IBaseDao#delete(java.lang.Class, java.lang.String, java.lang.Object)
  */
 @Override
 public void delete(Class<?> clazz, String property, final Object value) {
   HibernateTemplate ht = getHibernateTemplate();
   List<?> objectList = this.findObjectList(clazz, property, value);
   for (Object entity : objectList) {
     ht.delete(entity);
     ht.flush();
   }
 }
Esempio n. 26
0
  // 根据toid查找消息
  public List<Message> findlaterMessage(int toid) {

    List<Message> list = new ArrayList<Message>();

    //		List<Message> listspo=hibernateTemplate.find("from Message m where m.toid=? and type=4 group
    // by m.invid order by m.time desc",toid);
    //		List<Message> listuser=hibernateTemplate.find("from Message m where m.toid=? and type=0
    // group by m.fromid order by m.time desc",toid);
    //		List<Message> listinv=hibernateTemplate.find("from Message m where m.toid=? and type>4 group
    // by m.invid order by m.time desc",toid);
    Session session = hibernateTemplate.getSessionFactory().openSession();

    Query query =
        session.createQuery(
            "from Message m where m.toid=? and type=4 group by m.invid order by m.time desc");
    query.setInteger(0, toid);
    //		session.close();
    @SuppressWarnings("unchecked")
    List<Message> listspo = query.list();
    Query query2 =
        session.createQuery(
            "from Message m where m.toid=? and type=0 group by m.fromid order by m.time desc");
    query2.setInteger(0, toid);
    @SuppressWarnings("unchecked")
    List<Message> listuser = query2.list();
    Query query3 =
        session.createQuery(
            "from Message m where m.toid=? and type>4 group by m.invid order by m.time desc");
    query3.setInteger(0, toid);
    @SuppressWarnings("unchecked")
    List<Message> listinv = query3.list();
    session.close();

    hibernateTemplate.getSessionFactory().close();

    //		List<Message> listspo= hibernateTemplate
    //				.find("  from Message m where m.toid=? and type=4 group by m.invid order by m.time desc",
    //						toid);
    //		List<Message> listuser = hibernateTemplate
    //				.find("from Message m where m.toid=? and type<4 group by m.fromid order by m.time desc",
    //						toid);
    //
    //		List<Message> listinv = hibernateTemplate
    //				.find("from Message m where m.toid=? and type>4 group by m.invid order by m.time desc",
    //						toid);
    if (listinv.size() != 0) {
      list.addAll(listinv);
    }
    if (listspo.size() != 0) {
      list.addAll(listspo);
    }
    if (listuser.size() != 0) {
      list.addAll(listuser);
    }

    return list;
  }
Esempio n. 27
0
 // 根据toid查找消息
 public List<Message> findMessage(int toid) {
   Session session = hibernateTemplate.getSessionFactory().openSession();
   Query query = session.createQuery("from Message m where m.toid=? ");
   query.setInteger(0, toid);
   @SuppressWarnings("unchecked")
   List<Message> list = query.list();
   session.close();
   hibernateTemplate.getSessionFactory().close();
   return list;
 }
  @Before
  public void setUp() {
    t = new HibernateTemplate(sess);

    brh = new UserProfile("brh", 12.);
    admin = new UserProfile("admin", 10., Boolean.TRUE);

    t.save(brh);
    t.save(admin);
  }
Esempio n. 29
0
 @Override
 @Transactional(readOnly = false, rollbackFor = Exception.class)
 public void delete(String levelForUserId) throws UserExistInLevelException {
   // 如果有用户处于当前等级,则不能删除
   String hql = "select count(user) from User user where user.level.id = ?";
   long n = (Long) ht.find(hql, levelForUserId).get(0);
   if (n > 0) {
     throw new UserExistInLevelException();
   }
   ht.bulkUpdate("delete from LevelForUser lfu where lfu.id = ?", levelForUserId);
 }
Esempio n. 30
0
  public void replicarPendientes() {
    for (Long sucursalId : getSucursales()) {
      importarPendientes(sucursalId);
    }
    final JdbcTemplate template = Services.getInstance().getJdbcTemplate();
    String sql =
        "select * from sx_clientes_log where tx_replicado is null and date(modificado)>=? order by modificado desc";
    Object[] values = new Object[] {new SqlParameterValue(Types.DATE, new Date())};
    List<Map<String, Object>> rows = template.queryForList(sql, values);
    if (rows.size() > 0) {
      logger.info("Client es pendiente de replicado: " + rows.size());
    }
    for (Map<String, Object> row : rows) {
      String clave = (String) row.get("CLAVE");
      Number id = (Number) row.get("ID");
      Cliente c = Services.getInstance().getClientesManager().buscarPorClave(clave);
      boolean aplicado = true;
      if (c != null) {
        logger.info("Replicando :" + c.getClave() + " Log ID:" + id);
        for (Long sucursalId : getSucursales()) {

          HibernateTemplate target = ReplicaServices.getInstance().getHibernateTemplate(sucursalId);
          try {

            target.replicate(c, ReplicationMode.OVERWRITE);

          } catch (Exception e) {
            aplicado = false;
            logger.error(
                "Error replicando cliente: "
                    + c.getClave()
                    + " A sucursal: "
                    + sucursalId
                    + "  "
                    + ExceptionUtils.getRootCauseMessage(e));
          }
        }
        if (aplicado) {
          try {
            Object[] params = {
              new SqlParameterValue(Types.TIMESTAMP, new Date()),
              new SqlParameterValue(Types.NUMERIC, id.longValue())
            };
            template.update("update sx_clientes_log set tx_replicado=? where id=?", params);
            // logger.info("Log replicado: "+id+ "Cliente : "+c.getClave());
          } catch (Exception e) {
            logger.error(e);
          }
          logger.info(
              "Actualizacion de cliente exitosa Log ID: " + id + " Cliente(Clave):" + c.getClave());
        }
      }
    }
  }