List of usage examples for java.util Collections binarySearch
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
From source file:org.jfree.data.time.TimeSeries.java
/** * Adds a data item to the series and sends a {@link SeriesChangeEvent} to * all registered listeners.//from ww w. j a va2 s .c o m * * @param item the (timeperiod, value) pair (<code>null</code> not * permitted). * @param notify notify listeners? */ public void add(TimeSeriesDataItem item, boolean notify) { ParamChecks.nullNotPermitted(item, "item"); item = (TimeSeriesDataItem) item.clone(); Class c = item.getPeriod().getClass(); if (this.timePeriodClass == null) { this.timePeriodClass = c; } else if (!this.timePeriodClass.equals(c)) { StringBuilder b = new StringBuilder(); b.append("You are trying to add data where the time period class "); b.append("is "); b.append(item.getPeriod().getClass().getName()); b.append(", but the TimeSeries is expecting an instance of "); b.append(this.timePeriodClass.getName()); b.append("."); throw new SeriesException(b.toString()); } // make the change (if it's not a duplicate time period)... boolean added = false; int count = getItemCount(); if (count == 0) { this.data.add(item); added = true; } else { RegularTimePeriod last = getTimePeriod(getItemCount() - 1); if (item.getPeriod().compareTo(last) > 0) { this.data.add(item); added = true; } else { int index = Collections.binarySearch(this.data, item); if (index < 0) { this.data.add(-index - 1, item); added = true; } else { StringBuilder b = new StringBuilder(); b.append("You are attempting to add an observation for "); b.append("the time period "); b.append(item.getPeriod().toString()); b.append(" but the series already contains an observation"); b.append(" for that time period. Duplicates are not "); b.append("permitted. Try using the addOrUpdate() method."); throw new SeriesException(b.toString()); } } } if (added) { updateBoundsForAddedItem(item); // check if this addition will exceed the maximum item count... if (getItemCount() > this.maximumItemCount) { TimeSeriesDataItem d = (TimeSeriesDataItem) this.data.remove(0); updateBoundsForRemovedItem(d); } removeAgedItems(false); // remove old items if necessary, but // don't notify anyone, because that // happens next anyway... if (notify) { fireSeriesChanged(); } } }
From source file:com.smartitengineering.cms.api.impl.workspace.WorkspaceAPIImpl.java
protected Collection<String> cutList(List<String> list, String startPoint, int count) { if (logger.isDebugEnabled()) { logger.debug("All names " + list); }//from w ww . j av a 2 s . co m int index = Collections.binarySearch(list, startPoint); if (logger.isDebugEnabled()) { logger.debug("Index " + index); } if (index < 0) { index = index * -1; } if (count > 0 && index + 1 >= list.size() && StringUtils.isNotBlank(startPoint)) { logger.debug("Index is equal to size and count is greater than 0"); return Collections.emptyList(); } if (count < 0 && index <= 0) { logger.debug("Index is zero to size and count is smaller than 0"); return Collections.emptyList(); } final int fromIndex; final int toIndex; if (count > 0) { fromIndex = StringUtils.isBlank(startPoint) ? 0 : index + 1; toIndex = (fromIndex + count >= list.size()) ? list.size() : fromIndex + count; } else { toIndex = index; fromIndex = (toIndex + count >= 0) ? toIndex + count : 0; } if (logger.isDebugEnabled()) { logger.debug("Sublisting starts at " + fromIndex + " and ends before " + toIndex); } final List<String> result = list.subList(fromIndex, toIndex); if (logger.isDebugEnabled()) { logger.debug("Returning " + result); } return result; }
From source file:org.openmrs.module.hospitalcore.impl.HospitalCoreServiceImpl.java
private int indexOf(List<ConceptModel> conceptList, String name) { ConceptModel concept = new ConceptModel(); concept.setName(name);//w w w . j a v a 2s . co m return Collections.binarySearch(conceptList, concept); }
From source file:com.bt.download.android.gui.Librarian.java
private Set<Integer> getSharedFiles(byte fileType) { TreeSet<Integer> result = new TreeSet<Integer>(); List<Integer> delete = new ArrayList<Integer>(); Cursor c = null;// w w w .j a v a 2 s . com try { ContentResolver cr = context.getContentResolver(); String[] columns = new String[] { SharingColumns.FILE_ID, SharingColumns._ID }; c = cr.query(Sharing.Media.CONTENT_URI, columns, SharingColumns.SHARED + "=1 AND " + SharingColumns.FILE_TYPE + "=?", new String[] { String.valueOf(fileType) }, null); if (c == null || !c.moveToFirst()) { return result; } int fileIdCol = c.getColumnIndex(SharingColumns.FILE_ID); int sharingIdCol = c.getColumnIndex(SharingColumns._ID); Pair<List<Integer>, List<String>> pair = getAllFiles(fileType); List<Integer> files = pair.first; List<String> paths = pair.second; do { int fileId = c.getInt(fileIdCol); int sharingId = c.getInt(sharingIdCol); int index = Collections.binarySearch(files, fileId); try { if (index >= 0) { File f = new File(paths.get(index)); if (f.exists() && f.isFile()) { result.add(fileId); } else { delete.add(sharingId); } } else { delete.add(sharingId); } } catch (Throwable e) { Log.e(TAG, "Error checking fileId: " + fileId + ", fileType: " + fileId); } } while (c.moveToNext()); } catch (Throwable e) { Log.e(TAG, "General failure getting shared/unshared files ids", e); } finally { if (c != null) { c.close(); } if (delete.size() > 0) { deleteSharedStates(delete); } } return result; }
From source file:org.lealone.cluster.locator.TokenMetaData.java
public Token getPredecessor(Token token) { List<Token> tokens = sortedTokens(); int index = Collections.binarySearch(tokens, token); assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndpointMap.keySet(), ", "); return index == 0 ? tokens.get(tokens.size() - 1) : tokens.get(index - 1); }
From source file:org.lealone.cluster.locator.TokenMetaData.java
public Token getSuccessor(Token token) { List<Token> tokens = sortedTokens(); int index = Collections.binarySearch(tokens, token); assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndpointMap.keySet(), ", "); return (index == (tokens.size() - 1)) ? tokens.get(0) : tokens.get(index + 1); }
From source file:org.lealone.cluster.locator.TokenMetaData.java
public static int firstTokenIndex(final ArrayList<Token> ring, Token start, boolean insertMin) { assert ring.size() > 0; // insert the minimum token (at index == -1) if we were asked to include it and it isn't a member of the ring int i = Collections.binarySearch(ring, start); if (i < 0) { i = (i + 1) * (-1);/*from w ww .ja v a 2 s .c o m*/ if (i >= ring.size()) i = insertMin ? -1 : 0; } return i; }
From source file:org.jfree.data.time.TimeSeries.java
/** * Updates (changes) the value for a time period. Throws a * {@link SeriesException} if the period does not exist. * * @param period the period (<code>null</code> not permitted). * @param value the value (<code>null</code> permitted). *//* ww w. j a v a2s . c o m*/ public void update(RegularTimePeriod period, Number value) { TimeSeriesDataItem temp = new TimeSeriesDataItem(period, value); int index = Collections.binarySearch(this.data, temp); if (index < 0) { throw new SeriesException("There is no existing value for the " + "specified 'period'."); } update(index, value); }
From source file:org.jfree.data.time.TimeSeries.java
/** * Adds or updates an item in the times series and sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param item the data item (<code>null</code> not permitted). * * @return A copy of the overwritten data item, or <code>null</code> if no * item was overwritten.//from ww w .ja va 2 s. co m * * @since 1.0.14 */ public TimeSeriesDataItem addOrUpdate(TimeSeriesDataItem item) { ParamChecks.nullNotPermitted(item, "item"); Class periodClass = item.getPeriod().getClass(); if (this.timePeriodClass == null) { this.timePeriodClass = periodClass; } else if (!this.timePeriodClass.equals(periodClass)) { String msg = "You are trying to add data where the time " + "period class is " + periodClass.getName() + ", but the TimeSeries is expecting an instance of " + this.timePeriodClass.getName() + "."; throw new SeriesException(msg); } TimeSeriesDataItem overwritten = null; int index = Collections.binarySearch(this.data, item); if (index >= 0) { TimeSeriesDataItem existing = (TimeSeriesDataItem) this.data.get(index); overwritten = (TimeSeriesDataItem) existing.clone(); // figure out if we need to iterate through all the y-values // to find the revised minY / maxY boolean iterate = false; Number oldYN = existing.getValue(); double oldY = oldYN != null ? oldYN.doubleValue() : Double.NaN; if (!Double.isNaN(oldY)) { iterate = oldY <= this.minY || oldY >= this.maxY; } existing.setValue(item.getValue()); if (iterate) { updateMinMaxYByIteration(); } else if (item.getValue() != null) { double yy = item.getValue().doubleValue(); this.minY = minIgnoreNaN(this.minY, yy); this.maxY = maxIgnoreNaN(this.maxY, yy); } } else { item = (TimeSeriesDataItem) item.clone(); this.data.add(-index - 1, item); updateBoundsForAddedItem(item); // check if this addition will exceed the maximum item count... if (getItemCount() > this.maximumItemCount) { TimeSeriesDataItem d = (TimeSeriesDataItem) this.data.remove(0); updateBoundsForRemovedItem(d); } } removeAgedItems(false); // remove old items if necessary, but // don't notify anyone, because that // happens next anyway... fireSeriesChanged(); return overwritten; }
From source file:org.geoserver.wms.map.GetMapKvpRequestReader.java
private static void addRemoteLayersFromUserLayer(GetMapRequest request, UserLayer ul, List layers, List styles) throws ServiceException, IOException { RemoteOWS service = ul.getRemoteOWS(); if (!service.getService().equalsIgnoreCase("WFS")) throw new ServiceException("GeoServer only supports WFS as remoteOWS service"); if (service.getOnlineResource() == null) throw new ServiceException("OnlineResource for remote WFS not specified in SLD"); final FeatureTypeConstraint[] featureConstraints = ul.getLayerFeatureConstraints(); if (featureConstraints == null || featureConstraints.length == 0) throw new ServiceException( "No FeatureTypeConstraint specified, no layer can be loaded for this UserStyle"); DataStore remoteWFS = null;/*w w w . ja v a 2s. c om*/ List remoteTypeNames = null; try { URL url = new URL(service.getOnlineResource()); remoteWFS = connectRemoteWFS(url); remoteTypeNames = new ArrayList(Arrays.asList(remoteWFS.getTypeNames())); Collections.sort(remoteTypeNames); } catch (MalformedURLException e) { throw new ServiceException("Invalid online resource url: '" + service.getOnlineResource() + "'"); } Style[] layerStyles = ul.getUserStyles(); if (request.getFilter() == null) request.setFilter(new ArrayList()); for (int i = 0; i < featureConstraints.length; i++) { // make sure the layer is there String name = featureConstraints[i].getFeatureTypeName(); if (Collections.binarySearch(remoteTypeNames, name) < 0) { throw new ServiceException("Could not find layer feature type '" + name + "' on remote WFS '" + service.getOnlineResource()); } // grab the filter Filter filter = featureConstraints[i].getFilter(); if (filter == null) filter = Filter.INCLUDE; // connect the layer SimpleFeatureSource fs = remoteWFS.getFeatureSource(name); // this is messy, why the spec allows for multiple constraints and multiple // styles is beyond me... we'll style each remote layer with all possible // styles, feauture type style matching will do the rest during rendering for (int j = 0; j < layerStyles.length; j++) { Style style = layerStyles[i]; MapLayerInfo info = new MapLayerInfo(fs); layers.add(info); styles.add(style); // treat it like an externally provided filter... ugly I know, but // the sane thing (adding a filter as a MapLayerInfo field) would // break havoc in GetFeatureInfo request.getFilter().add(filter); } } }