List of usage examples for org.apache.commons.collections.iterators LoopingIterator LoopingIterator
public LoopingIterator(Collection coll)
From source file:com.pureinfo.tgirls.servlet.GetPicArrServlet.java
@Override protected void doGet(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException { String type = _req.getParameter("pictype"); String s = _req.getParameter("size"); String sstartIndex = _req.getParameter("startIndex"); if (StringUtils.isEmpty(s)) { s = "50"; }//from w w w.j a v a2s . co m if (StringUtils.isEmpty(sstartIndex)) { sstartIndex = "0"; } int startIndex = Integer.parseInt(sstartIndex); int resultsize = Integer.parseInt(s); logger.debug("to get pics with type:" + type + " and size:" + resultsize); _resp.setContentType("text/json; charset=utf-8"); JsonBase json = new JsonBase(); //List<Photo> result = new ArrayList<Photo>(); List<Photo> cacheList = null; if ((cacheList = (List<Photo>) cache.get("pics." + type)) == null) { try { startIndex = 0; IPhotoMgr mgr = (IPhotoMgr) ArkContentHelper.getContentMgrOf(Photo.class); if (StringUtils.isEmpty(type)) { cacheList = mgr.getRandomPics(500); } else { cacheList = mgr.getRandomPics(Integer.parseInt(type), 500); } if (cacheList != null) { cache.put("pics." + type, cacheList); } } catch (PureException e) { logger.error("error when get pics.", e); } } if (cacheList == null || cacheList.isEmpty()) { json.setErrorCode(ErrorCode.ERROR.getCode()); json.setErrorMsg(""); _resp.getWriter().write(json.toString()); return; } //Collections.shuffle(cacheList); //result.addAll(cacheList); //if (resultsize < result.size()) { // result.subList(0, resultsize); //} try { Photo photo; List<JSONObject> jsonList = new ArrayList<JSONObject>(); int temp = 0; int i = 0; if (startIndex == 0) { startIndex = new Random().nextInt(cacheList.size()); } Iterator<Photo> itor = new LoopingIterator(cacheList); while (itor.hasNext() && i < resultsize) { photo = itor.next(); if (temp < startIndex) { logger.debug("currentIndex[" + temp + "] and startIndex[" + startIndex + "]"); temp++; continue; } logger.debug("to add photo[" + photo + "]"); jsonList.add(new JSONObject(photo)); i++; } Collections.shuffle(jsonList); json.put("pics", jsonList); json.put("nextIndex", startIndex + resultsize); } catch (JSONException e) { throw new RuntimeException(); } // logger.debug("result:" + json.toString()); _resp.getWriter().write(json.toString()); return; }