001 /* 002 * SonarQube, open source software quality management tool. 003 * Copyright (C) 2008-2013 SonarSource 004 * mailto:contact AT sonarsource DOT com 005 * 006 * SonarQube is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * SonarQube is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020 021 package org.sonar.api.utils; 022 023 /** 024 * @since 3.6 025 */ 026 public class Paging { 027 028 private final int pageSize; 029 private final int pageIndex; 030 private final int total; 031 032 private Paging(int pageSize, int pageIndex, int total) { 033 this.pageSize = pageSize; 034 this.pageIndex = pageIndex; 035 this.total = total; 036 } 037 038 /** 039 * Page index, starting with 1. 040 */ 041 public int pageIndex() { 042 return pageIndex; 043 } 044 045 /** 046 * Maximum number of items per page. It is greater than 0. 047 */ 048 public int pageSize() { 049 return pageSize; 050 } 051 052 /** 053 * Total number of items. It is greater than or equal 0. 054 */ 055 public int total() { 056 return total; 057 } 058 059 public int offset(){ 060 return (pageIndex - 1) * pageSize; 061 } 062 063 /** 064 * Number of pages. It is greater than or equal 0. 065 */ 066 public int pages() { 067 int p = total / pageSize; 068 if (total % pageSize > 0) { 069 p++; 070 } 071 return p; 072 } 073 074 public static Paging create(int pageSize, int pageIndex, int totalItems) { 075 if (pageSize<1) { 076 throw new IllegalArgumentException("Page size must be strictly positive. Got " + pageSize); 077 } 078 if (pageIndex<1) { 079 throw new IllegalArgumentException("Page index must be strictly positive. Got " + pageIndex); 080 } 081 if (totalItems<0) { 082 throw new IllegalArgumentException("Total items must be positive. Got " + totalItems); 083 } 084 return new Paging(pageSize, pageIndex, totalItems); 085 } 086 }