List of usage examples for java.util Collections binarySearch
@SuppressWarnings("unchecked") public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
From source file:org.broad.igv.feature.FeatureUtils.java
/** * Return a feature that encompasses the supplied position. * * @param position Query position./*from ww w.j a v a 2 s. c o m*/ * @param features List of features. * @return The feature whose start overlaps with position, or null. */ private static Feature getFeatureAt(double position, List<? extends Feature> features) { int strt = (int) position; Feature key = new BasicFeature("", strt, strt + 1); int r = Collections.binarySearch(features, key, FEATURE_START_COMPARATOR); if (r >= 0) { return features.get(r); } else { return null; } }
From source file:dev.drsoran.moloko.sync.util.SyncUtils.java
public final static <T> void applyServerOperations(RtmProvider rtmProvider, List<? extends IServerSyncOperation<T>> serverOps, List<T> sortedServerElements, Comparator<? super T> cmp) throws ServiceException { for (IServerSyncOperation<T> serverOp : serverOps) { if (!(serverOp instanceof INoopSyncOperation)) { try { final T result = serverOp.execute(rtmProvider); if (result == null) throw new ServiceException(-1, "ServerSyncOperation produced no result"); // If the set already contains an element in respect to the Comparator, // then we update it by the new received. final int pos = Collections.binarySearch(sortedServerElements, result, cmp); if (pos >= 0) { sortedServerElements.remove(pos); sortedServerElements.add(pos, result); } else { sortedServerElements.add((-pos - 1), result); }//from www . ja v a2 s.c om } catch (ServiceException e) { MolokoApp.Log.e(SyncUtils.class, "Applying server operation failed", e); throw e; } } } }
From source file:it.cnr.icar.eric.server.query.federation.FederatedQueryProcessor.java
private AdhocQueryResponse getUnifiedResponse() throws RegistryException { AdhocQueryResponse response = null;// w w w .jav a 2 s . c om try { response = bu.queryFac.createAdhocQueryResponse(); RegistryObjectListType ebRegistryObjectListType = bu.rimFac.createRegistryObjectListType(); response.setRegistryObjectList(ebRegistryObjectListType); int maxTotalResultCount = -1; RegistryErrorList ebRegistryErrorList = null; Iterator<AdhocQueryResponse> i = responses.iterator(); while (i.hasNext()) { AdhocQueryResponse ebAdhocQueryResponse = i.next(); int totalResultCount = ebAdhocQueryResponse.getTotalResultCount().intValue(); if (totalResultCount > maxTotalResultCount) { maxTotalResultCount = totalResultCount; } if ((ebAdhocQueryResponse.getRegistryErrorList() != null) && (ebAdhocQueryResponse.getRegistryErrorList().getRegistryError().size() > 0)) { if (ebRegistryErrorList == null) { ebRegistryErrorList = bu.rsFac.createRegistryErrorList(); response.setRegistryErrorList(ebRegistryErrorList); } response.getRegistryErrorList().getRegistryError() .addAll(ebAdhocQueryResponse.getRegistryErrorList().getRegistryError()); } //Spec Issue: How to handle duplicate id across registries?? //Need to return one. Which one? The latest? Probably the one from current registry. //May require always querying current registry last since code below keeps replacing existing objects //with new ones that have same id. if (ebAdhocQueryResponse.getRegistryObjectList() != null) { IdentifiableComparator comparator = new IdentifiableComparator(); List<JAXBElement<? extends IdentifiableType>> unifiedObjects = response.getRegistryObjectList() .getIdentifiable(); List<JAXBElement<? extends IdentifiableType>> currentObjects = ebAdhocQueryResponse .getRegistryObjectList().getIdentifiable(); Collections.sort(unifiedObjects, comparator); //Remove duplicates. //unifiedObjects.removeAll(currentObjects) will not work as there is no comparator implemented for JAXB objects Iterator<JAXBElement<? extends IdentifiableType>> currentObjectsIter = currentObjects .iterator(); while (currentObjectsIter.hasNext()) { RegistryObjectType currentObject = (RegistryObjectType) currentObjectsIter.next() .getValue(); int index = Collections.binarySearch(unifiedObjects, currentObject, comparator); if (index >= 0) { unifiedObjects.remove(index); log.trace("Removing duplicate object returned by a previous registry: id=" + currentObject.getId() + " name=" + bu.getInternationalStringAsString(currentObject.getName())); } log.trace("Adding object returned by registry: id=" + currentObject.getId() + " name=" + bu.getInternationalStringAsString(currentObject.getName())); } //Add the currentObjects to unified objects unifiedObjects.addAll(currentObjects); } } if ((response.getRegistryErrorList() != null) && (response.getRegistryErrorList().getRegistryError().size() > 0)) { response.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Failure); } else { response.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success); } //Set iterative query related attributes response.setStartIndex(adhocQueryRequest.getStartIndex()); response.setTotalResultCount(BigInteger.valueOf(maxTotalResultCount)); } catch (JAXRException e) { throw new RegistryException(e); } return response; }
From source file:net.sourceforge.pmd.Report.java
/** * Adds a new rule violation to the report and notify the listeners. * * @param violation// w w w . j a v a 2 s .c om * the violation to add */ public void addRuleViolation(RuleViolation violation) { // NOPMD suppress int line = violation.getBeginLine(); if (linesToSuppress.containsKey(line)) { suppressedRuleViolations.add(new SuppressedViolation(violation, true, linesToSuppress.get(line))); return; } if (violation.isSuppressed()) { suppressedRuleViolations.add(new SuppressedViolation(violation, false, null)); return; } int index = Collections.binarySearch(violations, violation, RuleViolationComparator.INSTANCE); violations.add(index < 0 ? -index - 1 : index, violation); violationTree.addRuleViolation(violation); for (ThreadSafeReportListener listener : listeners) { listener.ruleViolationAdded(violation); } }
From source file:org.codehaus.enunciate.modules.objc.ObjCDeploymentModule.java
@Override public void doFreemarkerGenerate() throws IOException, TemplateException, EnunciateException { File genDir = getGenerateDir(); String label = getLabel() == null ? getEnunciate().getConfig() == null ? "enunciate" : getEnunciate().getConfig().getLabel() : getLabel();// w ww. j ava 2 s . co m if (!enunciate.isUpToDateWithSources(genDir)) { EnunciateFreemarkerModel model = getModel(); TreeMap<String, String> translations = new TreeMap<String, String>(); translations.put("id", this.translateIdTo); model.put("clientSimpleName", new ClientSimpleNameMethod(translations)); List<TypeDefinition> schemaTypes = new ArrayList<TypeDefinition>(); ExtensionDepthComparator comparator = new ExtensionDepthComparator(); for (SchemaInfo schemaInfo : model.getNamespacesToSchemas().values()) { for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) { int position = Collections.binarySearch(schemaTypes, typeDefinition, comparator); if (position < 0) { position = -position - 1; } schemaTypes.add(position, typeDefinition); } } model.put("schemaTypes", schemaTypes); NameForTypeDefinitionMethod nameForTypeDefinition = new NameForTypeDefinitionMethod( getTypeDefinitionNamePattern(), label, model.getNamespacesToPrefixes(), this.packageIdentifiers); model.put("nameForTypeDefinition", nameForTypeDefinition); model.put("nameForEnumConstant", new NameForEnumConstantMethod(getEnumConstantNamePattern(), label, model.getNamespacesToPrefixes(), this.packageIdentifiers)); TreeMap<String, String> conversions = new TreeMap<String, String>(); for (SchemaInfo schemaInfo : model.getNamespacesToSchemas().values()) { for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) { if (typeDefinition.isEnum()) { conversions.put(typeDefinition.getQualifiedName(), "enum " + nameForTypeDefinition.calculateName(typeDefinition)); } else { conversions.put(typeDefinition.getQualifiedName(), (String) nameForTypeDefinition.calculateName(typeDefinition)); } } } ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(conversions); model.put("classnameFor", classnameFor); model.put("functionIdentifierFor", new FunctionIdentifierForMethod(nameForTypeDefinition)); model.put("objcBaseName", label); model.put("separateCommonCode", isSeparateCommonCode()); model.put("findRootElement", new FindRootElementMethod()); model.put("referencedNamespaces", new ReferencedNamespacesMethod()); model.put("prefix", new PrefixMethod()); model.put("accessorOverridesAnother", new AccessorOverridesAnotherMethod()); debug("Generating the C data structures and (de)serialization functions..."); URL apiTemplate = getTemplateURL("api.fmt"); processTemplate(apiTemplate, model); } else { info("Skipping C code generation because everything appears up-to-date."); } ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "objc.client.library", "Objective C Client Library"); NamedFileArtifact sourceHeader = new NamedFileArtifact(getName(), "objc.client.h", new File(getGenerateDir(), label + ".h")); sourceHeader.setPublic(false); sourceHeader.setArtifactType(ArtifactType.sources); NamedFileArtifact sourceImpl = new NamedFileArtifact(getName(), "objc.client.m", new File(getGenerateDir(), label + ".m")); sourceImpl.setPublic(false); sourceImpl.setArtifactType(ArtifactType.sources); String description = readResource("library_description.fmt"); //read in the description from file artifactBundle.setDescription(description); artifactBundle.addArtifact(sourceHeader); artifactBundle.addArtifact(sourceImpl); if (isSeparateCommonCode()) { NamedFileArtifact commonSourceHeader = new NamedFileArtifact(getName(), "objc.common.client.h", new File(getGenerateDir(), "enunciate-common.h")); commonSourceHeader.setPublic(false); commonSourceHeader.setArtifactType(ArtifactType.sources); commonSourceHeader.setDescription("Common header needed for all projects."); NamedFileArtifact commonSourceImpl = new NamedFileArtifact(getName(), "objc.common.client.m", new File(getGenerateDir(), "enunciate-common.m")); commonSourceImpl.setPublic(false); commonSourceImpl.setArtifactType(ArtifactType.sources); commonSourceImpl.setDescription("Common implementation code needed for all projects."); artifactBundle.addArtifact(commonSourceHeader); artifactBundle.addArtifact(commonSourceImpl); } getEnunciate().addArtifact(artifactBundle); }
From source file:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java
/** * Put all the milestones into the project. Note, will skip * milestones with the same IID./*from ww w . jav a 2 s .com*/ * @return T=successfully set milestones, * F=API failure during attempt */ public boolean putAllMilestones() { if (!createApi()) { return false; } // The current list of milestones in gitlab, if any List<GitlabMilestone> currmslist = new ArrayList<GitlabMilestone>(); try { currmslist = api.getMilestones(project); } catch (IOException e) { } // sort it by IID Collections.sort(currmslist, new MilestoneOrderByIID()); // add, or skip, each milestone we have for (GitlabMilestone m : milestones) { Integer IID = m.getIid(); int currmslistind = -1; Integer newID = null; if (!currmslist.isEmpty()) { currmslistind = Collections.binarySearch(currmslist, m, new MilestoneOrderByIID()); newID = currmslist.get(currmslistind).getId(); } if (currmslistind >= 0) { // the milestone IID exists newMilestoneIDs.put(IID, newID); // store the IID vs. new ID mapping System.out.printf("Skipping existing project milestone: %s (IID=%d, ID=%d), in project %s\n", m.getTitle(), IID, newID, project.getName()); } else { // the milestone IID doesn't exist, so add it try { GitlabMilestone current = api.createMilestone(project.getId(), m); System.out.printf("Put project milestone: %s (IID=%d), into project %s\n", m.getTitle(), IID, project.getName()); newMilestoneIDs.put(IID, current.getId()); // store the IID vs. new ID mapping } catch (IOException e) { System.out.printf("Error while putting project milestone: %s (IID=%d), into project %s\n", m.getTitle(), IID, project.getName()); e.printStackTrace(); return false; } } } System.out.println("Final Milestone IID-to-newID mapping:"); for (Integer IID : newMilestoneIDs.keySet()) { System.out.printf("IID: %d\t = ID: %d \n", IID, newMilestoneIDs.get(IID)); } return true; }
From source file:com.projity.interval.ValueObjectForIntervalTable.java
private int findActiveIndex(long date) { ValueObjectForInterval find = createValueObject(date); int index = Collections.binarySearch(valueObjects, find, find); // find it if (index < 0) // binary search is weird. The element before is -index - 2 index = -index - 2; // gets index of element before return index; }
From source file:com.github.pockethub.ui.gist.GistFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (RESULT_OK != resultCode || data == null) return;// w w w . j a v a 2s .c o m switch (requestCode) { case COMMENT_CREATE: GithubComment comment = (GithubComment) data.getParcelableExtra(EXTRA_COMMENT); if (comments != null) { comments.add(comment); gist.comments = gist.comments + 1; updateList(gist, comments); } else refreshGist(); return; case COMMENT_EDIT: comment = (GithubComment) data.getParcelableExtra(EXTRA_COMMENT); if (comments != null && comment != null) { int position = Collections.binarySearch(comments, comment, new Comparator<GithubComment>() { public int compare(GithubComment lhs, GithubComment rhs) { return String.valueOf(lhs.id).compareTo(rhs.id); } }); imageGetter.removeFromCache(comment.id); comments.set(position, comment); updateList(gist, comments); } else refreshGist(); return; } super.onActivityResult(requestCode, resultCode, data); }
From source file:com.github.pockethub.android.ui.gist.GistFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (RESULT_OK != resultCode || data == null) { return;//from w ww .j a v a 2 s . co m } switch (requestCode) { case COMMENT_CREATE: GitHubComment comment = data.getParcelableExtra(EXTRA_COMMENT); if (comments != null) { comments.add(comment); gist = gist.toBuilder().comments(gist.comments() + 1).build(); updateList(gist, comments); } else { refreshGist(); } return; case COMMENT_EDIT: comment = data.getParcelableExtra(EXTRA_COMMENT); if (comments != null && comment != null) { int position = Collections.binarySearch(comments, comment, (lhs, rhs) -> Integer.valueOf(lhs.id()).compareTo(rhs.id())); imageGetter.removeFromCache(comment.id()); comments.set(position, comment); updateList(gist, comments); } else { refreshGist(); } return; } super.onActivityResult(requestCode, resultCode, data); }
From source file:com.panet.imeta.trans.steps.sort.SortRows.java
private Object[] getBuffer() throws KettleValueException { Object[] retval;/*from w ww . java 2 s . com*/ // Open all files at once and read one row from each file... if (data.files.size() > 0 && (data.dis.size() == 0 || data.fis.size() == 0)) { if (log.isBasic()) logBasic("Opening " + data.files.size() + " tmp-files..."); try { for (int f = 0; f < data.files.size() && !isStopped(); f++) { FileObject fileObject = (FileObject) data.files.get(f); String filename = KettleVFS.getFilename(fileObject); if (log.isDetailed()) logDetailed("Opening tmp-file: [" + filename + "]"); InputStream fi = KettleVFS.getInputStream(fileObject); DataInputStream di; data.fis.add(fi); if (data.compressFiles) { GZIPInputStream gzfi = new GZIPInputStream(new BufferedInputStream(fi)); di = new DataInputStream(gzfi); data.gzis.add(gzfi); } else { di = new DataInputStream(new BufferedInputStream(fi, 50000)); } data.dis.add(di); // How long is the buffer? int buffersize = data.bufferSizes.get(f); if (log.isDetailed()) logDetailed("[" + filename + "] expecting " + buffersize + " rows..."); if (buffersize > 0) { Object[] row = (Object[]) data.outputRowMeta.readData(di); data.rowbuffer.add(row); // new row from input stream data.tempRows.add(new RowTempFile(row, f)); } } // Sort the data row buffer Collections.sort(data.tempRows, data.comparator); } catch (Exception e) { logError("Error reading back tmp-files : " + e.toString()); logError(Const.getStackTracker(e)); } } if (data.files.size() == 0) { if (data.getBufferIndex < data.buffer.size()) { retval = (Object[]) data.buffer.get(data.getBufferIndex); data.getBufferIndex++; } else { retval = null; } } else { if (data.rowbuffer.size() == 0) { retval = null; } else { // We now have "filenr" rows waiting: which one is the smallest? // if (log.isRowLevel()) { for (int i = 0; i < data.rowbuffer.size() && !isStopped(); i++) { Object[] b = (Object[]) data.rowbuffer.get(i); logRowlevel("--BR#" + i + ": " + data.outputRowMeta.getString(b)); } } RowTempFile rowTempFile = data.tempRows.remove(0); retval = rowTempFile.row; int smallest = rowTempFile.fileNumber; // now get another Row for position smallest FileObject file = (FileObject) data.files.get(smallest); DataInputStream di = (DataInputStream) data.dis.get(smallest); InputStream fi = (InputStream) data.fis.get(smallest); GZIPInputStream gzfi = (data.compressFiles) ? (GZIPInputStream) data.gzis.get(smallest) : null; try { Object[] row2 = (Object[]) data.outputRowMeta.readData(di); RowTempFile extra = new RowTempFile(row2, smallest); int index = Collections.binarySearch(data.tempRows, extra, data.comparator); if (index < 0) { data.tempRows.add(index * (-1) - 1, extra); } else { data.tempRows.add(index, extra); } } catch (KettleFileException fe) // empty file or EOF mostly { try { di.close(); fi.close(); if (gzfi != null) gzfi.close(); file.delete(); } catch (IOException e) { logError("Unable to close/delete file #" + smallest + " --> " + file.toString()); setErrors(1); stopAll(); return null; } data.files.remove(smallest); data.dis.remove(smallest); data.fis.remove(smallest); if (gzfi != null) data.gzis.remove(smallest); // Also update all file numbers in in data.tempRows if they are larger than smallest. // for (RowTempFile rtf : data.tempRows) { if (rtf.fileNumber > smallest) rtf.fileNumber--; } } catch (SocketTimeoutException e) { throw new KettleValueException(e); // should never happen on local files } } } return retval; }