List of usage examples for java.util Vector size
public synchronized int size()
From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java
/** * Generate a pie graph representing average test counts for each type of test for * all builds in the list. /*from www . ja va2s.c o m*/ * * @param builds List of builds * * @return Pie graph representing build execution times across all builds */ public static final JFreeChart getAverageTestCountChart(Vector<CMnDbBuildData> builds) { JFreeChart chart = null; // Collect the average of all test types Hashtable countAvg = new Hashtable(); DefaultPieDataset dataset = new DefaultPieDataset(); if ((builds != null) && (builds.size() > 0)) { // Collect build metrics for each of the builds in the list Enumeration buildList = builds.elements(); while (buildList.hasMoreElements()) { // Process the build metrics for the current build CMnDbBuildData build = (CMnDbBuildData) buildList.nextElement(); Hashtable testSummary = build.getTestSummary(); if ((testSummary != null) && (testSummary.size() > 0)) { Enumeration keys = testSummary.keys(); while (keys.hasMoreElements()) { String testType = (String) keys.nextElement(); CMnDbTestSummaryData tests = (CMnDbTestSummaryData) testSummary.get(testType); Integer avgValue = null; if (countAvg.containsKey(testType)) { Integer oldAvg = (Integer) countAvg.get(testType); avgValue = oldAvg + tests.getTotalCount(); } else { avgValue = tests.getTotalCount(); } countAvg.put(testType, avgValue); } } } // while list has elements // Populate the data set with the average values for each metric Enumeration keys = countAvg.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); Integer total = (Integer) countAvg.get(key); Integer avg = new Integer(total.intValue() / builds.size()); dataset.setValue(key, avg); } } // if list has elements // API: ChartFactory.createPieChart(title, data, legend, tooltips, urls) chart = ChartFactory.createPieChart("Avg Test Count by Type", dataset, true, true, false); // get a reference to the plot for further customization... PiePlot plot = (PiePlot) chart.getPlot(); chartFormatter.formatTypeChart(plot, "tests"); return chart; }
From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java
/** * Makes a JSON object and sends it to response with information needed for * building the OAuth2 login form.// www. jav a 2s . c o m * * @param request * @param response * @throws ElementNotFoundException */ private static void makeForm(HttpServletRequest request, HttpServletResponse response) throws ElementNotFoundException { JSONResponse jsonResponse = new JSONResponse(request); JSONObject form = new JSONObject(); try { JSONArray providers = new JSONArray(); form.put("providers", providers); Vector<String> providernames = OAuthConfigurator.getProviders(); for (int j = 0; j < providernames.size(); j++) { OAuthConfigurator.Oauth2Settings settings = OAuthConfigurator .getOAuthSettings(providernames.get(j)); JSONObject provider = new JSONObject(); provider.put("id", providernames.get(j)); provider.put("description", settings.description); provider.put("logo", settings.logo); provider.put("registerlink", settings.registerlink); providers.put(provider); } } catch (JSONException e) { } jsonResponse.setMessage(form); try { jsonResponse.print(response); } catch (Exception e1) { } }
From source file:edu.umn.cs.spatialHadoop.nasa.SpatioAggregateQueries.java
/** * Return all matching partitions according to a time range * @param inFile // w ww.ja v a 2 s . co m * @param params * @return * @throws ParseException * @throws IOException */ private static Vector<Path> selectTemporalPartitions(Path inFile, OperationsParams params) throws ParseException, IOException { // 1- Run a temporal filter step to find all matching temporal partitions Vector<Path> matchingPartitions = new Vector<Path>(); // List of time ranges to check. Initially it contains one range as // specified by the user. Eventually, it can be split into at most two // partitions if partially matched by a partition. Vector<TimeRange> temporalRanges = new Vector<TimeRange>(); System.out.println(new TimeRange(params.get("time"))); temporalRanges.add(new TimeRange(params.get("time"))); Path[] temporalIndexes = new Path[] { new Path(inFile, "yearly"), new Path(inFile, "monthly"), new Path(inFile, "daily") }; int index = 0; final FileSystem fs = inFile.getFileSystem(params); while (index < temporalIndexes.length && !temporalRanges.isEmpty()) { Path indexDir = temporalIndexes[index]; LOG.info("Checking index dir " + indexDir); TemporalIndex temporalIndex = new TemporalIndex(fs, indexDir); for (int iRange = 0; iRange < temporalRanges.size(); iRange++) { TimeRange range = temporalRanges.get(iRange); TemporalPartition[] matches = temporalIndex.selectContained(range.start, range.end); if (matches != null) { LOG.info("Matched " + matches.length + " partitions in " + indexDir); for (TemporalPartition match : matches) { matchingPartitions.add(new Path(indexDir, match.dirName)); } // Update range to remove matching part TemporalPartition firstMatch = matches[0]; TemporalPartition lastMatch = matches[matches.length - 1]; if (range.start < firstMatch.start && range.end > lastMatch.end) { // Need to split the range into two temporalRanges.setElementAt(new TimeRange(range.start, firstMatch.start), iRange); temporalRanges.insertElementAt(new TimeRange(lastMatch.end, range.end), iRange); } else if (range.start < firstMatch.start) { // Update range in-place range.end = firstMatch.start; } else if (range.end > lastMatch.end) { // Update range in-place range.start = lastMatch.end; } else { // Current range was completely covered. Remove it temporalRanges.remove(iRange); } } } index++; } numOfTemporalPartitionsInLastQuery = matchingPartitions.size(); return matchingPartitions; }
From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java
/** * Generate a stacked bar graph representing build execution times across * all builds in the list. //from w w w. j a v a2s . com * * @param builds List of builds * * @return Stacked graph representing build execution times across all builds */ public static final JFreeChart getMetricChart(Vector<CMnDbBuildData> builds) { JFreeChart chart = null; // Get a list of all possible build metrics int[] metricTypes = CMnDbMetricData.getAllTypes(); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); if ((builds != null) && (builds.size() > 0)) { // Collect build metrics for each of the builds in the list Collections.sort(builds, new CMnBuildIdComparator()); Enumeration buildList = builds.elements(); while (buildList.hasMoreElements()) { // Process the build metrics for the current build CMnDbBuildData build = (CMnDbBuildData) buildList.nextElement(); Vector metrics = build.getMetrics(); if ((metrics != null) && (metrics.size() > 0)) { // Sort the list of metrics to ensure they are displayed on the chart in a sensible order Collections.sort(metrics, new CMnMetricDateComparator()); // Collect data for each of the build metrics in the current build Enumeration metricList = metrics.elements(); while (metricList.hasMoreElements()) { CMnDbMetricData currentMetric = (CMnDbMetricData) metricList.nextElement(); // Get elapsed time in "minutes" Long elapsedTime = new Long(currentMetric.getElapsedTime() / (1000 * 60)); Integer buildId = new Integer(build.getId()); String metricName = CMnDbMetricData.getMetricType(currentMetric.getType()); dataset.addValue(elapsedTime, metricName, buildId); } // while build has metrics } // if has metrics } // while list has elements } // if list has elements // API: ChartFactory.createStackedBarChart(title, domainAxisLabel, rangeAxisLabel, dataset, orientation, legend, tooltips, urls) chart = ChartFactory.createStackedBarChart("Build Metrics", "Builds", "Execution Time (min)", dataset, PlotOrientation.VERTICAL, true, true, false); // get a reference to the plot for further customization... CategoryPlot plot = (CategoryPlot) chart.getPlot(); chartFormatter.formatMetricChart(plot, dataset); return chart; }
From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java
/** * Returns unique user identifier from id_token (JWTPayload). The JWT token * is *NOT* verified. Several impact portal session attributes are set: - * user_identifier - emailaddress/*from w w w . j a v a 2s .c o m*/ * * @param request * @param JWT * @return * @throws ElementNotFoundException */ private static UserInfo getIdentifierFromJWTPayload(String JWT) throws ElementNotFoundException { JSONObject id_token_json = null; try { id_token_json = (JSONObject) new JSONTokener(JWT).nextValue(); } catch (JSONException e1) { Debug.errprintln("Unable to convert JWT Token to JSON"); return null; } String email = "null"; String userSubject = null; String aud = ""; try { email = id_token_json.get("email").toString(); } catch (JSONException e) { } try { userSubject = id_token_json.get("sub").toString(); } catch (JSONException e) { } try { aud = id_token_json.get("aud").toString(); } catch (JSONException e) { } if (aud == null) { Debug.errprintln("Error: aud == null"); return null; } if (userSubject == null) { Debug.errprintln("Error: userSubject == null"); return null; } // Get ID based on aud (client id) String clientId = null; Vector<String> providernames = OAuthConfigurator.getProviders(); for (int j = 0; j < providernames.size(); j++) { OAuthConfigurator.Oauth2Settings settings = OAuthConfigurator.getOAuthSettings(providernames.get(j)); if (settings.OAuthClientId.equals(aud)) { clientId = settings.id; } } if (clientId == null) { Debug.errprintln("Error: could not match OAuthClientId to aud"); return null; } String user_identifier = clientId + "/" + userSubject; String user_openid = null; UserInfo userInfo = new UserInfo(); userInfo.user_identifier = user_identifier; userInfo.user_openid = user_openid; userInfo.user_email = email; Debug.println("getIdentifierFromJWTPayload (id_token): Found unique ID " + user_identifier); return userInfo; }
From source file:edu.ku.brc.specify.dbsupport.cleanuptools.LocalityCleanup.java
/** * //from ww w . j av a2 s . co m */ public static void fixTaxa() { String connectStr = "jdbc:mysql://localhost/"; String dbName = "kevin"; DBConnection dbc = new DBConnection("root", "root", connectStr + dbName, "com.mysql.jdbc.Driver", "org.hibernate.dialect.MySQLDialect", dbName); Connection conn = dbc.createConnection(); BasicSQLUtils.setDBConnection(conn); try { // Fix Catalog Numbers String sql = "SELECT COUNT(*) FROM collectionobject WHERE CatalogNumber LIKE 'NHRS-COLE %'"; System.out.println("CatNum to be fixed: " + BasicSQLUtils.getCountAsInt(sql)); PreparedStatement pTxStmt = conn .prepareStatement("UPDATE collectionobject SET CatalogNumber=? WHERE CollectionObjectID = ?"); sql = "SELECT CatalogNumber, CollectionObjectID FROM collectionobject WHERE CatalogNumber LIKE 'NHRS-COLE %'"; for (Object[] cols : BasicSQLUtils.query(sql)) { String catNum = cols[0].toString(); catNum = StringUtils.replace(catNum, "COLE ", "COLE"); pTxStmt.setString(1, catNum); pTxStmt.setInt(2, (Integer) cols[1]); if (pTxStmt.executeUpdate() != 1) { System.out.println("Error deleting ColObjID: " + cols[1]); } else { System.out.println("Fixed ColObjID: " + cols[1]); } } pTxStmt.close(); sql = "SELECT COUNT(*) FROM collectionobject WHERE CatalogNumber LIKE 'NHRS-COLE %'"; System.out.println("CatNum not fixed: " + BasicSQLUtils.getCountAsInt(sql)); // Fix Taxon - Start by finding all the duplicate Taxon Records sql = "SELECT Name FROM (SELECT Name, COUNT(Name) as cnt, TaxonID FROM taxon GROUP BY Name) T1 WHERE cnt > 1 AND TaxonID > 15156 ORDER BY cnt desc"; Statement stmt = conn.createStatement(); PreparedStatement pStmt = conn .prepareStatement("UPDATE determination SET TaxonID=? WHERE DeterminationID = ?"); PreparedStatement pStmt2 = conn .prepareStatement("UPDATE determination SET PreferredTaxonID=? WHERE DeterminationID = ?"); PreparedStatement pStmt3 = conn.prepareStatement("UPDATE taxon SET AcceptedID=? WHERE TaxonID = ?"); PreparedStatement delStmt = conn.prepareStatement("DELETE FROM taxon WHERE TaxonID=?"); int fixedCnt = 0; for (Object[] cols : BasicSQLUtils.query(sql)) { String name = cols[0].toString(); sql = String.format("SELECT COUNT(*) FROM taxon WHERE Name = '%s' ORDER BY TaxonID ASC", name); System.out.println("------------------------------------" + name + " - " + BasicSQLUtils.getCountAsInt(sql) + "-----------------------------------"); // Find all duplicate Taxon Objects sql = String.format("SELECT TaxonID FROM taxon WHERE Name = '%s' ORDER BY TaxonID ASC", name); int c = 0; Integer firstID = null; ResultSet rs2 = stmt.executeQuery(sql); while (rs2.next()) { int id = rs2.getInt(1); if (c == 0) // Skip the first one which will the original { firstID = id; c = 1; continue; } // Find all the determinations sql = String.format("SELECT DeterminationId FROM determination WHERE TaxonID = %d", id); System.out.println(sql); Vector<Integer> ids = BasicSQLUtils.queryForInts(conn, sql); System.out.println("Fixing " + ids.size() + " determinations with TaxonID: " + id + " Setting to orig TaxonID: " + firstID); for (Integer detId : ids) { pStmt.setInt(1, firstID); pStmt.setInt(2, detId); if (pStmt.executeUpdate() != 1) { System.out.println("Error updating DetId: " + detId); } else { System.out.print(detId + ", "); fixedCnt++; } } System.out.println(); // Find all the determinations sql = String.format("SELECT DeterminationId FROM determination WHERE PreferredTaxonID = %d", id, id); System.out.println(sql); ids = BasicSQLUtils.queryForInts(conn, sql); System.out.println("Fixing " + ids.size() + " determinations with PreferredTaxonID: " + id + " Setting to orig TaxonID: " + firstID); for (Integer detId : ids) { pStmt2.setInt(1, firstID); pStmt2.setInt(2, detId); if (pStmt2.executeUpdate() != 1) { System.out.println("Error updating DetId: " + detId); } else { System.out.print(detId + ", "); fixedCnt++; } } System.out.println(); sql = String.format("SELECT TaxonID FROM taxon WHERE AcceptedID = %d", id); System.out.println(sql); ids = BasicSQLUtils.queryForInts(conn, sql); System.out.println("Fixing " + ids.size() + " taxon with AcceptedID: " + id + " Setting to orig TaxonID: " + firstID); for (Integer taxId : ids) { pStmt3.setInt(1, firstID); pStmt3.setInt(2, taxId); if (pStmt3.executeUpdate() != 1) { System.out.println("Error updating TaxId: " + taxId); } else { System.out.print(taxId + ", "); fixedCnt++; } } System.out.println(); sql = "SELECT COUNT(*) FROM taxon WHERE ParentID = " + id; System.out.println(sql); if (BasicSQLUtils.getCountAsInt(sql) == 0) { delStmt.setInt(1, id); if (delStmt.executeUpdate() != 1) { System.out.println("Error deleting TaxonID: " + id); } else { System.out.println("Deleted TaxonID: " + id); } } else { System.out.println("Unable to delete TaxonID: " + id + " it is a parent."); } c++; } rs2.close(); int detCnt = BasicSQLUtils .getCountAsInt("SELECT COUNT(*) FROM determination WHERE TaxonID = " + firstID); if (detCnt > 0) { System.out.println(detCnt + " Determinations still using TaxonID: " + firstID); } } stmt.close(); pStmt.close(); System.out.println("Fixed Det Ids: " + fixedCnt); } catch (SQLException ex) { ex.printStackTrace(); } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java
/** * Given a list of locale pairs, remove them from the list of all locale * pairs. Then create a hashtable where the key is the source locale, and * the value is all possible target locales. * /*from w w w . j a va2s.c o m*/ */ public static Hashtable getRemainingLocales(List currentLocales) throws EnvoyServletException { Hashtable remaining = new Hashtable(); Vector sourceLocales = UserHandlerHelper.getAllSourceLocales(); for (int i = 0; i < sourceLocales.size(); i++) { GlobalSightLocale curLocale = (GlobalSightLocale) sourceLocales.elementAt(i); Vector validTargets = UserHandlerHelper.getTargetLocales(curLocale); remaining.put(curLocale, validTargets); } // Now that we have a hashtable of all valid source locales and // their target locales, removes the ones that already exist for // this vendor. for (int i = 0; i < currentLocales.size(); i++) { LocalePair pair = (LocalePair) currentLocales.get(i); GlobalSightLocale target = pair.getTarget(); Vector targets = (Vector) remaining.get(pair.getSource()); if (targets != null && targets.contains(target)) { targets.remove(target); if (targets.size() == 0) { // no valid targets left so remove the entry in the hash remaining.remove(pair.getSource()); } } } return remaining; }
From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java
/** * Return a hashtable where the key is an activity and the value is a list * of the activity rates//from w w w .j av a2s . c o m */ public static HashMap getActivities(GlobalSightLocale sourceLocale, GlobalSightLocale targetLocale, Locale uiLocale) throws EnvoyServletException { boolean isCostingEnabled = false; try { SystemConfiguration sc = SystemConfiguration.getInstance(); isCostingEnabled = sc.getBooleanParameter(SystemConfigParamNames.COSTING_ENABLED); } catch (Exception e) { } try { HashMap activityHash = new HashMap(); Vector activities = UserHandlerHelper.getAllActivities(uiLocale); for (int i = 0; i < activities.size(); i++) { Activity activity = (Activity) activities.get(i); Collection activityRates = null; if (isCostingEnabled) { activityRates = ServerProxy.getCostingEngine().getRates(activity, sourceLocale, targetLocale); } activityHash.put(activity, activityRates); } return activityHash; } catch (Exception e) { throw new EnvoyServletException(e); } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java
/** * Save the request parameters from the edit role page *//*from w ww . j av a2s . co m*/ public static void modifyRole(Vendor vendor, HttpServletRequest request, SessionManager sessionMgr, Locale uiLocale) throws EnvoyServletException { LocalePair lp = (LocalePair) sessionMgr.getAttribute("localePair"); GlobalSightLocale srcLocale = (GlobalSightLocale) sessionMgr.getAttribute("sourceLocale"); GlobalSightLocale targLocale = (GlobalSightLocale) sessionMgr.getAttribute("targetLocale"); // Get all possible activities Vector activities = UserHandlerHelper.getAllActivities(uiLocale); for (int i = 0; i < activities.size(); i++) { Activity activity = (Activity) activities.get(i); String activityName = (String) request.getParameter(activity.getActivityName()); if (activityName != null) { Rate rate = getRate(activity, request); VendorRole role = activityInRole(activity.getName(), lp, vendor); if (role != null) { // update the role role.setRate(rate); } else { // add new role VendorRole newRole = new VendorRole(activity, lp, rate); vendor.addRole(newRole); } } else { VendorRole role = activityInRole(activity.getName(), lp, vendor); if (role != null) { // remove role vendor.removeRole(role); } } } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java
/** * Save the request parameters from the new role page *//* ww w . java2s.c o m*/ public static void newRole(Vendor vendor, HttpServletRequest request, SessionManager sessionMgr, Locale uiLocale) throws EnvoyServletException { // Get the source and target locales String src = request.getParameter("srcLocales"); String targ = request.getParameter("targLocales"); if (src.equals("-1") || targ.equals("-1")) { // the user isn't adding a role (it's not required) return; } LocalePair lp = null; try { GlobalSightLocale sourceLocale = ServerProxy.getLocaleManager().getLocaleById(Long.parseLong(src)); GlobalSightLocale targetLocale = ServerProxy.getLocaleManager().getLocaleById(Long.parseLong(targ)); lp = ServerProxy.getLocaleManager().getLocalePairBySourceTargetIds(sourceLocale.getId(), targetLocale.getId()); } catch (Exception e) { throw new EnvoyServletException(e); } // Get all activities and loop thru to get set ones Vector activities = UserHandlerHelper.getAllActivities(uiLocale); for (int i = 0; i < activities.size(); i++) { Activity activity = (Activity) activities.get(i); String activityName = (String) request.getParameter(activity.getActivityName()); Rate rate = null; if (activityName != null) { rate = getRate(activity, request); VendorRole newRole = new VendorRole(activity, lp, rate); vendor.addRole(newRole); } } }