List of usage examples for org.springframework.data.domain Page getContent
List<T> getContent();
From source file:org.jtalks.jcommune.model.dao.search.hibernate.TopicHibernateSearchDaoTest.java
@Test public void testFullPhraseSearchPageNumberTooLow() { Topic expectedTopic = PersistedObjectsFactory.getDefaultTopic(); expectedTopic.setTitle(TOPIC_CONTENT); saveAndFlushIndexes(Arrays.asList(expectedTopic)); configureMocks(TOPIC_CONTENT, TOPIC_CONTENT); PageRequest pageRequest = new PageRequest("-1", PAGE_SIZE); Page<Topic> searchResultPage = topicSearchDao.searchByTitleAndContent(TOPIC_CONTENT, pageRequest, Arrays.asList(expectedTopic.getBranch().getId())); Assert.assertEquals(searchResultPage.getNumber(), 1); Assert.assertTrue(searchResultPage.hasContent(), "Search result must not be empty."); for (Topic topic : searchResultPage.getContent()) { Assert.assertEquals(expectedTopic.getTitle(), topic.getTitle(), "Content from the index should be the same as in the database."); }/*from w w w . j a va 2s. c o m*/ }
From source file:org.jtalks.jcommune.model.dao.search.hibernate.TopicHibernateSearchDaoTest.java
@Test public void testFullPhraseSearchPageNumberTooBig() { Topic expectedTopic = PersistedObjectsFactory.getDefaultTopic(); expectedTopic.setTitle(TOPIC_CONTENT); saveAndFlushIndexes(Arrays.asList(expectedTopic)); configureMocks(TOPIC_CONTENT, TOPIC_CONTENT); PageRequest pageRequest = new PageRequest("1000", 50); Page<Topic> searchResultPage = topicSearchDao.searchByTitleAndContent(TOPIC_CONTENT, pageRequest, Arrays.asList(expectedTopic.getBranch().getId())); Assert.assertEquals(searchResultPage.getNumber(), 1); Assert.assertTrue(searchResultPage.hasContent(), "Search result must not be empty."); for (Topic topic : searchResultPage.getContent()) { Assert.assertEquals(expectedTopic.getTitle(), topic.getTitle(), "Content from the index should be the same as in the database."); }/*from w w w . j a va2 s . com*/ }
From source file:org.jtalks.jcommune.model.dao.search.hibernate.TopicHibernateSearchDaoTest.java
@Test(dataProvider = "parameterFullPhraseSearch") public void testPostContentSearch(String content) { Topic expectedTopic = PersistedObjectsFactory.getDefaultTopic(); expectedTopic.getLastPost().setPostContent(content); saveAndFlushIndexes(Arrays.asList(expectedTopic)); configureMocks(content, content);/*from ww w . java 2 s . c o m*/ Page<Topic> searchResultPage = topicSearchDao.searchByTitleAndContent(content, DEFAULT_PAGE_REQUEST, Arrays.asList(expectedTopic.getBranch().getId())); Assert.assertTrue(searchResultPage.hasContent(), "Search result must not be empty."); for (Topic topic : searchResultPage.getContent()) { Assert.assertEquals(expectedTopic.getTitle(), topic.getTitle(), "Content from the index should be the same as in the database."); } }
From source file:org.lareferencia.backend.indexer.IndexerImpl.java
public synchronized boolean index(NetworkSnapshot snapshot) { try {/*ww w . ja v a 2 s . co m*/ // Borrado de los docs del pas del snapshot MessageDigest md = MessageDigest.getInstance("MD5"); String countryISO = snapshot.getNetwork().getCountryISO(); this.sendUpdateToSolr( "<delete><query>country_iso:" + snapshot.getNetwork().getCountryISO() + "</query></delete>"); // Update de los registros de a PAGE_SIZE Page<OAIRecord> page = recordRepository.findBySnapshotIdAndStatus(snapshot.getId(), RecordStatus.VALID, new PageRequest(0, PAGE_SIZE)); int totalPages = page.getTotalPages(); Long lastId = -1L; // Aqu se guarda el ultimo id de cada pgina para ser usado en el la query optimizada for (int i = 0; i < totalPages; i++) { Transformer trf = buildTransformer(); trf.setParameter("country_iso", countryISO); trf.setParameter("country", snapshot.getNetwork().getName()); //page = recordRepository.findBySnapshotIdAndStatusLimited(snapshot.getId(), RecordStatus.VALID, lastId, new PageRequest(0, PAGE_SIZE) ); page = recordRepository.findBySnapshotIdAndStatus(snapshot.getId(), RecordStatus.VALID, new PageRequest(i, PAGE_SIZE)); System.out.println("Indexando Snapshot: " + snapshot.getId() + " de: " + snapshot.getNetwork().getName() + " pgina: " + i + " de: " + totalPages); StringBuffer strBuf = new StringBuffer(); List<OAIRecord> records = page.getContent(); for (OAIRecord record : records) { OAIRecordMetadata domRecord = new OAIRecordMetadata(record.getIdentifier(), record.getPublishedXML()); StringWriter stringWritter = new StringWriter(); Result output = new StreamResult(stringWritter); // id unico pero mutable para solr trf.setParameter("solr_id", countryISO + "_" + snapshot.getId().toString() + "_" + record.getId().toString()); // id permantente para vufind trf.setParameter("vufind_id", countryISO + "_" + DigestUtils.md5Hex(record.getPublishedXML())); // header id para staff trf.setParameter("header_id", record.getIdentifier()); // Se transforma y genera el string del registro trf.transform(new DOMSource(domRecord.getDOMDocument()), output); strBuf.append(stringWritter.toString()); // Se actualiza el lastID para permitir la paginacin con offset 0 //lastId = records.get( records.size()-1 ).getId(); } this.sendUpdateToSolr("<add>" + strBuf.toString() + "</add>"); trf = null; page = null; strBuf = null; } // commit de los cambios this.sendUpdateToSolr("<commit/>"); } catch (Exception e) { e.printStackTrace(); try { this.sendUpdateToSolr("<rollback/>"); } catch (SolrServerException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return false; } return true; }
From source file:org.lareferencia.backend.indexer.IntelligoIndexer.java
public synchronized boolean index(NetworkSnapshot snapshot) { try {//ww w . j a va2s . c o m // Borrado de los docs del pas del snapshot Page<OAIRecord> page = recordRepository.findBySnapshotIdAndStatus(snapshot.getId(), RecordStatus.VALID, new PageRequest(0, PAGE_SIZE)); int totalPages = page.getTotalPages(); String filepath = outputPath + "/" + snapshot.getNetwork().getName().replace(" ", "_") + "_" + snapshot.getId(); boolean success = (new File(filepath)).mkdirs(); if (!success) { // Directory creation failed } for (int i = 0; i < totalPages; i++) { Transformer trf = buildTransformer(); //trf.setParameter("country", snapshot.getNetwork().getName() ); page = recordRepository.findBySnapshotIdAndStatus(snapshot.getId(), RecordStatus.VALID, new PageRequest(i, PAGE_SIZE)); System.out.println("Indexando Snapshot: " + snapshot.getId() + " de: " + snapshot.getNetwork().getName() + " pgina: " + i + " de: " + totalPages); StringBuffer strBuf = new StringBuffer(); List<OAIRecord> records = page.getContent(); strBuf.append("<add>"); for (OAIRecord record : records) { OAIRecordMetadata metadata = new OAIRecordMetadata(record.getIdentifier(), record.getPublishedXML()); StringWriter stringWritter = new StringWriter(); Result output = new StreamResult(stringWritter); // id unico pero mutable para solr trf.setParameter("solr_id", snapshot.getId() + "." + record.getId().toString()); /////// DC:DESCRIPTION - Deteccin y divisin de idiomas String ab_es = ""; String ab_en = ""; String ab_pt = ""; //System.out.println( metadata.getFieldOcurrences("dc:description") ); for (String ab : metadata.getFieldOcurrences("dc:description")) { String lang = detectLang(ab); switch (lang) { case "es": ab_es += ab; break; case "en": ab_en += ab; break; case "pt": ab_pt += ab; break; } } trf.setParameter("ab_es", ab_es); trf.setParameter("ab_en", ab_en); trf.setParameter("ab_pt", ab_pt); ///////////////////////////////////////////////////////////// /////// DC:title - Deteccin y divisin de idiomas String ti_es = ""; String ti_en = ""; String ti_pt = ""; for (String ti : metadata.getFieldOcurrences("dc:title")) { String lang = detectLang(ti); switch (lang) { case "es": ti_es += ti; break; case "en": ti_en += ti; break; case "pt": ti_pt += ti; break; } } trf.setParameter("ti_es", ti_es); trf.setParameter("ti_en", ti_en); trf.setParameter("ti_pt", ti_pt); ///////////////////////////////////////////////////////////// // Se transforma y genera el string del registro trf.transform(new DOMSource(metadata.getDOMDocument()), output); strBuf.append(stringWritter.toString()); } strBuf.append("</add>"); BufferedWriter out = new BufferedWriter(new FileWriter(filepath + "/" + i + ".solr.xml")); out.write(strBuf.toString()); out.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; }
From source file:org.lareferencia.provider.providers.LaReferenciaProvider.java
public List<Record> listRecords(String set, StateHolder state, boolean includeMetadata) throws CannotDisseminateFormatException, NoRecordsMatchException { if (oaiRecordRepository == null) throw new IllegalStateException("listRecords() expects a non-null oairecord repository"); final List<Record> records = new ArrayList<Record>(); if (state.isFirstCall()) { List<Long> snapshotIdList = new ArrayList<Long>(); List<Integer> totalPageList = new ArrayList<Integer>(); // CASO DE SET DEFINIDO if (set != null && !set.toUpperCase().equals(DRIVER_SET_NAME)) { NationalNetwork network = nationalNetworkRepository.findByCountryISO(set); if (network == null) { throw new NoRecordsMatchException("Set dont exist"); } else { NetworkSnapshot snapshot = networkSnapshotRepository .findLastGoodKnowByNetworkID(network.getId()); if (snapshot != null) { // obtiene la primera pgina de cada snapshot Page<OAIRecord> page = oaiRecordRepository.findBySnapshotAndStatus(snapshot, RecordStatus.VALID, new PageRequest(0, PAGE_SIZE)); // agrega los datos del snapshot a la lista snapshotIdList.add(snapshot.getId()); totalPageList.add(page.getTotalPages()); }//ww w . ja v a 2 s . c o m } } else { // CASO DE SET NULL // Se recorren todas las redes publicadas for (NationalNetwork network : nationalNetworkRepository.findByPublishedOrderByNameAsc(true)) { NetworkSnapshot snapshot = networkSnapshotRepository .findLastGoodKnowByNetworkID(network.getId()); if (snapshot != null) { // obtiene la primera pgina de cada snapshot Page<OAIRecord> page = oaiRecordRepository.findBySnapshotAndStatus(snapshot, RecordStatus.VALID, new PageRequest(0, PAGE_SIZE)); // agrega los datos del snapshot a la lista snapshotIdList.add(snapshot.getId()); totalPageList.add(page.getTotalPages()); } } } // se inicializa el estado state.initialize(snapshotIdList, totalPageList); } // obtiene la pgina actual NetworkSnapshot snapshot = networkSnapshotRepository.findOne(state.obtainActualSnapshotID()); Page<OAIRecord> page = oaiRecordRepository.findBySnapshotAndStatus(snapshot, RecordStatus.VALID, new PageRequest(state.obtainActualPage(), PAGE_SIZE)); // actualiza el estado state.update(); /** // Dates. final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); if(session.getFrom() != null && session.getUntil() != null) { final String formattedFrom = dateFormat.format(session.getFrom()); final String formattedUntil = dateFormat.format(session.getUntil()); query.setQuery(query.getQuery() + " AND lastModifiedDateFacet:[" + formattedFrom + " TO " + formattedUntil + "]"); } else if(session.getFrom() != null) { final String formattedFrom = dateFormat.format(session.getFrom()); query.setQuery(query.getQuery() + " AND lastModifiedDateFacet:[" + formattedFrom + " TO 99999999999999999]"); } else if(session.getUntil() != null) { final String formattedUntil = dateFormat.format(session.getUntil()); query.setQuery(query.getQuery() + " AND lastModifiedDateFacet:[00000000000000000 TO " + formattedUntil + "]"); } */ try { if (page.getContent().size() == 0) throw new NoRecordsMatchException(); for (OAIRecord oairecord : page.getContent()) { final Record record = new Record(); // Identifier. record.setIdentifier(buildIdentifier(oairecord)); record.setDate(dateFormat.format(oairecord.getDatestamp())); record.setDeleted(false); record.addSet(oairecord.getSnapshot().getNetwork().getCountryISO()); if (includeMetadata) record.setMetadata(oairecord.getPublishedXML()); records.add(record); } } finally { //session.setMemento(memento); } return records; }
From source file:org.lazulite.boot.autoconfigure.osaam.shiro.web.session.mgt.OnlineWebSessionManager.java
/** * ?session? session/*w w w . j a va 2 s . c om*/ */ @Override public void validateSessions() { if (log.isInfoEnabled()) { log.info("invalidation sessions..."); } int invalidCount = 0; int timeout = (int) getGlobalSessionTimeout(); Date expiredDate = DateUtils.addMilliseconds(new Date(), 0 - timeout); PageRequest pageRequest = new PageRequest(0, 100); Page<UserOnline> page = userOnlineService.findExpiredUserOnlineList(expiredDate, pageRequest); //?? while (page.hasContent()) { List<Long> needOfflineIdList = Lists.newArrayList(); for (UserOnline userOnline : page.getContent()) { try { SessionKey key = new DefaultSessionKey(userOnline.getId()); Session session = retrieveSession(key); //cache db if (session != null) { session.setAttribute(ShiroConstants.ONLY_CLEAR_CACHE, true); } validate(session, key); } catch (InvalidSessionException e) { if (log.isDebugEnabled()) { boolean expired = (e instanceof ExpiredSessionException); String msg = "Invalidated session with id [" + userOnline.getId() + "]" + (expired ? " (expired)" : " (stopped)"); log.debug(msg); } invalidCount++; needOfflineIdList.add(userOnline.getId()); } } if (needOfflineIdList.size() > 0) { try { userOnlineService.batchOffline(needOfflineIdList); } catch (Exception e) { log.error("batch delete db session error.", e); } } pageRequest = new PageRequest(0, pageRequest.getPageSize()); page = userOnlineService.findExpiredUserOnlineList(expiredDate, pageRequest); } if (log.isInfoEnabled()) { String msg = "Finished invalidation session."; if (invalidCount > 0) { msg += " [" + invalidCount + "] sessions were stopped."; } else { msg += " No sessions were stopped."; } log.info(msg); } }
From source file:org.springframework.batch.item.data.RepositoryItemReader.java
/** * Performs the actual reading of a page via the repository. * Available for overriding as needed./*from w w w .j ava 2 s .c om*/ * * @return the list of items that make up the page * @throws Exception */ @SuppressWarnings("unchecked") protected List<T> doPageRead() throws Exception { Pageable pageRequest = new PageRequest(page, pageSize, sort); MethodInvoker invoker = createMethodInvoker(repository, methodName); List<Object> parameters = new ArrayList<Object>(); if (arguments != null && arguments.size() > 0) { parameters.addAll(arguments); } parameters.add(pageRequest); invoker.setArguments(parameters.toArray()); Page<T> curPage = (Page<T>) doInvoke(invoker); return curPage.getContent(); }
From source file:org.springframework.cloud.dataflow.server.service.impl.AbstractStreamService.java
@Override public Page<StreamDefinition> findDefinitionByNameLike(Pageable pageable, String search) { Page<StreamDefinition> streamDefinitions; if (search != null) { final SearchPageable searchPageable = new SearchPageable(pageable, search); searchPageable.addColumns("DEFINITION_NAME", "DEFINITION"); streamDefinitions = streamDefinitionRepository.findByNameLike(searchPageable); long count = streamDefinitions.getContent().size(); long to = Math.min(count, pageable.getOffset() + pageable.getPageSize()); streamDefinitions = new PageImpl<>(streamDefinitions.getContent(), pageable, streamDefinitions.getTotalElements()); } else {//from w w w .j av a2s . c o m streamDefinitions = streamDefinitionRepository.findAll(pageable); } return streamDefinitions; }
From source file:org.springframework.data.elasticsearch.core.ElasticsearchTemplate.java
@Override public <T> T queryForObject(CriteriaQuery 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; }