1 11 package org.jboss.portlet.forums.helper; 12 13 14 20 public class Range 21 { 22 27 public Range(int left, 28 int middle, 29 int right) 30 { 31 this.left = left; 32 this.middle = middle; 33 this.right = right; 34 } 35 36 37 protected final int left; 38 39 40 protected final int middle; 41 42 43 protected final int right; 44 45 48 protected void start(StringBuffer buffer) 49 { 50 buffer.append("["); 51 } 52 53 56 protected void end(StringBuffer buffer) 57 { 58 buffer.append("]"); 59 } 60 61 64 protected void normal(StringBuffer buffer, 65 int index) 66 { 67 buffer.append(index).append(","); 68 } 69 70 73 protected void lastNormal(StringBuffer buffer, 74 int index) 75 { 76 buffer.append(index); 77 } 78 79 82 protected void enhanced(StringBuffer buffer, 83 int index) 84 { 85 buffer.append("-").append(index).append("-,"); 86 } 87 88 91 protected void lastEnhanced(StringBuffer buffer, 92 int index) 93 { 94 buffer.append("-").append(index).append("-"); 95 } 96 97 100 protected void gap(StringBuffer buffer) 101 { 102 buffer.append(" ... "); 103 } 104 105 108 protected void separe(StringBuffer buffer) 109 { 110 buffer.append(", "); 111 } 112 113 116 protected final String build(int size, 117 int offset) 118 { 119 int l1 = 0; 121 int r1 = left; 122 int l2 = offset - (middle / 2); 123 int r2 = offset + ((middle + 1) / 2); 124 int l3 = size - right; 125 int r3 = size; 126 127 if (size < r1) 129 { 130 r1 = size; 131 } 132 133 if (l3 < r1) 135 { 136 l3 = r1; 137 } 138 139 if (l2 < r1) 141 { 142 l2 = r1; 143 } 144 145 if (l3 < r2) 147 { 148 r2 = l3; 149 } 150 151 StringBuffer buffer = new StringBuffer (); 152 start(buffer); 153 154 range(buffer, l1, offset, r1); 156 157 if (l2 < r2) 158 { 159 gap(buffer, r1, l2); 160 range(buffer, l2, offset, r2); 161 gap(buffer, r2, l3); 162 range(buffer, l3, offset, r3); 163 } 164 else if (l3 < r3) 165 { 166 gap(buffer, r1, l3); 167 range(buffer, l3, offset, r3); 168 } 169 170 end(buffer); 171 172 return buffer.toString(); 173 } 174 175 private void gap(StringBuffer buffer, 176 int from, 177 int to) 178 { 179 if (from < to) 180 { 181 gap(buffer); 182 } 183 else if (from == to) 184 { 185 separe(buffer); 186 } 187 } 188 189 196 private void range(StringBuffer buffer, 197 int from, 198 int offset, 199 int to) 200 { 201 boolean last = from < to--; 202 if ((from <= offset) && (offset <= to)) 203 { 204 while (from < offset) 205 { 206 normal(buffer, from++); 207 } 208 209 if (from < to) 210 { 211 enhanced(buffer, from++); 212 } 213 while (from < to) 214 { 215 normal(buffer, from++); 216 } 217 218 if (last) 219 { 220 if (offset == from) 221 { 222 lastEnhanced(buffer, from); 223 } 224 else 225 { 226 lastNormal(buffer, from); 227 } 228 } 229 } 230 else 231 { 232 while (from < to) 233 { 234 normal(buffer, from++); 235 } 236 237 if (last) 238 { 239 lastNormal(buffer, from); 240 } 241 } 242 } 243 } | Popular Tags |