@Test
  @Ignore(
      "By default, the search request will fail if there is no mapping associated with a field. The ignore_unmapped option allows to ignore fields that have no mapping and not sort by them")
  public void shouldReturnSortedPageableResultsGivenStringQuery() {
    // todo
    // given
    String documentId = randomNumeric(5);
    SampleEntity sampleEntity = new SampleEntity();
    sampleEntity.setId(documentId);
    sampleEntity.setMessage("some message");
    sampleEntity.setVersion(System.currentTimeMillis());

    IndexQuery indexQuery = new IndexQuery();
    indexQuery.setId(documentId);
    indexQuery.setObject(sampleEntity);

    elasticsearchTemplate.index(indexQuery);
    elasticsearchTemplate.refresh(SampleEntity.class, true);

    StringQuery stringQuery =
        new StringQuery(
            matchAllQuery().toString(),
            new PageRequest(0, 10),
            new Sort(new Sort.Order(Sort.Direction.ASC, "messsage")));
    // when
    Page<SampleEntity> sampleEntities =
        elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class);
    // then
    assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L)));
  }
 @Override
 public Iterable<DocumentObject> findAll(Integer pageNumber, Integer pageSize) {
   Page<DocumentObject> page =
       documentObjectRepository.findAll(new PageRequest(pageNumber, pageSize));
   Iterable<DocumentObject> pagedDocumentObject = page.getContent();
   return pagedDocumentObject;
 }
 private void addLastLink(Page<T> page, String pageParam, String sizeParam) {
   if (page.isLast()) {
     Link link =
         buildPageLink(pageParam, page.getTotalPages(), sizeParam, page.getSize(), Link.REL_LAST);
     add(link);
   }
 }
 private void addNextLink(Page<T> page, String pageParam, String sizeParam) {
   if (page.hasNext()) {
     Link link =
         buildPageLink(pageParam, page.getNumber() + 1, sizeParam, page.getSize(), Link.REL_NEXT);
     add(link);
   }
 }
  /** GET /evolutionPrescriptions -> get all the evolutionPrescriptions. */
  @RequestMapping(
      value = "/episodes/{episode_id}/evolutionPrescriptions",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @Timed
  public ResponseEntity<List<EvolutionPrescription>> getAllByEpisode(
      @PathVariable(value = "episode_id") Long episodeId,
      @RequestParam(value = "page", required = false) Integer offset,
      @RequestParam(value = "per_page", required = false) Integer limit)
      throws URISyntaxException {
    Page<EvolutionPrescription> page;

    if (episodeId != null && episodeId > 0) {
      page =
          evolutionPrescriptionRepository.findByEpisode(
              episodeId, PaginationUtil.generatePageRequest(offset, limit));
    } else {
      page =
          evolutionPrescriptionRepository.findAll(
              PaginationUtil.generatePageRequest(offset, limit));
    }
    HttpHeaders headers =
        PaginationUtil.generatePaginationHttpHeaders(
            page, "/api/episodes/" + episodeId + "/evolutionPrescriptions", offset, limit);
    return new ResponseEntity<List<EvolutionPrescription>>(
        page.getContent(), headers, HttpStatus.OK);
  }
 @Override
 public List<OaCertificateType> findAll(Page page) {
   org.springframework.data.domain.Page<OaCertificateType> springDataPage =
       certificateTypeDAO.findAll(PageUtils.createPageable(page));
   page.setTotalCount(springDataPage.getTotalElements());
   return springDataPage.getContent();
 }
Esempio n. 7
0
  // 点击关闭按钮(明细新增等)
  @RequestMapping("DtlInitReflash")
  public String DtlInitReflash(
      Model model, FTZ210205Form form, @PageableDefaults Pageable pageable) {
    FtzInMsgCtl query_FtzInMsgCtl = new FtzInMsgCtl();
    query_FtzInMsgCtl.setMsgId(form.getSelected_msgId());
    FtzInMsgCtl ftzInMsgCtl = ftz210205Serv.queryFtzInMsgCtl(query_FtzInMsgCtl);
    if (null == ftzInMsgCtl) {
      model.addAttribute(ResultMessages.error().add("w.sm.0001"));
      return "ftzmis/FTZ210205_Input_Dtl";
    }
    ftzInMsgCtl.setSubmitDate(DateUtil.getFormatDateAddSprit(ftzInMsgCtl.getSubmitDate()));
    ftzInMsgCtl.setBalanceCode(ftzInMsgCtl.getBalanceCode().trim());
    form.setFtzInMsgCtl(ftzInMsgCtl);

    FtzInTxnDtl query_FtzInTxnDtl = new FtzInTxnDtl();
    query_FtzInTxnDtl.setMsgId(form.getSelected_msgId());
    // 查询明细数据列表
    Page<FtzInTxnDtl> page = ftz210205Serv.queryFtzInTxnDtlPage(pageable, query_FtzInTxnDtl);
    if (page.getContent().size() > 0) {
      List<FtzInTxnDtl> ftzInTxnDtls = page.getContent();
      for (FtzInTxnDtl ftzInTxnDtl : ftzInTxnDtls) {
        ftzInTxnDtl.setTranDate(DateUtil.getFormatDateAddSprit(ftzInTxnDtl.getTranDate()));
      }
      model.addAttribute("page", page);
    }

    // 清空页面列表选择Key
    form.setSelected_msgId("");
    form.setSelected_seqNo(null);
    return "ftzmis/FTZ210205_Input_Dtl";
  }
 @Test
 public void testPaginationNoElementsFound() {
   Pageable pageable = new PageRequest(0, 2);
   Page<ProductBean> page = repo.findByNameStartingWith("hpotsirhc", pageable);
   Assert.assertEquals(0, page.getNumberOfElements());
   Assert.assertTrue(page.getContent().isEmpty());
 }
  @Test
  public void getFavoritesByUserId() {

    mockUnauthorizedServer
        .expect(requestTo("https://api.soundcloud.com/users/3510549?client_id=someApiKey"))
        .andExpect(method(GET))
        .andRespond(withResponse(jsonResource("testdata/userprofile"), responseHeaders));

    mockUnauthorizedServer
        .expect(
            requestTo("https://api.soundcloud.com/users/3510549/favorites?client_id=someApiKey"))
        .andExpect(method(GET))
        .andRespond(withResponse(jsonResource("testdata/favorites"), responseHeaders));

    Page<Track> tracksPage =
        unauthorizedSoundCloud.usersOperations().userOperations(3510549).getFavorites();
    assertEquals(0, tracksPage.getNumber());
    assertEquals(56, tracksPage.getTotalElements());
    List<Track> tracks = tracksPage.getContent();
    assertNotNull(tracks);
    assertEquals(50, tracks.size());
    Track firstTrack = tracks.get(0);
    assertEquals("Sneaky Sound System - Big (Oliver Remix)", firstTrack.getTitle());
    assertEquals(
        "http://soundcloud.com/weareoliver/sneaky-sound-system-big-oliver",
        firstTrack.getPermalinkUrl());
    assertEquals("22905377", firstTrack.getId());
  }
  @Test
  public void getTracks() {

    mockUnauthorizedServer
        .expect(
            requestTo(
                "https://api.soundcloud.com/resolve?url=http://soundcloud.com/mattslip&client_id=someApiKey"))
        .andExpect(method(GET))
        .andRespond(withResponse(jsonResource("testdata/resolveuser"), responseHeaders));

    mockUnauthorizedServer
        .expect(requestTo("https://api.soundcloud.com/users/3510549?client_id=someApiKey"))
        .andExpect(method(GET))
        .andRespond(withResponse(jsonResource("testdata/userprofile"), responseHeaders));

    mockUnauthorizedServer
        .expect(requestTo("https://api.soundcloud.com/users/3510549/tracks?client_id=someApiKey"))
        .andExpect(method(GET))
        .andRespond(withResponse(jsonResource("testdata/tracks"), responseHeaders));

    Page<Track> tracksPage =
        unauthorizedSoundCloud.usersOperations().userOperations("mattslip").getTracks();
    List<Track> tracks = tracksPage.getContent();
    assertEquals(0, tracksPage.getNumber());
    assertEquals(50, tracksPage.getTotalElements());

    assertNotNull(tracks);
    assertEquals(50, tracks.size());
    Track firstTrack = tracks.get(0);
    assertEquals("Kid Sister vs Daft Punk (Monsieur Adi Mashup)", firstTrack.getTitle());
    assertEquals(
        "http://soundcloud.com/monsieuradi/kid-sister-vs-daft-punk", firstTrack.getPermalinkUrl());
    assertEquals("39679670", firstTrack.getId());
  }
 @Test
 public void getLeaders_setFilteredAttributes() {
   when(userRepository.findAll(userPageable)).thenReturn(userResultsPage);
   Page<UserDTO> page = communityServiceImpl.getLeaders(userPageable);
   assertDTOWithHiddenValues(page.getContent().get(0), userA);
   assertDTOWithHiddenValues(page.getContent().get(1), userB);
 }
  @ApiOperation(value = "带条件及翻页查询")
  @RequestMapping(value = "page", method = RequestMethod.GET)
  @ResponseBody
  public AjaxPage data(@ModelAttribute @Valid PageParam param) {
    List<SpecificationCondition> conditions = new ArrayList<SpecificationCondition>();
    if (StringUtils.isNotBlank(param.channelName))
      conditions.add(SpecificationCondition.eq("id.channelId", param.channelName.split("-")[0]));
    if (StringUtils.isNotBlank(param.categoryName))
      conditions.add(SpecificationCondition.eq("id.text", param.categoryName.split("-")[0]));
    if (StringUtils.isNotBlank(param.textType))
      conditions.add(SpecificationCondition.eq("textType", param.textType));
    if (StringUtils.isNotBlank(param.text))
      conditions.add(
          SpecificationCondition.equalOrLikeIgnoreCase("id.text", "%" + param.text.trim() + "%"));
    if (StringUtils.isNotBlank(param.textState))
      conditions.add(SpecificationCondition.eq("textState", param.textState));

    List<String> sortNames = new ArrayList<String>();
    if ("id.spId".equals(param.getSortName()) || "id.spServiceCode".equals(param.getSortName())) {
      sortNames.add("id.spId");
      sortNames.add("id.spServiceCode");
    } else sortNames.add(param.getSortName());

    SpecificationHelper<ChannelTextFilter> sh =
        new SpecificationHelper<ChannelTextFilter>(conditions, param.getSortOrder(), sortNames);
    Page<ChannelTextFilter> p = ctfService.page(new PageRequest(param), sh.createSpecification());
    List<ChannelTextFilter> list = p.getContent();
    Integer category = FiltrationType.CATEGORY.getValue().intValue();
    for (ChannelTextFilter ctf : list) {
      ctf.getId().setChannelId(channelService.findOneMatch(ctf.getId().getChannelId()));
      if (category.equals(ctf.getTextType()))
        ctf.getId().setText(tftypeService.findOneMatch(ctf.getId().getText()));
    }
    return AjaxPageUtil.toAjaxPage(p.getTotalElements(), list);
  }
  /**
   * 生成应用明细告警展示信息
   *
   * @param applicationId 所属应用ID
   * @return 告警展示信息
   */
  public ApplicationDetailAlarmViewModel generateAlarmViewModel(String applicationId) {
    Date startDate = DateUtil.getTodayBeginDate();
    Date endDate = new Date();

    Application application = applicationRepository.findApplicationbyId(applicationId);
    int interval = application.getInterval().intValue();
    ApplicationDetailAlarmViewModel applicationDetailAlarmViewModel =
        new ApplicationDetailAlarmViewModel();
    // 获得健康度
    SeverityLevel severityLevel = healthStaService.healthStaForCurrent(applicationId, interval);

    applicationDetailAlarmViewModel.setSeverityLevel(severityLevel);
    int criticalCount = alarmRepository.countCriticalByMonitorId(applicationId, startDate, endDate);

    Pageable pageable = new PageRequest(0, 10, Sort.Direction.DESC, "create_time");
    Page<Alarm> alarmPage =
        alarmRepository.selectCriticalAlarmsByMonitorId(
            pageable, applicationId, startDate, endDate);
    Iterator<Alarm> alarmIterator = alarmPage.iterator();
    while (alarmIterator.hasNext()) {
      applicationDetailAlarmViewModel.addAlarmInfo(alarmIterator.next().getMessage());
    }

    applicationDetailAlarmViewModel.setCriticalCount(criticalCount);
    return applicationDetailAlarmViewModel;
  }
Esempio n. 14
0
  public PagedList<LiveDto> findLivesToShow(Date date, ProjectProgress status, int page, int size) {
    PageRequest pageable = new PageRequest(page - 1, size);
    Specification<Live> spec =
        new Specification<Live>() {
          @Override
          public Predicate toPredicate(
              Root<Live> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            Path<Boolean> shouldShow = root.get("shouldShow");
            predicates.add(cb.equal(shouldShow, true)); // 限制值返回shouldShow的lives

            if (date == null && status == null)
              return cb.and(predicates.toArray(new Predicate[predicates.size()]));

            // 首先匹配日期,返回最新直播
            if (date != null) {
              Path<Date> startDate = root.get("startDate");
              predicates.add(cb.greaterThan(startDate, date));
              return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }

            // 匹配直播状态
            Path<ProjectProgress> statusPath = root.get("status");
            predicates.add(cb.equal(statusPath, status));
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
          }
        };
    Page<Live> list = getRepository().findAll(spec, pageable);
    Page<LiveDto> result = list.map(adapter);
    return new PagedList<>(result);
  }
Esempio n. 15
0
  /**
   * GET /clinicHistorys -> get all the clinicHistorys.
   *
   * @throws URISyntaxException
   */
  @RequestMapping(
      value = "/clinicHistorys",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @Timed
  public ResponseEntity<List<ClinicHistory>> getAllByFilter(
      @RequestParam(value = "page", required = false) Integer offset,
      @RequestParam(value = "per_page", required = false) Integer limit,
      @RequestParam(value = "firstName", required = false) String firstName,
      @RequestParam(value = "secondName", required = false) String secondName,
      @RequestParam(value = "paternalSurname", required = false) String paternalSurname,
      @RequestParam(value = "maternalSurname", required = false) String maternalSurname,
      @RequestParam(value = "cedula", required = false) String cedula)
      throws URISyntaxException {
    log.debug("REST request to get all ClinicHistorys");
    firstName = firstName == null ? "%" : "%" + firstName + "%";
    secondName = secondName == null ? "%" : "%" + secondName + "%";
    paternalSurname = paternalSurname == null ? "%" : "%" + paternalSurname + "%";
    maternalSurname = maternalSurname == null ? "%" : "%" + maternalSurname + "%";
    cedula = cedula == null ? "%" : cedula + "%";

    Page<ClinicHistory> page =
        clinicHistoryRepository.findByFilter(
            firstName,
            secondName,
            paternalSurname,
            maternalSurname,
            cedula,
            PaginationUtil.generatePageRequest(offset, limit));
    HttpHeaders headers =
        PaginationUtil.generatePaginationHttpHeaders(page, "/api/clinicHistorys", offset, limit);
    return new ResponseEntity<List<ClinicHistory>>(page.getContent(), headers, HttpStatus.OK);
  }
Esempio n. 16
0
  public static HttpHeaders generatePaginationHttpHeaders(
      Page page, String baseUrl, Integer offset, Integer limit) throws URISyntaxException {

    if (offset == null || offset < MIN_OFFSET) {
      offset = DEFAULT_OFFSET;
    }
    if (limit == null || limit > MAX_LIMIT) {
      limit = DEFAULT_LIMIT;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-Total-Count", "" + page.getTotalElements());
    String link = "";
    if (offset < page.getTotalPages()) {
      link =
          "<"
              + (new URI(baseUrl + "?page=" + (offset + 1) + "&per_page=" + limit)).toString()
              + ">; rel=\"next\",";
    }
    if (offset > 1) {
      link +=
          "<"
              + (new URI(baseUrl + "?page=" + (offset - 1) + "&per_page=" + limit)).toString()
              + ">; rel=\"prev\",";
    }
    link +=
        "<"
            + (new URI(baseUrl + "?page=" + page.getTotalPages() + "&per_page=" + limit)).toString()
            + ">; rel=\"last\","
            + "<"
            + (new URI(baseUrl + "?page=" + 1 + "&per_page=" + limit)).toString()
            + ">; rel=\"first\"";
    headers.add(HttpHeaders.LINK, link);
    return headers;
  }
  @ApiOperation(value = "带条件及翻页查询")
  @RequestMapping(value = "page", method = RequestMethod.POST)
  @ResponseBody
  public AjaxPage page(@ModelAttribute @Valid PageParam param) {

    List<SpecificationCondition> conditions = new ArrayList<SpecificationCondition>();
    conditions.add(
        SpecificationCondition.equalOrLikeIgnoreCase(
            "textFilterPattern", param.getTextFilterPattern()));
    SpecificationHelper<TextFilter> sh = new SpecificationHelper<TextFilter>(conditions, param);
    Page<TextFilter> p = textFilterService.page(new PageRequest(param), sh.createSpecification());
    List<esms.etonenet.boss1069.web.decorate.TextFilter> list = new ArrayList<>();
    for (TextFilter textFilter : p.getContent()) {
      esms.etonenet.boss1069.web.decorate.TextFilter textFilters =
          new esms.etonenet.boss1069.web.decorate.TextFilter();
      List<Integer> inte =
          CheckBoxUtil.findx2Value(textFilter.getTextFilterCategoryFlag().intValue());
      textFilters.setTextFilterPattern(textFilter.getTextFilterPattern());
      StringBuffer sb = new StringBuffer();
      for (Integer integer : inte) {
        if (integer != null)
          sb.append(ContentFilterCategoryFlag.toDisplayMap().get(String.valueOf(integer)));
        sb.append(" ");
      }
      textFilters.setTextFilterCategoryFlagName(sb.toString().trim());
      list.add(textFilters);
    }
    return AjaxPageUtil.toAjaxPage(p.getTotalElements(), list);
  }
  @Test
  public void shouldFilterSearchResultsForGivenFilter() {
    // given
    String documentId = randomNumeric(5);
    SampleEntity sampleEntity = new SampleEntity();
    sampleEntity.setId(documentId);
    sampleEntity.setMessage("some message");
    sampleEntity.setVersion(System.currentTimeMillis());

    IndexQuery indexQuery = new IndexQuery();
    indexQuery.setId(documentId);
    indexQuery.setObject(sampleEntity);
    elasticsearchTemplate.index(indexQuery);
    elasticsearchTemplate.refresh(SampleEntity.class, true);

    SearchQuery searchQuery =
        new NativeSearchQueryBuilder()
            .withQuery(matchAllQuery())
            .withFilter(boolFilter().must(termFilter("id", documentId)))
            .build();
    // when
    Page<SampleEntity> sampleEntities =
        elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
    // then
    assertThat(sampleEntities.getTotalElements(), equalTo(1L));
  }
  @Test
  public void shouldDeleteDocumentBySpecifiedTypeUsingDeleteQuery() {
    // given
    String documentId = randomNumeric(5);
    SampleEntity sampleEntity = new SampleEntity();
    sampleEntity.setId(documentId);
    sampleEntity.setMessage("some message");
    sampleEntity.setVersion(System.currentTimeMillis());

    IndexQuery indexQuery = new IndexQuery();
    indexQuery.setId(documentId);
    indexQuery.setObject(sampleEntity);

    elasticsearchTemplate.index(indexQuery);
    // when
    DeleteQuery deleteQuery = new DeleteQuery();
    deleteQuery.setQuery(fieldQuery("id", documentId));
    deleteQuery.setIndex("test-index");
    deleteQuery.setType("test-type");
    elasticsearchTemplate.delete(deleteQuery);
    // then
    SearchQuery searchQuery =
        new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
    Page<SampleEntity> sampleEntities =
        elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
    assertThat(sampleEntities.getTotalElements(), equalTo(0L));
  }
  /** @see DATAJPA-472 */
  @Test
  public void shouldSupportFindAllWithPageableAndEntityWithIdClass() throws Exception {

    if (Package.getPackage("org.hibernate.cfg").getImplementationVersion().startsWith("4.1.")) {

      // we expect this test to fail on 4.1.x - due to a bug in hibernate - remove as soon as 4.1.x
      // fixes the issue.
      expectedException.expect(InvalidDataAccessApiUsageException.class);
      expectedException.expectMessage("No supertype found");
    }

    IdClassExampleDepartment dep = new IdClassExampleDepartment();
    dep.setName("TestDepartment");
    dep.setDepartmentId(-1);

    IdClassExampleEmployee emp = new IdClassExampleEmployee();
    emp.setDepartment(dep);
    emp = employeeRepositoryWithIdClass.save(emp);

    Page<IdClassExampleEmployee> page =
        employeeRepositoryWithIdClass.findAll(new PageRequest(0, 10));

    assertThat(page, is(notNullValue()));
    assertThat(page.getTotalElements(), is(1L));
  }
  /**
   * Gets the link node of the previous page.
   *
   * @param page the pagination object
   * @param contextPath current context path of servlet
   * @return the node
   */
  private Element getPreviousElement(final Page<?> page, final String contextPath) {
    final Element result = new Element("li");

    String url;
    if (!page.hasPrevious()) {
      url = getPagedParams(contextPath, 0, page.getSize());
    } else {
      url = getPagedParams(contextPath, page.getNumber() - 1, page.getSize());
    }

    final Element a = new Element("a");
    a.setAttribute("href", url);
    result.addChild(a);

    final Element icon = new Element("i");
    icon.setAttribute("class", "glyphicon glyphicon-triangle-left");

    a.addChild(icon);

    if (!page.hasPrevious()) {
      result.setAttribute("class", "disabled");
    }

    return result;
  }
  @Test
  // @Transactional
  public void JPAPageTest() {

    QCpCtrl qcpCtrl = QCpCtrl.cpCtrl;

    final Pageable page =
        new PageRequest(
            0,
            1,
            new Sort(
                new Sort.Order(Sort.Direction.ASC, "id.regstDay"),
                new Sort.Order(Sort.Direction.ASC, "id.regstTime")));

    Page<CpCtrl> cpCtrlEntries =
        cpCtrlRepository.findAll(
            qcpCtrl.id.eqpNum.eq(7).and(qcpCtrl.id.outletNum.eq(1)).and(qcpCtrl.transYn.eq("N")),
            page);

    cpCtrlEntries.forEach(
        c -> {
          System.out.println(c.getId().getRegstDay());
          System.out.println(c.getId().getRegstTime());
          // System.out.println(c.getCtrlParameter().toString());
          System.out.println(c.getOutletStat());
          System.out.println(c.getRegst());
        });
  }
  @Test
  @Transactional
  @Rollback(value = true)
  @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL)
  public void test_Pageable_GetAllRecentUpdate() throws Exception {
    final int count = 10;

    Map<NEntityReference, Persistable<Long>> persistableMap = Maps.newHashMap();
    for (int it = 0; it < count; it++) {
      final Persistable<Long> persistable = this.getSpiedPersistableFromSupported(it);
      Mockito.when(persistable.getId()).thenReturn((long) (it + 1));
      final NEntityReference ref =
          (NEntityReference) this.entityReferenceHelper.toReference(persistable);
      this.recentlyUpdatedService.newRecentUpdate(persistable);

      persistableMap.put(ref, persistable);
    }

    final EntityReferenceHelper spy = Mockito.spy(this.entityReferenceHelper);
    for (final NEntityReference ref : persistableMap.keySet()) {
      Mockito.when(spy.fromReference(ref)).thenReturn(persistableMap.get(ref));
    }

    ReflectionTestUtils.setField(this.recentlyUpdatedService, "entityReferenceHelper", spy);

    final Page<RecentUpdateBean> recentlyUpdated =
        this.recentlyUpdatedService.getRecentlyUpdated(new PageRequest(0, 50));

    Assert.assertNotNull(recentlyUpdated);
    Assert.assertTrue(recentlyUpdated.getNumberOfElements() > 0);
    Assert.assertEquals(count, recentlyUpdated.getNumberOfElements());
  }
  public DomainList<BeneficiaryDomain> getBeneficiariesByArrangement(
      ArrangementDomain arrangement, Integer pageIndex, Integer pageSize) {
    Pageable pageable = new PageRequest(pageIndex, pageSize);
    Page<BeneficiaryDomain> page = beneficiaryRepository.findByArrangement(arrangement, pageable);

    return new DomainList<BeneficiaryDomain>(page.getContent(), (int) page.getTotalElements());
  }
 @Override
 public void restartDataTracking() {
   Page<TwitterUser> existingUsers =
       twitterUserRepository.findAllListMembers(new PageRequest(0, 4000));
   tick5StatusListener.halt();
   tick5StatusListener.listen(existingUsers.getContent());
 }
Esempio n. 26
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  @RequestMapping("Qry")
  public String query(
      BatchManageForm batchManageForm, @PageableDefaults Pageable pageable, Model model) {
    batchManageServ.transTimeFmtRemove(batchManageForm);

    BatTaskInfo query_batTaskInfo = new BatTaskInfo();
    query_batTaskInfo.setTaskName(batchManageForm.getQuery_task_name());
    query_batTaskInfo.setTaskStartType(batchManageForm.getQuery_task_type());
    query_batTaskInfo.setTaskStartTimeStart(batchManageForm.getQuery_taskStartTimeStart());
    query_batTaskInfo.setTaskStartTimeEnd(batchManageForm.getQuery_taskStartTimeEnd());
    if (null != batchManageForm.getQuery_task_start_day()
        && !"".equals(batchManageForm.getQuery_task_start_day())) {
      query_batTaskInfo.setTaskStartDay(
          Short.parseShort(batchManageForm.getQuery_task_start_day()));
    }

    Page page = batchManageServ.queryBatTaskInfoByPage(pageable, query_batTaskInfo);
    List<BatTaskInfo> taskInfos = page.getContent();
    for (int i = 0; i < taskInfos.size(); i++) {
      BatTaskInfo taskInfo = taskInfos.get(i);
      taskInfo.setTaskStartTime(DateUtil.getFormatTimeAddColon(taskInfo.getTaskStartTime()));
    }

    if (page.getContent().size() > 0) {
      model.addAttribute("page", page);
      batchManageServ.transTimeFmtAdd(batchManageForm);
      return "sysrunner/BMG_TASK_Qry";
    } else {
      model.addAttribute(ResultMessages.info().add("w.sm.0001"));
      batchManageServ.transTimeFmtAdd(batchManageForm);
      return "sysrunner/BMG_TASK_Qry";
    }
  }
Esempio n. 27
0
  public void runAll(String dataPath, String logPath) {
    FileUtil fileData = new FileUtil(dataPath, "out", false);
    FileUtil fileLog = new FileUtil(logPath, "out", false);
    dalian = new Dalian(fileLog);
    System.out.println("Process jiabi data start.");
    int onepage = 1000;

    long count = jiabiBaseDao.count();
    for (int i = 0; i <= count / onepage; i++) {
      long t1 = System.currentTimeMillis();
      Page<SimJiabiBaseInfo> readPage = jiabiBaseDao.findAll(new PageRequest(i, onepage));
      long t2 = System.currentTimeMillis();
      System.out.println("找1000个的时间:" + (t2 - t1));
      for (SimJiabiBaseInfo jbi : readPage.getContent()) {
        HashMap<String, HashMap<Integer, Double>> ans = getSim(jbi.getFmid());
        if (ans != null && ans.size() != 0) MapHelper.write("J" + jbi.getFmid(), ans, fileData);
      }
      System.out.println(
          "The number of completed items: " + (i * onepage + readPage.getContent().size()));
    }

    fileData.close();
    fileLog.close();
    System.out.println("Process jiabi data end.");
  }
  @Test
  public void shouldSortResultsGivenSortCriteria() {
    // given
    List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
    // first document
    String documentId = randomNumeric(5);
    SampleEntity sampleEntity1 = new SampleEntity();
    sampleEntity1.setId(documentId);
    sampleEntity1.setMessage("abc");
    sampleEntity1.setRate(10);
    sampleEntity1.setVersion(System.currentTimeMillis());

    IndexQuery indexQuery1 = new IndexQuery();
    indexQuery1.setId(documentId);
    indexQuery1.setObject(sampleEntity1);

    // second document
    String documentId2 = randomNumeric(5);
    SampleEntity sampleEntity2 = new SampleEntity();
    sampleEntity2.setId(documentId2);
    sampleEntity2.setMessage("xyz");
    sampleEntity2.setRate(5);
    sampleEntity2.setVersion(System.currentTimeMillis());

    IndexQuery indexQuery2 = new IndexQuery();
    indexQuery2.setId(documentId2);
    indexQuery2.setObject(sampleEntity2);

    // third document
    String documentId3 = randomNumeric(5);
    SampleEntity sampleEntity3 = new SampleEntity();
    sampleEntity3.setId(documentId3);
    sampleEntity3.setMessage("xyz");
    sampleEntity3.setRate(15);
    sampleEntity3.setVersion(System.currentTimeMillis());

    IndexQuery indexQuery3 = new IndexQuery();
    indexQuery3.setId(documentId3);
    indexQuery3.setObject(sampleEntity3);

    indexQueries.add(indexQuery1);
    indexQueries.add(indexQuery2);
    indexQueries.add(indexQuery3);

    elasticsearchTemplate.bulkIndex(indexQueries);
    elasticsearchTemplate.refresh(SampleEntity.class, true);

    SearchQuery searchQuery =
        new NativeSearchQueryBuilder()
            .withQuery(matchAllQuery())
            .withSort(new FieldSortBuilder("rate").ignoreUnmapped(true).order(SortOrder.ASC))
            .build();
    // when
    Page<SampleEntity> sampleEntities =
        elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
    // then
    assertThat(sampleEntities.getTotalElements(), equalTo(3L));
    assertThat(sampleEntities.getContent().get(0).getRate(), is(sampleEntity2.getRate()));
  }
 private void addPreviousLink(Page<T> page, String pageParam, String sizeParam) {
   if (page.hasPrevious()) {
     Link link =
         buildPageLink(
             pageParam, page.getNumber() - 1, sizeParam, page.getSize(), Link.REL_PREVIOUS);
     add(link);
   }
 }
 @Override
 public <T> T queryForObject(StringQuery query, Class<T> clazz) {
   Page<T> page = queryForPage(query, clazz);
   Assert.isTrue(
       page.getTotalElements() < 2,
       "Expected 1 but found " + page.getTotalElements() + " results");
   return page.getTotalElements() > 0 ? page.getContent().get(0) : null;
 }