List of usage examples for org.springframework.data.domain PageImpl PageImpl
public PageImpl(List<T> content)
From source file:com.github.vanroy.springdata.jest.JestElasticsearchTemplateTests.java
@Test /**/*ww w. j a v a2s .c o m*/ * This is basically a demonstration to show composing entities out of heterogeneous indexes. */ public void shouldComposeObjectsReturnedFromHeterogeneousIndexes() { // Given HetroEntity1 entity1 = new HetroEntity1(randomNumeric(3), "aFirstName"); HetroEntity2 entity2 = new HetroEntity2(randomNumeric(4), "aLastName"); IndexQuery idxQuery1 = new IndexQueryBuilder().withIndexName(INDEX_1_NAME).withId(entity1.getId()) .withObject(entity1).build(); IndexQuery idxQuery2 = new IndexQueryBuilder().withIndexName(INDEX_2_NAME).withId(entity2.getId()) .withObject(entity2).build(); elasticsearchTemplate.bulkIndex(Arrays.asList(idxQuery1, idxQuery2)); elasticsearchTemplate.refresh(INDEX_1_NAME); elasticsearchTemplate.refresh(INDEX_2_NAME); // When SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withTypes("hetro") .withIndices(INDEX_1_NAME, INDEX_2_NAME).build(); Page<ResultAggregator> page = elasticsearchTemplate.queryForPage(searchQuery, ResultAggregator.class, new JestSearchResultMapper() { @Override public <T> Page<T> mapResults(SearchResult response, Class<T> clazz, Pageable pageable) { List<ResultAggregator> values = new ArrayList<>(); for (SearchResult.Hit<JsonObject, Void> searchHit : response.getHits(JsonObject.class)) { String id = String.valueOf(searchHit.source.get("id")); String firstName = searchHit.source.get("firstName") != null ? searchHit.source.get("firstName").getAsString() : ""; String lastName = searchHit.source.get("lastName") != null ? searchHit.source.get("lastName").getAsString() : ""; values.add(new ResultAggregator(id, firstName, lastName)); } return new PageImpl<>((List<T>) values); } }); assertThat(page.getTotalElements(), is(2L)); }
From source file:org.apereo.openlrs.model.event.EventConversionService.java
public Page<Event> toEventPage(Page<OpenLRSEntity> page) { Page<Event> events = null; if (page != null && page.getContent() != null && !page.getContent().isEmpty()) { List<OpenLRSEntity> entities = page.getContent(); List<Event> eventList = new ArrayList<Event>(); for (OpenLRSEntity entity : entities) { eventList.add(toEvent(entity)); }//from ww w .ja v a2 s . c o m events = new PageImpl<Event>(eventList); } return events; }
From source file:org.apereo.openlrs.model.event.EventConversionService.java
public Page<Statement> toXApiPage(Page<OpenLRSEntity> page) { Page<Statement> statements = null; if (page != null && page.getContent() != null && !page.getContent().isEmpty()) { List<OpenLRSEntity> entities = page.getContent(); List<Statement> statementList = new ArrayList<Statement>(); for (OpenLRSEntity entity : entities) { statementList.add(toXApi(entity)); }/*w w w . j a va 2 s .com*/ statements = new PageImpl<Statement>(statementList); } return statements; }
From source file:org.apereo.openlrs.storage.elasticsearch.XApiOnlyElasticsearchTierTwoStorage.java
@Override public Page<OpenLRSEntity> findAll(Pageable pageable) { Iterable<Statement> iterableStatements = esSpringDataRepository.findAll(); if (iterableStatements != null) { return new PageImpl<OpenLRSEntity>(IteratorUtils.toList(iterableStatements.iterator())); }/* w ww. j a va 2 s .com*/ return null; }
From source file:org.apereo.openlrs.storage.elasticsearch.XApiOnlyElasticsearchTierTwoStorage.java
@Override public Page<OpenLRSEntity> findWithFilters(Map<String, String> filters, Pageable pageable) { String actor = filters.get(StatementUtils.ACTOR_FILTER); String activity = filters.get(StatementUtils.ACTIVITY_FILTER); String since = filters.get(StatementUtils.SINCE_FILTER); String until = filters.get(StatementUtils.UNTIL_FILTER); int limit = getLimit(filters.get(StatementUtils.LIMIT_FILTER)); ;/* ww w . java 2 s .co m*/ XApiActor xApiActor = null; if (StringUtils.isNotBlank(actor)) { ObjectMapper objectMapper = new ObjectMapper(); try { xApiActor = objectMapper.readValue(actor.getBytes(), XApiActor.class); } catch (Exception e) { log.error(e.getMessage(), e); } } SearchQuery searchQuery = null; if (StringUtils.isNotBlank(activity) && xApiActor != null) { QueryBuilder actorQuery = buildActorQuery(xApiActor); QueryBuilder activityQuery = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity))); BoolQueryBuilder boolQuery = boolQuery().must(actorQuery).must(activityQuery); searchQuery = startQuery(limit, boolQuery).build(); } else if (xApiActor != null) { QueryBuilder query = buildActorQuery(xApiActor); if (query != null) { searchQuery = startQuery(limit, query).build(); } } else if (StringUtils.isNotBlank(activity)) { QueryBuilder query = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity))); searchQuery = startQuery(limit, query).build(); } else if (StringUtils.isNotBlank(since) || StringUtils.isNotBlank(until)) { QueryBuilder query = null; if (StringUtils.isNotBlank(since) && StringUtils.isNotBlank(until)) { query = new RangeQueryBuilder("stored").from(since).to(until); } else { if (StringUtils.isNotBlank(since)) { query = new RangeQueryBuilder("stored").from(since).to("now"); } if (StringUtils.isNotBlank(until)) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); TimeZone tz = TimeZone.getTimeZone("UTC"); formatter.setTimeZone(tz); Date date = (Date) formatter.parse(until); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR, -1); query = new RangeQueryBuilder("stored").from(formatter.format(calendar.getTime())) .to(until); } catch (ParseException e) { log.error(e.getMessage(), e); return null; } } } NativeSearchQueryBuilder searchQueryBuilder = startQuery(limit, query); searchQuery = searchQueryBuilder.withSort(new FieldSortBuilder("stored").order(SortOrder.DESC)).build(); } else if (limit > 0) { searchQuery = startQuery(limit, null).build(); } if (searchQuery != null) { if (log.isDebugEnabled()) { if (searchQuery.getQuery() != null) { log.debug(String.format("Elasticsearch query %s", searchQuery.getQuery().toString())); } } Iterable<Statement> iterableStatements = esSpringDataRepository.search(searchQuery); if (iterableStatements != null) { return new PageImpl<OpenLRSEntity>(IteratorUtils.toList(iterableStatements.iterator())); } } return null; }
From source file:org.dspace.app.rest.model.hateoas.DSpaceResource.java
public DSpaceResource(T data, Utils utils, String... rels) { this.data = data; if (data != null) { try {/*from w w w.j ava 2s. c o m*/ LinksRest links = data.getClass().getDeclaredAnnotation(LinksRest.class); if (links != null && rels != null) { List<String> relsList = Arrays.asList(rels); for (LinkRest linkAnnotation : links.links()) { if (!relsList.contains(linkAnnotation.name())) { continue; } String name = linkAnnotation.name(); Link linkToSubResource = utils.linkToSubResource(data, name); String apiCategory = data.getCategory(); String model = data.getType(); LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkAnnotation.name()); if (!linkRepository.isEmbeddableRelation(data, linkAnnotation.name())) { continue; } try { //RestModel linkClass = linkAnnotation.linkClass().newInstance(); Method[] methods = linkRepository.getClass().getMethods(); boolean found = false; for (Method m : methods) { if (StringUtils.equals(m.getName(), linkAnnotation.method())) { // TODO add support for single linked object other than for collections Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m.invoke( linkRepository, null, ((BaseObjectRest) data).getId(), null, null); EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(), pageResult, null); embedded.put(name, ep); found = true; } } // TODO custom exception if (!found) { throw new RuntimeException("Method for relation " + linkAnnotation.name() + " not found: " + linkAnnotation.method()); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } } } for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); String name = pd.getName(); if (readMethod != null && !"class".equals(name)) { LinkRest linkAnnotation = readMethod.getAnnotation(LinkRest.class); if (linkAnnotation != null) { if (StringUtils.isNotBlank(linkAnnotation.name())) { name = linkAnnotation.name(); } Link linkToSubResource = utils.linkToSubResource(data, name); // no method is specified to retrieve the linked object(s) so check if it is already here if (StringUtils.isBlank(linkAnnotation.method())) { this.add(linkToSubResource); Object linkedObject = readMethod.invoke(data); Object wrapObject = linkedObject; if (linkedObject instanceof RestModel) { RestModel linkedRM = (RestModel) linkedObject; wrapObject = utils .getResourceRepository(linkedRM.getCategory(), linkedRM.getType()) .wrapResource(linkedRM); } else { if (linkedObject instanceof List) { List<RestModel> linkedRMList = (List<RestModel>) linkedObject; if (linkedRMList.size() > 0) { DSpaceRestRepository<RestModel, ?> resourceRepository = utils .getResourceRepository(linkedRMList.get(0).getCategory(), linkedRMList.get(0).getType()); // TODO should we force pagination also of embedded resource? // This will force a pagination with size 10 for embedded collections as well // int pageSize = 1; // PageImpl<RestModel> page = new PageImpl( // linkedRMList.subList(0, // linkedRMList.size() > pageSize ? pageSize : linkedRMList.size()), new PageRequest(0, pageSize), linkedRMList.size()); PageImpl<RestModel> page = new PageImpl(linkedRMList); wrapObject = new EmbeddedPage(linkToSubResource.getHref(), page.map(resourceRepository::wrapResource), linkedRMList); } else { wrapObject = null; } } } if (linkedObject != null) { embedded.put(name, wrapObject); } else { embedded.put(name, null); } Method writeMethod = pd.getWriteMethod(); writeMethod.invoke(data, new Object[] { null }); } else { // call the link repository try { //RestModel linkClass = linkAnnotation.linkClass().newInstance(); String apiCategory = data.getCategory(); String model = data.getType(); LinkRestRepository linkRepository = utils.getLinkResourceRepository(apiCategory, model, linkAnnotation.name()); Method[] methods = linkRepository.getClass().getMethods(); boolean found = false; for (Method m : methods) { if (StringUtils.equals(m.getName(), linkAnnotation.method())) { // TODO add support for single linked object other than for collections Page<? extends Serializable> pageResult = (Page<? extends RestModel>) m .invoke(linkRepository, null, ((BaseObjectRest) data).getId(), null, null); EmbeddedPage ep = new EmbeddedPage(linkToSubResource.getHref(), pageResult, null); embedded.put(name, ep); found = true; } } // TODO custom exception if (!found) { throw new RuntimeException("Method for relation " + linkAnnotation.name() + " not found: " + linkAnnotation.method()); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) { Link linkToSubResource = utils.linkToSubResource(data, name); this.add(linkToSubResource); RestModel linkedObject = (RestModel) readMethod.invoke(data); if (linkedObject != null) { embedded.put(name, utils .getResourceRepository(linkedObject.getCategory(), linkedObject.getType()) .wrapResource(linkedObject)); } else { embedded.put(name, null); } Method writeMethod = pd.getWriteMethod(); writeMethod.invoke(data, new Object[] { null }); } } } } catch (IntrospectionException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } this.add(utils.linkToSingleResource(data, Link.REL_SELF)); } }
From source file:org.jbb.lib.mvc.PageWrapperTest.java
@Test public void pageItemTest() throws Exception { // given//from w w w .j a v a2 s .c om Page<String> page = new PageImpl<>(getContentWithSize(10)); // when PageWrapper<String> pageWrapper = new PageWrapper<>(page); PageItem pageItem = pageWrapper.getItems().get(0); // then assertThat(pageItem.getNumber()).isEqualTo(1); assertThat(pageItem.isCurrent()).isTrue(); assertThat(pageItem.paramNumber()).isEqualTo(0); }
From source file:org.jbb.lib.mvc.PageWrapperTest.java
@Test public void singlePageTest_forBelowMaxPageItemDisplay() throws Exception { // given// w w w . j ava 2 s. c om Page<String> page = new PageImpl<>(getContentWithSize(10)); // when PageWrapper<String> pageWrapper = new PageWrapper<>(page); // then assertThat(pageWrapper.getItems()).hasSize(1); assertThat(pageWrapper.getNumber()).isEqualTo(1); assertThat(pageWrapper.getContent()).hasSize(10); assertThat(pageWrapper.getSize()).isEqualTo(0); assertThat(pageWrapper.getTotalPages()).isEqualTo(1); assertThat(pageWrapper.isFirstPage()).isTrue(); assertThat(pageWrapper.isLastPage()).isTrue(); assertThat(pageWrapper.isHasNextPage()).isFalse(); assertThat(pageWrapper.isHasPreviousPage()).isFalse(); }
From source file:org.jtalks.jcommune.plugin.questionsandanswers.controller.QuestionsAndAnswersController.java
/** * Shows question page/*from ww w . jav a 2 s . com*/ * * @param request HttpServletRequest * @param model model for transferring to jsp * @param id id of question * * @return plugin view name * @throws NotFoundException if question with specified id not found */ @RequestMapping(value = "{id}", method = RequestMethod.GET) public String showQuestion(HttpServletRequest request, Model model, @PathVariable("id") Long id) throws NotFoundException { Topic topic = getTypeAwarePluginTopicService().get(id, QuestionsAndAnswersPlugin.TOPIC_TYPE); getTypeAwarePluginTopicService().checkViewTopicPermission(topic.getBranch().getId()); JCUser currentUser = getUserReader().getCurrentUser(); PostDto postDto = new PostDto(); PostDraft draft = topic.getDraftForUser(currentUser); if (draft != null) { postDto = PostDto.getDtoFor(draft); } Map<String, Object> data = getDefaultModel(request); data.put(QUESTION, topic); data.put(POST_PAGE, new PageImpl<>(getSortedPosts(topic.getPosts()))); data.put(BREADCRUMB_LIST, breadcrumbBuilder.getForumBreadcrumb(topic)); data.put(SUBSCRIBED, false); data.put(CONVERTER, BbToHtmlConverter.getInstance()); data.put(VIEW_LIST, getLocationService().getUsersViewing(topic)); data.put(POST_DTO, postDto); data.put(LIMIT_OF_POSTS_ATTRIBUTE, LIMIT_OF_POSTS_VALUE); getPluginLastReadPostService().markTopicAsRead(topic); VelocityEngine engine = new VelocityEngine(getProperties()); engine.init(); model.addAttribute(CONTENT, getMergedTemplate(engine, QUESTION_TEMPLATE_PATH, "UTF-8", data)); return PLUGIN_VIEW_NAME; }
From source file:org.jtalks.jcommune.plugin.questionsandanswers.controller.QuestionsAndAnswersController.java
/** * Process the answer form. Adds new answer to the specified question and redirects to the * question view page./*from ww w .j a v a 2 s .com*/ * * @param questionId id of question to which answer will be added * @param postDto dto that contains data entered in form * @param result validation result * @param model model for transferring to template * @param request HttpServletRequest * * @return redirect to the answer or back to answer page if validation failed * @throws NotFoundException when question or branch not found */ @RequestMapping(value = "{questionId}", method = RequestMethod.POST) public String create(@PathVariable("questionId") Long questionId, @Valid @ModelAttribute PostDto postDto, BindingResult result, Model model, HttpServletRequest request) throws NotFoundException { postDto.setTopicId(questionId); Topic topic = getTypeAwarePluginTopicService().get(questionId, QuestionsAndAnswersPlugin.TOPIC_TYPE); //We can't provide limitation properly without database-level locking if (result.hasErrors() || LIMIT_OF_POSTS_VALUE <= topic.getPostCount() - 1) { JCUser currentUser = getUserReader().getCurrentUser(); PostDraft draft = topic.getDraftForUser(currentUser); if (draft != null) { // If we create new dto object instead of using already existing // we lose error messages linked with it postDto.fillFrom(draft); } Map<String, Object> data = getDefaultModel(request); VelocityEngine engine = new VelocityEngine(getProperties()); engine.init(); data.put(QUESTION, topic); data.put(POST_PAGE, new PageImpl<>(getSortedPosts(topic.getPosts()))); data.put(BREADCRUMB_LIST, breadcrumbBuilder.getForumBreadcrumb(topic)); data.put(SUBSCRIBED, false); data.put(RESULT, result); data.put(CONVERTER, BbToHtmlConverter.getInstance()); data.put(VIEW_LIST, getLocationService().getUsersViewing(topic)); data.put(POST_DTO, postDto); data.put(LIMIT_OF_POSTS_ATTRIBUTE, LIMIT_OF_POSTS_VALUE); model.addAttribute(CONTENT, getMergedTemplate(engine, QUESTION_TEMPLATE_PATH, "UTF-8", data)); return PLUGIN_VIEW_NAME; } Post newbie = getTypeAwarePluginTopicService().replyToTopic(questionId, postDto.getBodyText(), topic.getBranch().getId()); getPluginLastReadPostService().markTopicAsRead(newbie.getTopic()); return "redirect:" + QuestionsAndAnswersPlugin.CONTEXT + "/" + questionId + "#" + newbie.getId(); }