List of usage examples for java.util SortedSet size
int size();
From source file:com.redhat.rhn.frontend.xmlrpc.kickstart.profile.ProfileHandler.java
/** * Set custom options for a kickstart profile. * @param loggedInUser The current user/*from ww w .ja v a 2s. c o m*/ * @param ksLabel the kickstart label * @param options the custom options to set * @return a int being the number of options set * @throws FaultException A FaultException is thrown if * the profile associated with ksLabel cannot be found * * @xmlrpc.doc Set custom options for a kickstart profile. * @xmlrpc.param #session_key() * @xmlrpc.param #param("string","ksLabel") * @xmlrpc.param #param("string[]","options") * @xmlrpc.returntype #return_int_success() */ public int setCustomOptions(User loggedInUser, String ksLabel, List<String> options) throws FaultException { KickstartData ksdata = XmlRpcKickstartHelper.getInstance().lookupKsData(ksLabel, loggedInUser.getOrg()); if (ksdata == null) { throw new FaultException(-3, "kickstartProfileNotFound", "No Kickstart Profile found with label: " + ksLabel); } Long ksid = ksdata.getId(); KickstartOptionsCommand cmd = new KickstartOptionsCommand(ksid, loggedInUser); SortedSet<KickstartCommand> customSet = new TreeSet<KickstartCommand>(); if (options != null) { for (int i = 0; i < options.size(); i++) { String option = options.get(i); KickstartCommand custom = new KickstartCommand(); custom.setCommandName(KickstartFactory.lookupKickstartCommandName("custom")); // the following is a workaround to ensure that the options are rendered // on the UI on separate lines. if (i < (options.size() - 1)) { option += "\r"; } custom.setArguments(option); custom.setKickstartData(cmd.getKickstartData()); custom.setCustomPosition(customSet.size()); custom.setCreated(new Date()); custom.setModified(new Date()); customSet.add(custom); } if (cmd.getKickstartData().getCustomOptions() == null) { cmd.getKickstartData().setCustomOptions(customSet); } else { cmd.getKickstartData().setCustomOptions(customSet); } cmd.store(); } return 1; }
From source file:org.cloudata.core.tabletserver.DiskSSTable.java
public Row.Key findMidRowKeyForSplit() throws IOException { lock.obtainReadLock();/*from w w w .j ava 2 s. co m*/ try { //MapFile Index? Row.Key merge. SortedSet<Row.Key> mergedRowKeySet = new TreeSet<Row.Key>(); int indexRecordCount = 0; int mapFileCount = 0; for (Map.Entry<String, List<TabletMapFile>> entry : mapFiles.entrySet()) { List<TabletMapFile> columnMapFiles = entry.getValue(); if (columnMapFiles.isEmpty()) continue; for (TabletMapFile columnMapFile : columnMapFiles) { mapFileCount++; for (MapFileIndexRecord mapFileIndexRecord : columnMapFile.getMapFileIndexRecords()) { mergedRowKeySet.add(mapFileIndexRecord.getRowKey()); indexRecordCount++; } } } //Split key . int rowRangeSize = mergedRowKeySet.size(); if (rowRangeSize == 1) { /////////////////////////////////////////////////////////////////////////// // // Row.Key previousRowKey = null; // for(Map.Entry<String, List<TabletMapFile>> entry: mapFiles.entrySet()) { // List<TabletMapFile> columnMapFiles = entry.getValue(); // if(columnMapFiles.size() == 0) continue; // // if(columnMapFiles.size() > 1) { // LOG.warn("Map file size > 1 while split:" + tabletInfo.getTabletName()); // } // for(TabletMapFile columnMapFile: columnMapFiles) { // for(MapFileIndexRecord mapFileIndexRecord: columnMapFile.getMapFileIndexRecords()) { // Row.Key indexRowKey = mapFileIndexRecord.getRowKey(); // if(previousRowKey != null && !indexRowKey.equals(previousRowKey)) { // LOG.debug("Different rowKey:" + indexRowKey); // } // previousRowKey = indexRowKey; // } // } // } //End of /////////////////////////////////////////////////////////////////////////// return null; } else if (rowRangeSize == 2) { return mergedRowKeySet.first(); } int count = 0; Row.Key midRowKey = null; for (Row.Key eachRowKey : mergedRowKeySet) { if (count >= (rowRangeSize / 2)) { midRowKey = eachRowKey; break; } count++; } if (midRowKey != null && midRowKey.equals(tabletInfo.getEndRowKey())) { LOG.warn("Wrong mid rowkey:"); for (Row.Key eachRowKey : mergedRowKeySet) { LOG.info("MapFile rowKey:" + eachRowKey); } } return midRowKey; } finally { lock.releaseReadLock(); } }
From source file:org.apache.accumulo.test.RewriteTabletDirectoriesIT.java
@Test public void test() throws Exception { try (AccumuloClient c = Accumulo.newClient().from(getClientProperties()).build()) { c.securityOperations().grantTablePermission(c.whoami(), MetadataTable.NAME, TablePermission.WRITE); final String tableName = getUniqueNames(1)[0]; c.tableOperations().create(tableName); // Write some data to a table and add some splits final SortedSet<Text> splits = new TreeSet<>(); try (BatchWriter bw = c.createBatchWriter(tableName)) { for (String split : "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".split(",")) { splits.add(new Text(split)); Mutation m = new Mutation(new Text(split)); m.put(new byte[] {}, new byte[] {}, new byte[] {}); bw.addMutation(m);//from w ww . j a v a 2 s . c om } } c.tableOperations().addSplits(tableName, splits); try (BatchScanner scanner = c.createBatchScanner(MetadataTable.NAME)) { DIRECTORY_COLUMN.fetch(scanner); TableId tableId = TableId.of(c.tableOperations().tableIdMap().get(tableName)); assertNotNull("TableID for " + tableName + " was null", tableId); scanner.setRanges(Collections.singletonList(TabletsSection.getRange(tableId))); // verify the directory entries are all on v1, make a few entries relative int count = 0; try (BatchWriter bw = c.createBatchWriter(MetadataTable.NAME)) { for (Entry<Key, Value> entry : scanner) { assertTrue("Expected " + entry.getValue() + " to contain " + v1, entry.getValue().toString().contains(v1.toString())); count++; if (count % 2 == 0) { String[] parts = entry.getValue().toString().split("/"); Key key = entry.getKey(); Mutation m = new Mutation(key.getRow()); m.put(key.getColumnFamily(), key.getColumnQualifier(), new Value((Path.SEPARATOR + parts[parts.length - 1]).getBytes())); bw.addMutation(m); } } } assertEquals(splits.size() + 1, count); // This should fail: only one volume assertEquals(1, cluster.exec(RandomizeVolumes.class, "-c", cluster.getClientPropsPath(), "-t", tableName) .getProcess().waitFor()); cluster.stop(); // add the 2nd volume PropertiesConfiguration conf = new PropertiesConfiguration(); conf.load(cluster.getAccumuloPropertiesPath()); conf.setProperty(Property.INSTANCE_VOLUMES.getKey(), v1 + "," + v2); conf.save(cluster.getAccumuloPropertiesPath()); // initialize volume assertEquals(0, cluster.exec(Initialize.class, "--add-volumes").getProcess().waitFor()); cluster.start(); // change the directory entries assertEquals(0, cluster.exec(Admin.class, "randomizeVolumes", "-t", tableName).getProcess().waitFor()); // verify a more equal sharing int v1Count = 0, v2Count = 0; for (Entry<Key, Value> entry : scanner) { if (entry.getValue().toString().contains(v1.toString())) { v1Count++; } if (entry.getValue().toString().contains(v2.toString())) { v2Count++; } } log.info("Count for volume1: {}", v1Count); log.info("Count for volume2: {}", v2Count); assertEquals(splits.size() + 1, v1Count + v2Count); // a fair chooser will differ by less than count(volumes) assertTrue("Expected the number of files to differ between volumes by less than 10. " + v1Count + " " + v2Count, Math.abs(v1Count - v2Count) < 2); // verify we can read the old data count = 0; for (Entry<Key, Value> entry : c.createScanner(tableName, Authorizations.EMPTY)) { assertTrue("Found unexpected entry in table: " + entry, splits.contains(entry.getKey().getRow())); count++; } assertEquals(splits.size(), count); } } }
From source file:com.gargoylesoftware.htmlunit.html.HtmlPage.java
private void removeElement(final Map<String, SortedSet<DomElement>> map, final DomElement element, final String attribute, final boolean recurse) { // first try real attributes String value = element.getAttribute(attribute); if (DomElement.ATTRIBUTE_NOT_DEFINED == value && !(element instanceof HtmlApplet)) { // second try are JavaScript attributes // ...but applets are a bit special so ignore them final ScriptableObject scriptObject = element.getScriptableObject(); // we have to make sure the scriptObject has a slot for the given attribute. // just using get() may use e.g. getWithPreemption(). if (scriptObject.has(attribute, scriptObject)) { final Object jsValue = scriptObject.get(attribute, scriptObject); if (jsValue != null && jsValue != Scriptable.NOT_FOUND && jsValue instanceof String) { value = (String) jsValue; }//from w w w . j ava 2s . co m } } if (!StringUtils.isEmpty(value)) { final SortedSet<DomElement> elements = map.remove(value); if (elements != null && (elements.size() != 1 || !elements.contains(element))) { elements.remove(element); map.put(value, elements); } } if (recurse) { for (final DomElement child : element.getChildElements()) { removeElement(map, child, attribute, true); } } }
From source file:org.lockss.config.ConfigManager.java
private void logConfig(Configuration config, Configuration oldConfig, Configuration.Differences diffs) { int maxLogValLen = config.getInt(PARAM_MAX_LOG_VAL_LEN, DEFAULT_MAX_LOG_VAL_LEN); Set<String> diffSet = diffs.getDifferenceSet(); SortedSet<String> keys = new TreeSet<String>(diffSet); int elided = 0; int numDiffs = keys.size(); // keys includes param name prefixes that aren't actual params, so // numDiffs is inflated by several. for (String key : keys) { if (numDiffs <= 40 || log.isDebug3() || shouldParamBeLogged(key)) { if (config.containsKey(key)) { String val = config.get(key); log.debug(" " + key + " = " + StringUtils.abbreviate(val, maxLogValLen)); } else if (oldConfig.containsKey(key)) { log.debug(" " + key + " (removed)"); }// www. j a va 2 s . c o m } else { elided++; } } if (elided > 0) log.debug(elided + " keys elided"); log.debug("New TdbAus: " + diffs.getTdbAuDifferenceCount()); if (log.isDebug3()) { log.debug3("TdbDiffs: " + diffs.getTdbDifferences()); } if (log.isDebug2()) { Tdb tdb = config.getTdb(); if (tdb != null) { log.debug2(StringPool.AU_CONFIG_PROPS.toStats()); Histogram hist1 = new Histogram(15); Histogram hist2 = new Histogram(15); Histogram hist3 = new Histogram(15); for (TdbAu.Id id : tdb.getAllTdbAuIds()) { TdbAu tau = id.getTdbAu(); hist1.addDataPoint(tau.getParams().size()); hist2.addDataPoint(tau.getAttrs().size()); hist3.addDataPoint(tau.getProperties().size()); } logHist("Tdb Params", hist1); logHist("Tdb Attrs", hist2); logHist("Tdb Props", hist3); } } }
From source file:org.alfresco.repo.web.scripts.facet.FacetablePropertiesGet.java
@Override protected Map<String, Object> unprotectedExecuteImpl(WebScriptRequest req, Status status, Cache cache) { // We use any provided locale to localise some elements of the webscript response, but not all. final String userLocaleString = req.getParameter(QUERY_PARAM_LOCALE); final Locale userLocale = (userLocaleString == null) ? Locale.getDefault() : new Locale(userLocaleString); // There are multiple defined URIs for this REST endpoint. Some define a "classname" template var. final Map<String, String> templateVars = req.getServiceMatch().getTemplateVars(); final String contentClassName = templateVars.get(TEMPLATE_VAR_CLASSNAME); final QName contentClassQName; try {/*from ww w. j a va 2s.c o m*/ contentClassQName = contentClassName == null ? null : QName.createQName(contentClassName, namespaceService); } catch (NamespaceException e) { throw new WebScriptException(Status.STATUS_NOT_FOUND, "Unrecognised classname: " + contentClassName, e); } // Build an FTL model of facetable properties - this includes normal Alfresco properties and also // 'synthetic' properties like size and mimetype. See below for more details. final Map<String, Object> model = new HashMap<>(); final SortedSet<FacetablePropertyFTL<?>> facetableProperties; if (contentClassQName == null) { facetableProperties = toFacetablePropertyModel(facetService.getFacetableProperties(), userLocale); final List<SyntheticPropertyDefinition> facetableSyntheticProperties = facetService .getFacetableSyntheticProperties(); facetableProperties.addAll(toFacetablePropertyModel_(facetableSyntheticProperties, userLocale)); } else { facetableProperties = toFacetablePropertyModel(facetService.getFacetableProperties(contentClassQName), userLocale); final List<SyntheticPropertyDefinition> facetableSyntheticProperties = facetService .getFacetableSyntheticProperties(contentClassQName); facetableProperties.addAll(toFacetablePropertyModel_(facetableSyntheticProperties, userLocale)); } // Always add some hard-coded facetable "properties" facetableProperties.add(new SpecialFacetablePropertyFTL("TAG", "Tag")); facetableProperties.add(new SpecialFacetablePropertyFTL("SITE", "Site", SiteModel.TYPE_SITE)); // The webscript allows for some further filtering of results: List<ResultFilter> filters = new ArrayList<>(); // Filter by property QName namespace: final String namespaceFilter = req.getParameter(QUERY_PARAM_NAMESPACE); if (namespaceFilter != null) { filters.add(new ResultFilter() { @Override public boolean filter(FacetablePropertyFTL<?> facetableProperty) { final QName propQName = facetableProperty.getQname(); Collection<String> prefixes = namespaceService.getPrefixes(propQName.getNamespaceURI()); return prefixes.contains(namespaceFilter); } }); } List<FacetablePropertyFTL<?>> filteredFacetableProperties = filter(facetableProperties, filters); if (logger.isDebugEnabled()) { logger.debug("Retrieved " + facetableProperties.size() + " available facets; filtered to " + filteredFacetableProperties.size()); } // Create paging ScriptPagingDetails paging = new ScriptPagingDetails( getNonNegativeIntParameter(req, QUERY_PARAM_MAX_ITEMS, DEFAULT_MAX_ITEMS_PER_PAGE), getNonNegativeIntParameter(req, QUERY_PARAM_SKIP_COUNT, 0)); model.put(PROPERTIES_KEY, ModelUtil.page(filteredFacetableProperties, paging)); model.put("paging", ModelUtil.buildPaging(paging)); return model; }
From source file:fll.scheduler.GreedySolver.java
private void outputSchedule(final File schedule) throws IOException { final List<SubjectiveStation> subjectiveStations = solverParameters.getSubjectiveStations(); try (final CSVWriter csv = new CSVWriter( new OutputStreamWriter(new FileOutputStream(schedule), Utilities.DEFAULT_CHARSET))) { final List<String> line = new ArrayList<String>(); line.add(TournamentSchedule.TEAM_NUMBER_HEADER); line.add(TournamentSchedule.TEAM_NAME_HEADER); line.add(TournamentSchedule.ORGANIZATION_HEADER); line.add(TournamentSchedule.JUDGE_GROUP_HEADER); for (final SubjectiveStation station : subjectiveStations) { line.add(station.getName()); }//from w w w . j a v a2 s . co m for (int round = 0; round < solverParameters.getNumPerformanceRounds(); ++round) { line.add(String.format(TournamentSchedule.PERF_HEADER_FORMAT, round + 1)); line.add(String.format(TournamentSchedule.TABLE_HEADER_FORMAT, round + 1)); } csv.writeNext(line.toArray(new String[line.size()])); line.clear(); for (final SchedTeam team : getAllTeams()) { final int teamNum = (team.getGroup() + 1) * 100 + team.getIndex(); final int judgingGroup = team.getGroup(); line.add(String.valueOf(teamNum)); line.add("Team " + teamNum); line.add("Org " + teamNum); line.add(groupNames[judgingGroup]); // judging group for (int subj = 0; subj < subjectiveStations.size(); ++subj) { final SubjectiveStation station = subjectiveStations.get(subj); final LocalTime time = getTime(sz[team.getGroup()][team.getIndex()][subj], 1); if (null == time) { throw new RuntimeException( "Could not find a subjective start for group: " + groupNames[team.getGroup()] + " team: " + (team.getIndex() + 1) + " subj: " + station.getName()); } line.add(TournamentSchedule.formatTime(time)); } // find all performances for a team and then sort by time final SortedSet<PerformanceTime> perfTimes = new TreeSet<PerformanceTime>(); for (int round = 0; round < solverParameters.getNumPerformanceRounds(); ++round) { for (int table = 0; table < solverParameters.getNumTables(); ++table) { for (int side = 0; side < 2; ++side) { final LocalTime time = getTime(pz[team.getGroup()][team.getIndex()][table][side], round + 1); if (null != time) { final String tableName = String.format("Table%d", (table + 1)); final int displayedSide = side + 1; perfTimes.add(new PerformanceTime(time, tableName, displayedSide)); } } } } if (perfTimes.size() != solverParameters.getNumPerformanceRounds()) { throw new FLLRuntimeException("Expecting " + solverParameters.getNumPerformanceRounds() + " performance times, but found " + perfTimes.size() + " group: " + (team.getGroup() + 1) + " team: " + (team.getIndex() + 1) + " perfs: " + perfTimes); } for (final PerformanceTime perfTime : perfTimes) { line.add(TournamentSchedule.formatTime(perfTime.getTime())); line.add(perfTime.getTable() + " " + perfTime.getSide()); } csv.writeNext(line.toArray(new String[line.size()])); line.clear(); } } }
From source file:com.rapidminer.gui.plotter.charts.AbstractPieChartPlotter.java
private void updateGroups() { SortedSet<String> groups = new TreeSet<String>(); if (groupByColumn >= 0) { synchronized (dataTable) { if (dataTable.isDate(groupByColumn)) { for (int i = 0; i < dataTable.getNumberOfRows(); i++) { DataTableRow row = dataTable.getRow(i); groups.add(Tools.createDateAndFormat(row.getValue(groupByColumn))); }// w ww . j a v a2 s . c o m } else if (dataTable.isTime(groupByColumn)) { for (int i = 0; i < dataTable.getNumberOfRows(); i++) { DataTableRow row = dataTable.getRow(i); groups.add(Tools.createTimeAndFormat(row.getValue(groupByColumn))); } } else if (dataTable.isDateTime(groupByColumn)) { for (int i = 0; i < dataTable.getNumberOfRows(); i++) { DataTableRow row = dataTable.getRow(i); groups.add(Tools.createDateTimeAndFormat(row.getValue(groupByColumn))); } } else if (dataTable.isNominal(groupByColumn)) { for (int i = 0; i < dataTable.getNumberOfRows(); i++) { DataTableRow row = dataTable.getRow(i); groups.add(dataTable.mapIndex(groupByColumn, (int) row.getValue(groupByColumn))); } } else { for (int i = 0; i < dataTable.getNumberOfRows(); i++) { DataTableRow row = dataTable.getRow(i); groups.add(Tools.formatIntegerIfPossible(row.getValue(groupByColumn))); } } } } if (groups.size() > 0) { ExtendedListModel model = new ExtendedListModel(); for (String group : groups) { model.addElement(group, "Select group '" + group + "' for explosion."); } this.explodingGroupList.setModel(model); } else { ExtendedListModel model = new ExtendedListModel(); model.addElement("Specify 'Group By' first..."); this.explodingGroupList.setModel(model); } }
From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java
public synchronized static void removeModule(HttpServletRequest request, SessionDataInfo sessionData, DatabaseInfo databaseDefn) throws AgileBaseException { CompanyInfo company = databaseDefn.getAuthManager().getCompanyForLoggedInUser(request); String internalModuleName = request.getParameter("internalmodulename"); if (internalModuleName == null) { throw new MissingParametersException("internalmodulename is required to remove a module"); }//from w w w .j av a2s . c o m ModuleInfo module = company.getModuleByInternalName(internalModuleName); // Check that the module hasn't got any reports in it Set<TableInfo> tables = company.getTables(); SortedSet<BaseReportInfo> memberReports = new TreeSet<BaseReportInfo>(); for (TableInfo table : tables) { for (BaseReportInfo report : table.getReports()) { ModuleInfo reportModule = report.getModule(); if (reportModule != null) { if (reportModule.equals(module)) { memberReports.add(report); } } } } if (memberReports.size() > 0) { throw new CantDoThatException("The module " + module + " still contains reports " + memberReports); } try { HibernateUtil.startHibernateTransaction(); HibernateUtil.activateObject(company); company.removeModule(module); HibernateUtil.currentSession().delete(module); HibernateUtil.currentSession().getTransaction().commit(); } catch (HibernateException hex) { HibernateUtil.currentSession().getTransaction().rollback(); company.addModule(module); throw new CantDoThatException("module removal failed", hex); } finally { HibernateUtil.closeSession(); } sessionData.setModule(null); }
From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java
protected void setPlotDrawingDefaults(Plot p, JRChartPlot jrPlot) { List defaultSeriesColors = (List) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.SERIES_COLORS); Paint[] defaultPlotOutlinePaintSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_PAINT_SEQUENCE) != null ? (Paint[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_PAINT_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE; Stroke[] defaultPlotStrokeSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_STROKE_SEQUENCE) != null ? (Stroke[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_STROKE_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE; Stroke[] defaultPlotOutlineStrokeSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_STROKE_SEQUENCE) != null ? (Stroke[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_STROKE_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE; Shape[] defaultPlotShapeSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_SHAPE_SEQUENCE) != null ? (Shape[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_SHAPE_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE; // Set color series Paint[] colors = null;// w w w . jav a 2 s . c o m SortedSet seriesColors = jrPlot.getSeriesColors(); Paint[] colorSequence = null; if (seriesColors != null && seriesColors.size() > 0) { int seriesColorsSize = seriesColors.size(); colors = new Paint[DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length + seriesColorsSize]; JRSeriesColor[] jrColorSequence = new JRSeriesColor[seriesColorsSize]; seriesColors.toArray(jrColorSequence); colorSequence = new Paint[seriesColorsSize]; for (int i = 0; i < seriesColorsSize; i++) { colorSequence[i] = jrColorSequence[i].getColor(); } populateSeriesColors(colors, colorSequence); } else if (defaultSeriesColors != null && defaultSeriesColors.size() > 0) { colors = new Paint[DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length + defaultSeriesColors.size()]; colorSequence = new Paint[defaultSeriesColors.size()]; defaultSeriesColors.toArray(colorSequence); populateSeriesColors(colors, colorSequence); } else { colors = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE; } p.setDrawingSupplier(new DefaultDrawingSupplier(colors, defaultPlotOutlinePaintSequence, defaultPlotStrokeSequence, defaultPlotOutlineStrokeSequence, defaultPlotShapeSequence)); }