@Nonnull protected MBeanAttributeInfo[] getMBeanAttributesFor() { final List<MBeanAttributeInfo> attributes = new ArrayList<>(); for (ScopeMapping mapping : _patternToMapping.values()) { for (String name : mapping.getAllNames()) { attributes.add( new MBeanAttributeInfo( name != null ? name + "." + REQUESTS_PER_SECOND_ATTRIBUTE_NAME : REQUESTS_PER_SECOND_ATTRIBUTE_NAME, Double.class.getName(), null, true, false, false)); attributes.add( new MBeanAttributeInfo( name != null ? name + "." + AVERAGE_REQUEST_DURATION_ATTRIBUTE_NAME : AVERAGE_REQUEST_DURATION_ATTRIBUTE_NAME, Double.class.getName(), null, true, false, false)); } } return attributes.toArray(new MBeanAttributeInfo[attributes.size()]); }
public List getUserListAT() { List<Map> list = new ArrayList<Map>(); String[][] data = { {"3537255778", "Alex Chen"}, {"2110989338", "Brian Wang"}, {"3537640807", "David Hsieh"}, {"5764816553", "James Yu"}, {"3756404948", "K.C."}, {"2110994764", "Neil Weinstock"}, {"6797798390", "Owen Chen"}, {"3831206627", "Randy Chen"}, {"6312460903", "Tony Shen"}, {"2110993498", "Yee Liaw"} }; for (int i = 0; i < data.length; i++) { Map map = new HashMap(); String userRef = data[i][0]; String userName = data[i][1]; map.put("userObjectId", userRef); map.put("userName", userName); list.add(map); } return list; }
@Override public List<Commit> getHistory(int page, int limit, String until) throws AmbiguousObjectException, IOException, NoHeadException, GitAPIException, SVNException { // Get the repository SVNURL svnURL = SVNURL.fromFile(new File(repoPrefix + ownerName + "/" + projectName)); org.tmatesoft.svn.core.io.SVNRepository repository = SVNRepositoryFactory.create(svnURL); // path to get log String[] paths = {"/"}; // Determine revisions long startRevision = repository.getLatestRevision() - page * limit; long endRevision = startRevision - limit; if (endRevision < 1) { endRevision = 1; } // No log to return. if (startRevision < endRevision) { return new ArrayList<>(); } // Get the logs List<Commit> result = new ArrayList<>(); for (Object entry : repository.log(paths, null, startRevision, endRevision, false, false)) { result.add(new SvnCommit((SVNLogEntry) entry)); } return result; }
public JSONObject filterPlacesRandomly( JSONObject placesJSONObject, int finalPlacesNumberPerRequest, List<String> place_ids) { JSONObject initialJSON = (JSONObject) placesJSONObject.clone(); JSONObject finalJSONObject = new JSONObject(); int numberFields = placesJSONObject.size(); int remainingPlaces = finalPlacesNumberPerRequest; int keywordsProcessed = 0; Set<String> keywords = initialJSON.keySet(); for (String keyword : keywords) { JSONArray placesForKeyword = (JSONArray) initialJSON.get(keyword); JSONArray finalPlacesForKeyword = new JSONArray(); int placesForKeywordSize = placesForKeyword.size(); int maxPlacesToKeepInFinalJSON = remainingPlaces / (numberFields - keywordsProcessed); int placesToKeepInFinalJSON = Math.min(maxPlacesToKeepInFinalJSON, placesForKeywordSize); remainingPlaces -= placesToKeepInFinalJSON; for (int i = 0; i < placesToKeepInFinalJSON; i++) { int remainingPlacesInJSONArray = placesForKeyword.size(); int randomElementPosInArray = (new Random()).nextInt(remainingPlacesInJSONArray); JSONObject temp = (JSONObject) placesForKeyword.remove(randomElementPosInArray); place_ids.add((String) temp.get("place_id")); finalPlacesForKeyword.add(temp); } finalJSONObject.put(keyword, finalPlacesForKeyword); keywordsProcessed++; } return finalJSONObject; }
public MutableHttpServletRequest() { attributeMap = new HashMap<String, Object>(); headerMap = new HashMap<String, String[]>(); parameterMap = new HashMap<String, String[]>(); fileItemMap = new HashMap<String, FileItem[]>(); locales = new ArrayList<Locale>(); locales.add(Locale.getDefault()); }
@Override public List<String> getHeaderValues(String s) { Enumeration<String> values = m_request.getHeaders(s); List<String> ret = new ArrayList<String>(); while (values.hasMoreElements()) { ret.add(values.nextElement()); } return (ret); }
@Override public List<String> getParameterValues(String s) { String[] values = m_request.getParameterValues(s); List<String> ret = new ArrayList<String>(); for (String value : values) { ret.add(value); } return (ret); }
public ControllerRequest(Class<? extends Controller> controllerClass, Matcher matchedUrl) { this.controllerClass = controllerClass; if (matchedUrl.groupCount() > 0) { List<String> argsList = new ArrayList<String>(matchedUrl.groupCount()); for (int i = 1; i <= matchedUrl.groupCount(); i++) { argsList.add(matchedUrl.group(i)); } this.args = argsList; } else { this.args = new ArrayList<String>(0); } }
public List getUserList() { List<Map> list = new ArrayList<Map>(); try { /* String apiUrl=rallyApiHost+"/user?query="+ "((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+ "(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+ "&fetch=true&order=Name&start=1&pagesize=100"; */ String apiUrl = rallyApiHost + "/user?query=(Disabled%20=%20false)" + "&fetch=true&order=Name&start=1&pagesize=100"; log.info("apiUrl=" + apiUrl); String responseXML = getRallyXML(apiUrl); org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = bSAX.build(new StringReader(responseXML)); Element root = doc.getRootElement(); XPath xpath = XPath.newInstance("//Object"); List xlist = xpath.selectNodes(root); Iterator iter = xlist.iterator(); while (iter.hasNext()) { Map map = new HashMap(); Element item = (Element) iter.next(); String userRef = item.getAttribute("ref").getValue(); String userName = item.getAttribute("refObjectName").getValue(); String userObjectId = item.getChildText("ObjectID"); map.put("userRef", userRef); map.put("userObjectId", userObjectId); map.put("userName", userName); list.add(map); } } catch (Exception ex) { log.error("", ex); } return list; }
void getDomChanges(List<DomElement> result, WApplication app) { DomElement e = DomElement.getForUpdate(this, this.getDomElementType()); if (!this.isStubbed() && this.flags_.get(BIT_GRID_CHANGED)) { DomElement newE = this.createDomElement(app); e.replaceWith(newE); } else { if (this.rowsChanged_ != null) { for (Iterator<WTableRow> i_it = this.rowsChanged_.iterator(); i_it.hasNext(); ) { WTableRow i = i_it.next(); DomElement e2 = DomElement.getForUpdate(i, DomElementType.DomElement_TR); i.updateDom(e2, false); result.add(e2); } ; this.rowsChanged_ = null; } if (this.rowsAdded_ != 0) { DomElement etb = DomElement.getForUpdate(this.getId() + "tb", DomElementType.DomElement_TBODY); for (int i = 0; i < (int) this.rowsAdded_; ++i) { DomElement tr = this.createRow(this.getRowCount() - this.rowsAdded_ + i, true, app); etb.addChild(tr); } result.add(etb); this.rowsAdded_ = 0; } if (this.flags_.get(BIT_COLUMNS_CHANGED)) { for (int i = 0; i < this.columns_.size(); ++i) { DomElement e2 = DomElement.getForUpdate(this.columns_.get(i), DomElementType.DomElement_COL); this.columns_.get(i).updateDom(e2, false); result.add(e2); } this.flags_.clear(BIT_COLUMNS_CHANGED); } this.updateDom(e, false); } result.add(e); }
/** * Procesa los llamados a listar marcas * * @param * @return * @throws IOException * @throws ServletException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BrandRepository brands = (BrandRepository) context.getBean("brandRepository"); Collection data_brands = brands.findAllBrand(); List param_brands = new ArrayList(); Iterator itr = data_brands.iterator(); while (itr.hasNext()) { Brand brand = (Brand) itr.next(); BrandDTO dto = BrandAssembler.Create(brand); param_brands.add(dto); } request.setAttribute("brands", param_brands); forward("/ListBrands.jsp", request, response); }
public static List<InetSocketAddress> readAddresses(Path path, Configuration conf) throws IOException { final List<InetSocketAddress> addrs = new ArrayList<InetSocketAddress>(); for (final String line : readConfig(path, conf)) { final StringTokenizer tokens = new StringTokenizer(line); if (tokens.hasMoreTokens()) { final String host = tokens.nextToken(); if (tokens.hasMoreTokens()) { final String port = tokens.nextToken(); addrs.add(new InetSocketAddress(host, Integer.parseInt(port))); } } } return addrs; }
/** * Gets values referenced by sequential keys, e.g. {@code key1...keyN}. * * @param keyPrefix Key prefix, e.g. {@code key} for {@code key1...keyN}. * @param params Parameters map. * @return Values. */ @Nullable protected List<Object> values(String keyPrefix, Map<String, Object> params) { assert keyPrefix != null; List<Object> vals = new LinkedList<>(); for (int i = 1; ; i++) { String key = keyPrefix + i; if (params.containsKey(key)) vals.add(params.get(key)); else break; } return vals; }
private void findCores(File dir, List<File> cores) { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { findCores(file, cores); } else { if ("core.properties".equals(file.getName())) { if (logger.isDebugEnabled()) { logger.debug("Found core:" + dir.getAbsolutePath()); } cores.add(dir); } } } }
private void expand(int row, int column, int rowSpan, int columnSpan) { int newRowCount = Math.max(this.getRowCount(), row + rowSpan); int newColumnCount = Math.max(this.getColumnCount(), column + columnSpan); int extraRows = newRowCount - this.getRowCount(); int extraColumns = newColumnCount - this.getColumnCount(); if (extraColumns > 0) { for (int a_row = 0; a_row < this.getRowCount(); ++a_row) { { int insertPos = this.grid_.items_.get(a_row).size(); for (int ii = 0; ii < (extraColumns); ++ii) this.grid_.items_.get(a_row).add(insertPos + ii, new Grid.Item()); } ; } { int insertPos = this.grid_.columns_.size(); for (int ii = 0; ii < (extraColumns); ++ii) this.grid_.columns_.add(insertPos + ii, new Grid.Section()); } ; } if (extraRows > 0) { { int insertPos = this.grid_.items_.size(); for (int ii = 0; ii < (extraRows); ++ii) this.grid_.items_.add(insertPos + ii, new ArrayList<Grid.Item>()); } ; for (int i = 0; i < extraRows; ++i) { final List<Grid.Item> items = this.grid_.items_.get(this.grid_.items_.size() - extraRows + i); { int insertPos = items.size(); for (int ii = 0; ii < (newColumnCount); ++ii) items.add(insertPos + ii, new Grid.Item()); } ; } { int insertPos = this.grid_.rows_.size(); for (int ii = 0; ii < (extraRows); ++ii) this.grid_.rows_.add(insertPos + ii, new Grid.Section()); } ; } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { GrupoRepository grupos = (GrupoRepository) context.getBean("grupoRepository"); try { Collection lista = grupos.findAllGrupo(); List data = new ArrayList(); Iterator itr = lista.iterator(); while (itr.hasNext()) { Grupo grupo = (Grupo) itr.next(); GrupoDTO dto = GrupoAssembler.CreateDTO(grupo); data.add(dto); } request.setAttribute("grupos", data); forward("/listaGrupos.jsp", request, response); } catch (Exception e) { request.setAttribute("mensaje", e.getMessage()); forward("/paginaError.jsp", request, response); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProfesorRepository profesores = (ProfesorRepository) context.getBean("profesorRepository"); try { Collection lista = profesores.findAllProfesor(); List data = new ArrayList(); Iterator itr = lista.iterator(); while (itr.hasNext()) { Profesor prof = (Profesor) itr.next(); ProfesorDTO dto = ProfesorAssembler.Create(prof); data.add(dto); } request.setAttribute("profesores", data); forward("/listaProfesores.jsp", request, response); } catch (Exception e) { request.setAttribute("mensaje", e.getMessage()); forward("/paginaError.jsp", request, response); } }
private static void addChild(UIComponent parent, String prevId, UIComponent child) { if (parent != null) { List<UIComponent> children = parent.getChildren(); int size = children.size(); boolean hasPrev = prevId == null; int i = 0; for (; i < size; i++) { UIComponent oldChild = children.get(i); if (hasPrev && oldChild.getId() != null) { children.add(i, child); return; } else if (prevId != null && prevId.equals(oldChild.getId())) hasPrev = true; } parent.getChildren().add(child); } }
public List getProjectList() { List<Map> list = new ArrayList<Map>(); try { String apiUrl = rallyApiHost + "/project?" + "fetch=true&order=Name&start=1&pagesize=200"; log.info("rallyApiUrl:" + apiUrl); String responseXML = getRallyXML(apiUrl); org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = bSAX.build(new StringReader(responseXML)); Element root = doc.getRootElement(); XPath xpath = XPath.newInstance("//Object"); List xlist = xpath.selectNodes(root); Iterator iter = xlist.iterator(); while (iter.hasNext()) { Map map = new HashMap(); Element item = (Element) iter.next(); String objId = item.getChildText("ObjectID"); String name = item.getChildText("Name"); String state = item.getChildText("State"); map.put("objId", objId); map.put("name", name); map.put("state", state); list.add(map); } } catch (Exception ex) { log.error("ERROR: ", ex); } return list; }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; javax.servlet.jsp.PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/xml;charset=ISO-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n"); out.write("\n"); HttpSession user = request.getSession(true); Notification newNotice = (Notification) user.getAttribute("newNotice"); List exclude = new ArrayList(); exclude.add(NotificationWizardServlet.WT_VENDOR_NAME); // Exclude WebTelemetry out.print(buildTree(newNotice, exclude)); out.write("\n"); } catch (Throwable t) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (pageContext != null) pageContext.handlePageException(t); } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext); } }
static void decodeTouches(String str, List<Touch> result) { if (str.length() == 0) { return; } List<String> s = new ArrayList<String>(); s = new ArrayList<String>(Arrays.asList(str.split(";"))); if (s.size() % 9 != 0) { logger.error( new StringWriter() .append("Could not parse touches array '") .append(str) .append("'") .toString()); return; } try { for (int i = 0; i < s.size(); i += 9) { result.add( new Touch( asUInt(s.get(i + 0)), asInt(s.get(i + 1)), asInt(s.get(i + 2)), asInt(s.get(i + 3)), asInt(s.get(i + 4)), asInt(s.get(i + 5)), asInt(s.get(i + 6)), asInt(s.get(i + 7)), asInt(s.get(i + 8)))); } } catch (NumberFormatException ee) { logger.error( new StringWriter() .append("Could not parse touches array '") .append(str) .append("'") .toString()); return; } }
/** * Creates a GPX-formatted file attachment for the given entry. * * @param user * @param entryId * @param fileName * @param activityId * @param track * @param track */ public void createAttachment( User user, int entryId, String fileName, String title, String activityId, GpsTrack track) throws DataAccessException, IOException { Attachment a = new Attachment(); a.setUserName(user.getUserName()); a.setUserId(user.getUserId()); a.setEntryId(entryId); a.setFileType("map"); a.setFileName(fileName); a.setActivityId(activityId); a.setTitle(title); GpxFormatter formatter = new GpxFormatter(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); List<GpsTrack> tracks = new ArrayList<GpsTrack>(); tracks.add(track); formatter.format(tracks, baos); log.debug(new String(baos.toByteArray())); a.setBytes(baos.toByteArray()); new AttachmentDao().create(a); }
/** * Move a table column from its original position to a new position. * * <p>The table expands automatically when the <code>to</code> column is beyond the current table * dimensions. * * <p> * * @see WTable#moveRow(int from, int to) */ public void moveColumn(int from, int to) { if (from < 0 || from >= (int) this.columns_.size()) { logger.error( new StringWriter() .append("moveColumn: the from index is not a valid column index.") .toString()); return; } WTableColumn from_tc = this.getColumnAt(from); this.columns_.remove(from_tc); if (to > (int) this.columns_.size()) { this.getColumnAt(to); } this.columns_.add(0 + to, from_tc); for (int i = 0; i < this.rows_.size(); i++) { List<WTableRow.TableData> cells = this.rows_.get(i).cells_; WTableRow.TableData cell = cells.get(from); cells.remove(0 + from); cells.add(0 + to, cell); } this.flags_.set(BIT_GRID_CHANGED); this.repaint(EnumSet.of(RepaintFlag.RepaintInnerHtml)); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get the number of workers to run int count = this.getRequestedCount(request, 4); // get the executor service final ServletContext sc = this.getServletContext(); final ExecutorService executorService = (ExecutorService) sc.getAttribute("myExecutorService"); // create work coordinator CountDownLatch countDownLatch = new CountDownLatch(count); Long t1 = System.nanoTime(); // create the workers List<RunnableWorkUnit2> workers = new ArrayList<RunnableWorkUnit2>(); for (int i = 0; i < count; i++) { RunnableWorkUnit2 wu = new RunnableWorkUnit2("RunnableTask" + String.valueOf(i + 1), countDownLatch); workers.add(wu); } // run the workers through the executor for (RunnableWorkUnit2 wu : workers) { executorService.execute(wu); } try { System.out.println("START WAITING"); countDownLatch.await(); System.out.println("DONE WAITING"); } catch (InterruptedException ex) { ex.printStackTrace(); } Long t2 = System.nanoTime(); Writer w = response.getWriter(); w.write(String.format("\n Request processed in %dms!", (t2 - t1) / 1000000)); w.flush(); w.close(); }
void getDomChanges(List<DomElement> result, WApplication app) { if (this.mediaId_.length() != 0) { DomElement media = DomElement.getForUpdate(this.mediaId_, DomElementType.DomElement_DIV); this.updateMediaDom(media, false); if (this.sourcesChanged_) { for (int i = 0; i < this.sourcesRendered_; ++i) { media.callJavaScript( "Wt3_2_3.remove('" + this.mediaId_ + "s" + String.valueOf(i) + "');", true); } this.sourcesRendered_ = 0; for (int i = 0; i < this.sources_.size(); ++i) { DomElement src = DomElement.createNew(DomElementType.DomElement_SOURCE); src.setId(this.mediaId_ + "s" + String.valueOf(i)); this.renderSource(src, this.sources_.get(i), i + 1 >= this.sources_.size()); media.addChild(src); } this.sourcesRendered_ = this.sources_.size(); this.sourcesChanged_ = false; media.callJavaScript(this.getJsMediaRef() + ".load();"); } result.add(media); } super.getDomChanges(result, app); }
private List<LicenseData> getSearchByFieldResults( String reseller, String parameter, String type) { List<LicenseData> list = new ArrayList<LicenseData>(); Connection con = null; try { Statement pst = null; con = getConnectiontoDB(); StringBuffer sql = new StringBuffer(); if (type.equalsIgnoreCase("sno")) { sql.append( " select distinct ib.item,o.orderkey,'1',so_header.so_number,so_header.end_user,TO_CHAR(TO_TIMESTAMP(so_header.ship_date/1000), 'YYYY-MM-DD'), "); } else { sql.append( " select distinct so_item.item,so_item.entitlementkey,so_item.quantity,so_header.so_number,so_header.end_user,TO_CHAR(TO_TIMESTAMP(so_header.ship_date/1000), 'YYYY-MM-DD'), "); } sql.append( "o.hmid, CASE TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') WHEN '1969-12-31' THEN '' WHEN TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') THEN '' ELSE TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') END, "); sql.append( "CASE TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') WHEN '1969-12-31' THEN '' WHEN TO_CHAR(TO_TIMESTAMP(o.substartdate/1000), 'YYYY-MM-DD') THEN '' ELSE TO_CHAR(TO_TIMESTAMP(o.subenddate/1000), 'YYYY-MM-DD') END, so_header.po_check_number,so_header.reseller, "); sql.append( " CASE WHEN so_item.producttype='Support' THEN TO_CHAR(TO_TIMESTAMP(o.startdate/1000), 'YYYY-MM-DD') ELSE '' END, "); sql.append( " CASE WHEN so_item.producttype='Support' THEN TO_CHAR(TO_TIMESTAMP(o.enddate/1000), 'YYYY-MM-DD') ELSE '' END "); if (type.equalsIgnoreCase("sno")) { sql.append(" ,ib.serialnumber"); sql.append( " from ns.so_header so_header inner join ns.ib ib on ib.salesordernumber =so_header.so_number "); sql.append(" inner join orderkey_information o on so_header.entitlement_key=o.orderkey"); sql.append( " inner join ns.temp_so_item so_item on so_header.entitlement_key=so_item.entitlementkey"); } else { sql.append( " from ns.so_header so_header inner join ns.temp_so_item so_item on so_header.entitlement_key=so_item.entitlementkey "); sql.append(" inner join orderkey_information o on so_header.entitlement_key=o.orderkey "); } if (type.equalsIgnoreCase("sno")) sql.append(" where ib.serialnumber ILIKE '%" + parameter.trim() + "%' "); if (type.equalsIgnoreCase("so")) sql.append("where so_header.so_number='" + parameter.trim() + "' "); if (type.equalsIgnoreCase("enduser")) sql.append( "where so_header.end_user ILIKE '%" + parameter.trim().replace("'", "''") + "%'"); if (type.equalsIgnoreCase("ek")) sql.append("where so_header.entitlement_key ILIKE '%" + parameter.trim() + "%'"); if (type.equalsIgnoreCase("po")) sql.append("where so_header.po_check_number ILIKE '%" + parameter.trim() + "%'"); if (type.equalsIgnoreCase("hm")) sql.append("where o.hmid ILIKE '%" + parameter.trim() + "%'"); if (reseller != null && !reseller.isEmpty() && !reseller.equalsIgnoreCase("%admin%")) sql.append(" and so_header.reseller ILIKE '" + reseller.trim() + "'"); if (type.equalsIgnoreCase("sno")) sql.append(" order by so_header.so_number desc "); pst = con.createStatement(); ResultSet rs = pst.executeQuery(sql.toString()); log.info("Search Fields : SQL Query " + sql); while (rs.next()) { LicenseData data = new LicenseData(); data.setEntitlementKey(rs.getString(2)); data.setSku(rs.getString(1)); data.setQuantity(rs.getString(3)); data.setSoNumbber(rs.getString(4)); ; data.setEndUser(rs.getString(5)); data.setShipDate(rs.getString(6)); data.setHmId(rs.getString(7)); data.setLicenseStartDate(rs.getString(8)); data.setLicenseEndDate(rs.getString(9)); data.setPoNumber(rs.getString(10)); data.setNumber(rs.getString(4)); data.setBillingCustomer(rs.getString(11)); data.setSupportStartDate(rs.getString(12)); data.setSupportEndDate(rs.getString(13)); if (type.equalsIgnoreCase("sno")) data.setSerialNumber(rs.getString(14)); list.add(data); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; }
/** * Search for pages matching a query, eliminating excessive hits with matching values for a named * field. Hits after the first <code>maxHitsPerDup</code> are removed from results. The remaining * hits have {@link Hit#moreFromDupExcluded()} set. * * <p>If maxHitsPerDup is zero then all hits are returned. * * @param query query * @param numHits number of requested hits * @param maxHitsPerDup the maximum hits returned with matching values, or zero * @param dedupField field name to check for duplicates * @param sortField Field to sort on (or null if no sorting). * @param reverse True if we are to reverse sort by <code>sortField</code>. * @return Hits the matching hits * @throws IOException */ public Hits search( Query query, int numHits, int maxHitsPerDup, String dedupField, String sortField, boolean reverse) throws IOException { if (maxHitsPerDup <= 0) // disable dup checking return search(query, numHits, dedupField, sortField, reverse); final float rawHitsFactor = this.conf.getFloat("searcher.hostgrouping.rawhits.factor", 2.0f); int numHitsRaw = (int) (numHits * rawHitsFactor); if (LOG.isInfoEnabled()) { LOG.info("searching for " + numHitsRaw + " raw hits"); } Hits hits = searchBean.search(query, numHitsRaw, dedupField, sortField, reverse); final long total = hits.getTotal(); final Map<String, DupHits> dupToHits = new HashMap<String, DupHits>(); final List<Hit> resultList = new ArrayList<Hit>(); final Set<Hit> seen = new HashSet<Hit>(); final List<String> excludedValues = new ArrayList<String>(); boolean totalIsExact = true; for (int rawHitNum = 0; rawHitNum < hits.getTotal(); rawHitNum++) { // get the next raw hit if (rawHitNum >= hits.getLength()) { // optimize query by prohibiting more matches on some excluded values final Query optQuery = (Query) query.clone(); for (int i = 0; i < excludedValues.size(); i++) { if (i == MAX_PROHIBITED_TERMS) break; optQuery.addProhibitedTerm(excludedValues.get(i), dedupField); } numHitsRaw = (int) (numHitsRaw * rawHitsFactor); if (LOG.isInfoEnabled()) { LOG.info("re-searching for " + numHitsRaw + " raw hits, query: " + optQuery); } hits = searchBean.search(optQuery, numHitsRaw, dedupField, sortField, reverse); if (LOG.isInfoEnabled()) { LOG.info("found " + hits.getTotal() + " raw hits"); } rawHitNum = -1; continue; } final Hit hit = hits.getHit(rawHitNum); if (seen.contains(hit)) continue; seen.add(hit); // get dup hits for its value final String value = hit.getDedupValue(); DupHits dupHits = dupToHits.get(value); if (dupHits == null) dupToHits.put(value, dupHits = new DupHits()); // does this hit exceed maxHitsPerDup? if (dupHits.size() == maxHitsPerDup) { // yes -- ignore the hit if (!dupHits.maxSizeExceeded) { // mark prior hits with moreFromDupExcluded for (int i = 0; i < dupHits.size(); i++) { dupHits.get(i).setMoreFromDupExcluded(true); } dupHits.maxSizeExceeded = true; excludedValues.add(value); // exclude dup } totalIsExact = false; } else { // no -- collect the hit resultList.add(hit); dupHits.add(hit); // are we done? // we need to find one more than asked for, so that we can tell if // there are more hits to be shown if (resultList.size() > numHits) break; } } final Hits results = new Hits(total, resultList.toArray(new Hit[resultList.size()])); results.setTotalIsExact(totalIsExact); return results; }
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.getWriter().println("<html><body>"); String keyname = req.getParameter("keyname"); String value = req.getParameter("value"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); // Using the synchronous cache. MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); // display every element of kind TaskData for /datastore if (req.getParameterMap().isEmpty()) { // querying from datastore resp.getWriter().println("<h3>Datastore results:</h3>"); List<String> listOfKeys = new ArrayList<String>(); Query q = new Query("TaskData"); PreparedQuery pq = datastore.prepare(q); for (Entity result : pq.asIterable()) { String datastore_key = result.getKey().getName(); String taskData_value = (String) result.getProperty("value"); Date taskData_date = (Date) result.getProperty("date"); resp.getWriter() .println( "<p>keyname = " + datastore_key + " value = " + taskData_value + " date = " + taskData_date.toString() + "</p>"); listOfKeys.add(datastore_key); } // check which of the keys exist in memcache String memcache_value; resp.getWriter().println("<h3>Memcache results:</h3>"); for (String datastore_key : listOfKeys) { memcache_value = (String) syncCache.get(datastore_key); if (memcache_value != null) { // String decoded = new String(memcache_value, "UTF-8"); resp.getWriter() .println("<p>keyname = " + datastore_key + " value = " + memcache_value + "</p>"); } } } // display element of kind TaskData with key=keyname else if (keyname != null && value == null) { // first check in the cache String memcache_value = (String) syncCache.get(keyname); // Read from cache. // Get value from datastore Key task_key = KeyFactory.createKey("TaskData", keyname); try { Entity tne = datastore.get(task_key); if (memcache_value == null) { resp.getWriter().println("<h2>Datastore</h2>"); } else { resp.getWriter().println("<h2>Both</h2>"); } } catch (EntityNotFoundException e) { resp.getWriter().println("<h2>Neither</h2>"); } } // store element of kind TaskData with key=keyname and value=value else if (keyname != null && value != null) { Entity tne = new Entity("TaskData", keyname); tne.setProperty("value", value); tne.setProperty("date", new Date()); datastore.put(tne); syncCache.put(keyname, value); // Populate cache. resp.getWriter() .println("<h2>Stored " + keyname + " and " + value + " in Datastore and Memcache</h2>"); } else { resp.getWriter().println("<h2>You entered wrong query parameters</h2>"); } /* Entity tne = new Entity("TaskData", "Person"); alice.setProperty("gender", "female"); alice.setProperty("age", 20); */ resp.getWriter().println("</body></html>"); }
// public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) { public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) { List<Map> list = new ArrayList<Map>(); statusMap.put(sessionId, "0"); try { String apiURL = rallyApiHost + "/hierarchicalrequirement?" + "query=(Iteration%20=%20" + rallyApiHost + "/iteration/" + iterationId + ")&fetch=true&start=1&pagesize=100"; log.info("getUserStoryList apiURL=" + apiURL); String responseXML = getRallyXML(apiURL); org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = bSAX.build(new StringReader(responseXML)); Element root = doc.getRootElement(); XPath xpath = XPath.newInstance("//Object"); List xlist = xpath.selectNodes(root); int totalSteps = xlist.size() + 1; int currentStep = 0; List taskRefLink = new ArrayList(); Iterator iter = xlist.iterator(); while (iter.hasNext()) { double totalTimeSpent = 0.0D; Map map = new HashMap(); Element item = (Element) iter.next(); String objId = item.getChildText("ObjectID"); String name = item.getChildText("Name"); String planEstimate = item.getChildText("PlanEstimate"); String formattedId = item.getChildText("FormattedID"); String taskActualTotal = item.getChildText("TaskActualTotal"); String taskEstimateTotal = item.getChildText("TaskEstimateTotal"); String taskRemainingTotal = item.getChildText("TaskRemainingTotal"); String scheduleState = item.getChildText("ScheduleState"); Element ownerElement = item.getChild("Owner"); String owner = ""; String ownerRef = ""; if (ownerElement != null) { owner = ownerElement.getAttributeValue("refObjectName"); } Element taskElements = item.getChild("Tasks"); // List taskElementList=taskElements.getContent(); List taskElementList = taskElements.getChildren(); List taskList = new ArrayList(); log.info("taskElements.getChildren=" + taskElements); log.info("taskList=" + taskElementList); for (int i = 0; i < taskElementList.size(); i++) { Element taskElement = (Element) taskElementList.get(i); String taskRef = taskElement.getAttributeValue("ref"); String[] objectIdArr = taskRef.split("/"); String objectId = objectIdArr[objectIdArr.length - 1]; log.info("objectId=" + objectId); // Map taskMap=getTaskMap(taskRef); Map taskMap = getTaskMapBatch(objectId); double taskTimeSpentTotal = Double.parseDouble((String) taskMap.get("taskTimeSpentTotal")); totalTimeSpent += taskTimeSpentTotal; taskList.add(taskMap); } map.put("type", "userstory"); map.put("formattedId", formattedId); map.put("name", name); map.put("taskStatus", scheduleState); map.put("owner", owner); map.put("planEstimate", planEstimate); map.put("taskEstimateTotal", taskEstimateTotal); map.put("taskRemainingTotal", taskRemainingTotal); map.put("taskTimeSpentTotal", "" + totalTimeSpent); list.add(map); list.addAll(taskList); ++currentStep; double percentage = 100.0D * currentStep / totalSteps; String status = "" + Math.round(percentage); statusMap.put(sessionId, status); out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status); out.flush(); log.info("out.flush..." + status); // log.info("status="+status+" sessionId="+sessionId); // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode()); } double planEstimate = 0.0D; double taskEstimateTotal = 0.0D; double taskRemainingTotal = 0.0D; double taskTimeSpentTotal = 0.0D; Map iterationMap = new HashMap(); for (Map map : list) { String type = (String) map.get("type"); String planEstimateStr = (String) map.get("planEstimate"); log.info("planEstimateStr=" + planEstimateStr); if ("userstory".equals(type)) { if (planEstimateStr != null) { planEstimate += Double.parseDouble(planEstimateStr); } taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal")); taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal")); taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal")); } } apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true"; log.info("iteration apiURL=" + apiURL); responseXML = getRallyXML(apiURL); bSAX = new org.jdom.input.SAXBuilder(); doc = bSAX.build(new StringReader(responseXML)); root = doc.getRootElement(); xpath = XPath.newInstance("//Iteration"); xlist = xpath.selectNodes(root); String projName = ""; String iterName = ""; String iterState = ""; iter = xlist.iterator(); while (iter.hasNext()) { Element item = (Element) iter.next(); iterName = item.getChildText("Name"); iterState = item.getChildText("State"); Element projElement = item.getChild("Project"); projName = projElement.getAttributeValue("refObjectName"); } iterationMap.put("type", "iteration"); iterationMap.put("formattedId", ""); iterationMap.put("name", projName + " - " + iterName); iterationMap.put("taskStatus", iterState); iterationMap.put("owner", ""); iterationMap.put("planEstimate", "" + planEstimate); iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal); iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal); iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal); list.add(0, iterationMap); statusMap.put(sessionId, "100"); log.info("L2 statusMap=" + statusMap); log.info("L2 verify=" + getProcessStatus(sessionId)); log.info("-----------"); // String jsonData=JsonUtil.encodeObj(list); String jsonData = JSONValue.toJSONString(list); out.println("<script>parent.tableResult=" + jsonData + "</script>"); out.println("<script>parent.showTableResult()</script>"); } catch (Exception ex) { log.error("ERROR: ", ex); } return list; }
public List getIterationList(String projectId) { List<Map> list = new ArrayList<Map>(); try { String apiUrl = rallyApiHost + "/iteration?" + "project=" + rallyApiHost + "/project/" + projectId + "&fetch=true&order=Name%20desc&start=1&pagesize=100"; String checkProjectRef = rallyApiHost + "/project/" + projectId; log.info("rallyApiUrl:" + apiUrl); log.info("checkProjectRef:" + checkProjectRef); String responseXML = getRallyXML(apiUrl); SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date currentDate = new Date(); org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = bSAX.build(new StringReader(responseXML)); Element root = doc.getRootElement(); XPath xpath = XPath.newInstance("//Object"); List xlist = xpath.selectNodes(root); Iterator iter = xlist.iterator(); while (iter.hasNext()) { Map map = new HashMap(); Element item = (Element) iter.next(); String objId = item.getChildText("ObjectID"); String name = item.getChildText("Name"); String state = item.getChildText("State"); String startDateStr = item.getChildText("StartDate"); String endDateStr = item.getChildText("EndDate"); Date startDate = ISO8601FORMAT.parse(startDateStr); Date endDate = ISO8601FORMAT.parse(endDateStr); boolean isCurrent = false; int startCheck = startDate.compareTo(currentDate); int endCheck = endDate.compareTo(currentDate); if (startCheck < 0 && endCheck > 0) { isCurrent = true; } log.info("name=" + name + " isCurrent=" + isCurrent); String releaseRef = item.getAttribute("ref").getValue(); // In child project, parent object have to be filiered Element projectElement = item.getChild("Project"); String projectRef = projectElement.getAttributeValue("ref"); if (projectRef.equals(checkProjectRef)) { map.put("objId", objId); map.put("rallyRef", releaseRef); map.put("name", name); map.put("state", state); map.put("isCurrent", "" + isCurrent); list.add(map); } } log.info("-----------"); } catch (Exception ex) { log.error("ERROR: ", ex); } return list; }