Example usage for java.util Collections binarySearch

List of usage examples for java.util Collections binarySearch

Introduction

In this page you can find the example usage for java.util Collections binarySearch.

Prototype

@SuppressWarnings("unchecked")
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 

Source Link

Document

Searches the specified list for the specified object using the binary search algorithm.

Usage

From source file:org.codehaus.enunciate.modules.php.PHPDeploymentModule.java

@Override
public void doFreemarkerGenerate() throws IOException, TemplateException, EnunciateException {
    File genDir = getGenerateDir();
    if (!enunciate.isUpToDateWithSources(genDir)) {
        EnunciateFreemarkerModel model = getModel();
        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;
                }//from  w ww .j  a va2 s  .  com
                schemaTypes.add(position, typeDefinition);
            }
        }
        model.put("schemaTypes", schemaTypes);
        model.put("packages2modules", this.packageToModuleConversions);
        ClientPackageForMethod moduleFor = new ClientPackageForMethod(this.packageToModuleConversions);
        moduleFor.setUseClientNameConversions(true);
        model.put("moduleFor", moduleFor);
        ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(this.packageToModuleConversions);
        classnameFor.setUseClientNameConversions(true);
        model.put("classnameFor", classnameFor);
        SimpleNameWithParamsMethod simpleNameFor = new SimpleNameWithParamsMethod(classnameFor);
        model.put("simpleNameFor", simpleNameFor);
        model.put("phpFileName", getSourceFileName());

        debug("Generating the PHP data classes...");
        URL apiTemplate = getTemplateURL("api.fmt");
        processTemplate(apiTemplate, model);
    } else {
        info("Skipping PHP code generation because everything appears up-to-date.");
    }

    ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "php.client.library",
            "PHP Client Library");
    artifactBundle.setPlatform("PHP");
    NamedFileArtifact sourceScript = new NamedFileArtifact(getName(), "php.client",
            new File(getGenerateDir(), getSourceFileName()));
    sourceScript.setArtifactType(ArtifactType.binaries); //binaries and sources are the same thing in php
    sourceScript.setPublic(false);
    String description = readResource("library_description.fmt"); //read in the description from file
    artifactBundle.setDescription(description);
    artifactBundle.addArtifact(sourceScript);
    getEnunciate().addArtifact(artifactBundle);
}

From source file:org.codehaus.enunciate.modules.ruby.RubyDeploymentModule.java

@Override
public void doFreemarkerGenerate() throws IOException, TemplateException, EnunciateException {
    File genDir = getGenerateDir();
    if (!enunciate.isUpToDateWithSources(genDir)) {
        EnunciateFreemarkerModel model = getModel();
        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;
                }//from w w w.  j ava  2  s. co m
                schemaTypes.add(position, typeDefinition);
            }
        }
        model.put("schemaTypes", schemaTypes);
        model.put("packages2modules", this.packageToModuleConversions);
        ClientPackageForMethod moduleFor = new ClientPackageForMethod(this.packageToModuleConversions);
        moduleFor.setUseClientNameConversions(true);
        model.put("moduleFor", moduleFor);
        ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(this.packageToModuleConversions);
        classnameFor.setUseClientNameConversions(true);
        model.put("classnameFor", classnameFor);
        SimpleNameWithParamsMethod simpleNameFor = new SimpleNameWithParamsMethod(classnameFor);
        model.put("simpleNameFor", simpleNameFor);
        model.put("rubyFileName", getSourceFileName());

        debug("Generating the Ruby data classes...");
        URL apiTemplate = getTemplateURL("api.fmt");
        processTemplate(apiTemplate, model);
    } else {
        info("Skipping Ruby code generation because everything appears up-to-date.");
    }

    ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "ruby.client.library",
            "Ruby Client Library");
    artifactBundle.setPlatform("Ruby");
    NamedFileArtifact sourceScript = new NamedFileArtifact(getName(), "ruby.client",
            new File(getGenerateDir(), getSourceFileName()));
    sourceScript.setArtifactType(ArtifactType.binaries); //binaries and sources are the same thing in ruby
    sourceScript.setPublic(false);
    String description = readResource("library_description.fmt"); //read in the description from file
    artifactBundle.setDescription(description);
    artifactBundle.addArtifact(sourceScript);
    getEnunciate().addArtifact(artifactBundle);
}

From source file:org.b3log.symphony.service.UserQueryService.java

/**
 * Gets usernames by the specified name prefix.
 *
 * @param namePrefix the specified name prefix
 * @return a list of usernames, for example      <pre>
 * [//from   w ww  .jav a2 s. co  m
 *     {
 *         "userName": "",
 *         "userAvatarURL": "",
 *     }, ....
 * ]
 * </pre>
 */
public List<JSONObject> getUserNamesByPrefix(final String namePrefix) {
    final JSONObject nameToSearch = new JSONObject();
    nameToSearch.put(User.USER_EMAIL, namePrefix);

    int index = Collections.binarySearch(userNames, nameToSearch, new Comparator<JSONObject>() {
        @Override
        public int compare(final JSONObject u1, final JSONObject u2) {
            String u1Name = u1.optString(User.USER_EMAIL);
            final String inputName = u2.optString(User.USER_EMAIL);

            if (u1Name.length() < inputName.length()) {
                return u1Name.compareTo(inputName);
            }

            u1Name = u1Name.substring(0, inputName.length());

            return u1Name.compareTo(inputName);
        }
    });

    final List<JSONObject> ret = new ArrayList<JSONObject>();

    if (index < 0) {
        return ret;
    }

    int start = index;
    int end = index;

    while (start > -1 && userNames.get(start).optString(User.USER_EMAIL).startsWith(namePrefix.toLowerCase())) {
        start--;
    }

    start++;

    if (start < index - 5) {
        end = start + 5;
    } else {
        while (end < userNames.size() && end < index + 5
                && userNames.get(end).optString(User.USER_EMAIL).startsWith(namePrefix.toLowerCase())) {
            end++;
        }
    }

    return userNames.subList(start, end);
}

From source file:SortedArrayList.java

/**
 * Add an Object and return it's index. It's prefered that a user use
 * <pre>//w ww.  j av a 2 s .  c o  m
 *  List list = new SortedArrayList();
 *  list.add(obj);
 *  int i = list.indexOf(obj);
 * </pre>
 * but if you need to insert an object and keep track of its index a call to
 * addObject() is faster. <font color="ff3333">NOTE: Duplicates of an object
 * will not be inserted. instead the index of the Object already in thelist will
 * be returned. </font>
 *
 * @param obj The object to be inserted.
 * @return index of the search key, if it is contained in the list;
 *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>.  The
 *         <i>insertion point</i> is defined as the point at which the
 *         key would be inserted into the list: the index of the first
 *         element greater than the key, or <tt>list.size()</tt>, if all
 *         elements in the list are less than the specified key.  Note
 *         that this guarantees that the return value will be &gt;= 0 if
 *         and only if the key is found.
 * @since Apr 29, 2003
 * @see java.util.Collections#binarySearch
 */
public int addObject(Object obj) {
    /*
     * Find the index at which to insert new item. The insertion index is
     * negative if the item doesn't already exist.
     */
    int insertionIndex = Collections.binarySearch(this, obj, comparator);

    // Do not add if obj is already in the list
    if (insertionIndex < 0) {
        /*
         *  Flip the insertion index sign
         *             insertionIndex = -insertionIndex - 1;
         *             super.add(insertionIndex, obj);
         * TODO - Verify with Brian but changed this
         * so that it does not modify the insertionIndex
         * that is returned.  If left as the way above,
         * the method will never return a negative number
         * so it will be as if the collection is changed
         */
        super.add((-insertionIndex - 1), obj);
    }

    return insertionIndex;
}

From source file:com.dulion.astatium.mesh.shredder.ContextManager.java

private void putNameTrie(String name, QName value) {
    String key = name.toLowerCase();
    List<QName> list = nameTrie.get(key);
    if (null == list) {
        list = new ArrayList<>();
        nameTrie.put(key, list);//from  w  w  w  .j  a v a  2  s .c o  m
        list.add(value);
    } else {
        int index = Collections.binarySearch(list, value, (first, second) -> {
            int result = first.getNamespaceURI().compareTo(second.getNamespaceURI());
            if (0 == result) {
                result = first.getLocalPart().compareTo(second.getLocalPart());
            }
            return result;
        });

        assert index < 0;

        list.add(-index - 1, value);
    }
}

From source file:savant.view.variation.VariationController.java

public synchronized List<VariantRecord> getData() {
    if (aggregateData == null) {
        int n = 0;
        int i = 0;
        List<String> names = new ArrayList<String>();
        for (VariantTrack t : tracks) {
            List<VariantRecord> trackData = rawData.get(i++);
            if (trackData != null) {
                if (aggregateData == null) {
                    aggregateData = new ArrayList<VariantRecord>(trackData.size());
                }/*from  www  .  j a  va2s . c  o  m*/
                // Slower process.  Traverse the list inserting data as we go.
                // It would might be more efficient to insert everything and sort,
                // but we have to allow for the possibility of having to munge together
                // two VariantRecords.
                for (VariantRecord rec : trackData) {
                    int index = Collections.binarySearch(aggregateData, rec, VARIANT_COMPARATOR);
                    if (index < 0) {
                        // Not found in list.  Insert it at the given location.
                        int insertionPos = -index - 1;
                        if (LOG.isDebugEnabled()) {
                            String before = insertionPos > 0 ? aggregateData.get(insertionPos - 1).toString()
                                    : "START";
                            String after = insertionPos < aggregateData.size()
                                    ? aggregateData.get(insertionPos).toString()
                                    : "END";

                            LOG.debug("Inserting " + rec + " after " + before + " and before " + after);
                        }
                        aggregateData.add(insertionPos, new PaddedVariantRecord(rec, n));
                    } else {
                        VariantRecord oldRec = aggregateData.get(index);
                        LOG.debug("Merging " + rec + " into " + oldRec + " padding "
                                + (n - oldRec.getParticipantCount()));
                        aggregateData.set(index,
                                new MergedVariantRecord(oldRec, rec, n - oldRec.getParticipantCount()));
                    }
                }
                names.addAll(Arrays.asList(((VariantDataSourceAdapter) t.getDataSource()).getParticipants()));
                n += t.getParticipantCount();
            }
        }
        participants = names.toArray(new String[0]);
    }
    return aggregateData;
}

From source file:com.webcohesion.enunciate.modules.objc_client.ObjCXMLClientModule.java

@Override
public void call(EnunciateContext context) {
    if (this.jaxbModule == null || this.jaxbModule.getJaxbContext() == null
            || this.jaxbModule.getJaxbContext().getSchemas().isEmpty()) {
        info("No JAXB XML data types: Objective-C XML client will not be generated.");
        return;//from   www  .  ja v a  2s  .co m
    }

    if (usesUnmappableElements()) {
        warn("Web service API makes use of elements that cannot be handled by the Objective-C XML client. Objective-C XML client will not be generated.");
        return;
    }

    List<String> namingConflicts = JAXBErrors
            .findConflictingAccessorNamingErrors(this.jaxbModule.getJaxbContext());
    if (namingConflicts != null && !namingConflicts.isEmpty()) {
        error("JAXB naming conflicts have been found:");
        for (String namingConflict : namingConflicts) {
            error(namingConflict);
        }
        error("These naming conflicts are often between the field and it's associated property, in which case you need to use one or two of the following strategies to avoid the conflicts:");
        error("1. Explicitly exclude one or the other.");
        error("2. Put the annotations on the property instead of the field.");
        error("3. Tell JAXB to use a different process for detecting accessors using the @XmlAccessorType annotation.");
        throw new EnunciateException("JAXB naming conflicts detected.");
    }

    EnunciateJaxbContext jaxbContext = this.jaxbModule.getJaxbContext();

    Map<String, String> packageIdentifiers = getPackageIdentifiers();

    String packageIdentifierPattern = getPackageIdentifierPattern();
    if ((packageIdentifierPattern != null)) {
        for (SchemaInfo schemaInfo : jaxbContext.getSchemas().values()) {
            for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) {
                String pckg = typeDefinition.getPackage().getQualifiedName().toString();
                if (!packageIdentifiers.containsKey(pckg)) {
                    try {
                        packageIdentifiers.put(pckg,
                                String.format(packageIdentifierPattern, pckg.split("\\.", 9)));
                    } catch (IllegalFormatException e) {
                        warn("Unable to format package %s with format pattern %s (%s)", pckg,
                                packageIdentifierPattern, e.getMessage());
                    }
                }
            }
        }
    }

    Map<String, Object> model = new HashMap<String, Object>();

    String slug = getSlug();

    model.put("slug", slug);

    File srcDir = getSourceDir();

    TreeMap<String, String> translations = new TreeMap<String, String>();
    translations.put("id", getTranslateIdTo());
    model.put("clientSimpleName", new ClientSimpleNameMethod(translations));

    List<TypeDefinition> schemaTypes = new ArrayList<TypeDefinition>();
    ExtensionDepthComparator comparator = new ExtensionDepthComparator();
    for (SchemaInfo schemaInfo : jaxbContext.getSchemas().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(), slug, jaxbContext.getNamespacePrefixes(), packageIdentifiers);
    model.put("nameForTypeDefinition", nameForTypeDefinition);
    model.put("nameForEnumConstant", new NameForEnumConstantMethod(getEnumConstantNamePattern(), slug,
            jaxbContext.getNamespacePrefixes(), packageIdentifiers));
    TreeMap<String, String> conversions = new TreeMap<String, String>();
    for (SchemaInfo schemaInfo : jaxbContext.getSchemas().values()) {
        for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) {
            if (typeDefinition.isEnum()) {
                conversions.put(typeDefinition.getQualifiedName().toString(),
                        "enum " + nameForTypeDefinition.calculateName(typeDefinition));
            } else {
                conversions.put(typeDefinition.getQualifiedName().toString(),
                        (String) nameForTypeDefinition.calculateName(typeDefinition));
            }
        }
    }
    ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(conversions, jaxbContext);
    model.put("classnameFor", classnameFor);
    model.put("functionIdentifierFor", new FunctionIdentifierForMethod(nameForTypeDefinition, jaxbContext));
    model.put("objcBaseName", slug);
    model.put("separateCommonCode", isSeparateCommonCode());
    model.put("findRootElement", new FindRootElementMethod(jaxbContext));
    model.put("referencedNamespaces", new ReferencedNamespacesMethod(jaxbContext));
    model.put("prefix", new PrefixMethod(jaxbContext.getNamespacePrefixes()));
    model.put("accessorOverridesAnother", new AccessorOverridesAnotherMethod());
    model.put("file", new FileDirective(srcDir, this.enunciate.getLogger()));

    Set<String> facetIncludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetIncludes());
    facetIncludes.addAll(getFacetIncludes());
    Set<String> facetExcludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetExcludes());
    facetExcludes.addAll(getFacetExcludes());
    FacetFilter facetFilter = new FacetFilter(facetIncludes, facetExcludes);

    model.put("isFacetExcluded", new IsFacetExcludedMethod(facetFilter));

    if (!isUpToDateWithSources(srcDir)) {
        debug("Generating the C data structures and (de)serialization functions...");
        URL apiTemplate = getTemplateURL("api.fmt");
        try {
            processTemplate(apiTemplate, model);
        } catch (IOException e) {
            throw new EnunciateException(e);
        } catch (TemplateException e) {
            throw new EnunciateException(e);
        }
    } else {
        info("Skipping C code generation because everything appears up-to-date.");
    }

    ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "objc.client.library",
            "Objective C Client Library");
    FileArtifact sourceHeader = new FileArtifact(getName(), "objc.client.h", new File(srcDir, slug + ".h"));
    sourceHeader.setPublic(false);
    sourceHeader.setArtifactType(ArtifactType.sources);
    FileArtifact sourceImpl = new FileArtifact(getName(), "objc.client.m", new File(srcDir, slug + ".m"));
    sourceImpl.setPublic(false);
    sourceImpl.setArtifactType(ArtifactType.sources);
    String description = readResource("library_description.fmt", model, nameForTypeDefinition); //read in the description from file
    artifactBundle.setDescription(description);
    artifactBundle.addArtifact(sourceHeader);
    artifactBundle.addArtifact(sourceImpl);
    if (isSeparateCommonCode()) {
        FileArtifact commonSourceHeader = new FileArtifact(getName(), "objc.common.client.h",
                new File(srcDir, "enunciate-common.h"));
        commonSourceHeader.setPublic(false);
        commonSourceHeader.setArtifactType(ArtifactType.sources);
        commonSourceHeader.setDescription("Common header needed for all projects.");
        FileArtifact commonSourceImpl = new FileArtifact(getName(), "objc.common.client.m",
                new File(srcDir, "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);
    }
    this.enunciate.addArtifact(artifactBundle);
}

From source file:org.apache.usergrid.persistence.geo.GeoIndexSearcher.java

/**
 * Perform a search from the center. The corresponding entities returned must be >= minDistance(inclusive) and <
 * maxDistance (exclusive)/*from  w  w w .  ja va2 s. c om*/
 *
 * @param maxResults The maximum number of results to include
 * @param minDistance The minimum distance (inclusive)
 * @param maxDistance The maximum distance (exclusive)
 * @param entityClass The entity class
 * @param baseQuery The base query
 * @param queryEngine The query engine to use
 * @param maxGeocellResolution The max resolution to use when searching
 */
public final SearchResults proximitySearch(final EntityLocationRef minMatch, final List<String> geoCells,
        Point searchPoint, String propertyName, double minDistance, double maxDistance, final int maxResults)
        throws Exception {

    List<EntityLocationRef> entityLocations = new ArrayList<EntityLocationRef>(maxResults);

    List<String> curGeocells = new ArrayList<String>();
    String curContainingGeocell = null;

    // we have some cells used from last time, re-use them
    if (geoCells != null && geoCells.size() > 0) {
        curGeocells.addAll(geoCells);
        curContainingGeocell = geoCells.get(0);
    }
    // start at the bottom
    else {

        /*
         * The currently-being-searched geocells. NOTES: Start with max possible.
         * Must always be of the same resolution. Must always form a rectangular
         * region. One of these must be equal to the cur_containing_geocell.
         */
        curContainingGeocell = GeocellUtils.compute(searchPoint, MAX_GEOCELL_RESOLUTION);
        curGeocells.add(curContainingGeocell);
    }

    if (minMatch != null) {
        minMatch.calcDistance(searchPoint);
    }
    // Set of already searched cells
    Set<String> searchedCells = new HashSet<String>();

    List<String> curGeocellsUnique = null;

    double closestPossibleNextResultDist = 0;

    /*
     * Assumes both a and b are lists of (entity, dist) tuples, *sorted by
     * dist*. NOTE: This is an in-place merge, and there are guaranteed no
     * duplicates in the resulting list.
     */

    int noDirection[] = { 0, 0 };
    List<Tuple<int[], Double>> sortedEdgesDistances = Arrays.asList(new Tuple<int[], Double>(noDirection, 0d));
    boolean done = false;
    UUID lastReturned = null;

    while (!curGeocells.isEmpty() && entityLocations.size() < maxResults) {
        closestPossibleNextResultDist = sortedEdgesDistances.get(0).getSecond();
        if (maxDistance > 0 && closestPossibleNextResultDist > maxDistance) {
            break;
        }

        Set<String> curTempUnique = new HashSet<String>(curGeocells);
        curTempUnique.removeAll(searchedCells);
        curGeocellsUnique = new ArrayList<String>(curTempUnique);

        Set<HColumn<ByteBuffer, ByteBuffer>> queryResults = null;

        lastReturned = null;

        // we need to keep searching everything in our tiles until we don't get
        // any more results, then we'll have the closest points and can move on
        // do the next tiles
        do {
            queryResults = doSearch(curGeocellsUnique, lastReturned, searchPoint, propertyName, MAX_FETCH_SIZE);

            if (logger.isDebugEnabled()) {
                logger.debug("fetch complete for: {}", StringUtils.join(curGeocellsUnique, ", "));
            }

            searchedCells.addAll(curGeocells);

            // Begin storing distance from the search result entity to the
            // search center along with the search result itself, in a tuple.

            // Merge new_results into results
            for (HColumn<ByteBuffer, ByteBuffer> column : queryResults) {

                DynamicComposite composite = DynamicComposite.fromByteBuffer(column.getName());

                UUID uuid = composite.get(0, ue);

                lastReturned = uuid;

                String type = composite.get(1, se);
                UUID timestampUuid = composite.get(2, ue);
                composite = DynamicComposite.fromByteBuffer(column.getValue());
                Double latitude = composite.get(0, de);
                Double longitude = composite.get(1, de);

                EntityLocationRef entityLocation = new EntityLocationRef(type, uuid, timestampUuid, latitude,
                        longitude);

                double distance = entityLocation.calcDistance(searchPoint);

                // discard, it's too close or too far, of closer than the minimum we
                // should match, skip it
                if (distance < minDistance || (maxDistance != 0 && distance > maxDistance)
                        || (minMatch != null && COMP.compare(entityLocation, minMatch) <= 0)) {
                    continue;
                }

                int index = Collections.binarySearch(entityLocations, entityLocation, COMP);

                // already in the index
                if (index > -1) {
                    continue;
                }

                // set the insert index
                index = (index + 1) * -1;

                // no point in adding it
                if (index >= maxResults) {
                    continue;
                }

                // results.add(index, entity);
                // distances.add(index, distance);
                entityLocations.add(index, entityLocation);

                /**
                 * Discard an additional entries as we iterate to avoid holding them
                 * all in ram
                 */
                while (entityLocations.size() > maxResults) {
                    entityLocations.remove(entityLocations.size() - 1);
                }
            }
        } while (queryResults != null && queryResults.size() == MAX_FETCH_SIZE);

        /**
         * We've searched everything and have a full set, we want to return the
         * "current" tiles to search next time for the cursor, since cass could
         * contain more results
         */
        if (done || entityLocations.size() == maxResults) {
            break;
        }

        sortedEdgesDistances = GeocellUtils.distanceSortedEdges(curGeocells, searchPoint);

        if (queryResults.size() == 0 || curGeocells.size() == 4) {
            /*
             * Either no results (in which case we optimize by not looking at
             * adjacents, go straight to the parent) or we've searched 4 adjacent
             * geocells, in which case we should now search the parents of those
             * geocells.
             */
            curContainingGeocell = curContainingGeocell.substring(0,
                    Math.max(curContainingGeocell.length() - 1, 0));
            if (curContainingGeocell.length() == 0) {
                // final check - top level tiles
                curGeocells.clear();
                String[] items = "0123456789abcdef".split("(?!^)");
                Collections.addAll(curGeocells, items);
                done = true;
            } else {
                List<String> oldCurGeocells = new ArrayList<String>(curGeocells);
                curGeocells.clear();
                for (String cell : oldCurGeocells) {
                    if (cell.length() > 0) {
                        String newCell = cell.substring(0, cell.length() - 1);
                        if (!curGeocells.contains(newCell)) {
                            curGeocells.add(newCell);
                        }
                    }
                }
            }
        } else if (curGeocells.size() == 1) {
            // Get adjacent in one direction.
            // TODO(romannurik): Watch for +/- 90 degree latitude edge case
            // geocells.
            for (Tuple<int[], Double> sortedEdgesDistance : sortedEdgesDistances) {

                int nearestEdge[] = sortedEdgesDistance.getFirst();
                String edge = GeocellUtils.adjacent(curGeocells.get(0), nearestEdge);

                // we're at the edge of the world, search in a different direction
                if (edge == null) {
                    continue;
                }

                curGeocells.add(edge);
                break;
            }
        } else if (curGeocells.size() == 2) {
            // Get adjacents in perpendicular direction.
            int nearestEdge[] = GeocellUtils
                    .distanceSortedEdges(Arrays.asList(curContainingGeocell), searchPoint).get(0).getFirst();
            int[] perpendicularNearestEdge = { 0, 0 };
            if (nearestEdge[0] == 0) {
                // Was vertical, perpendicular is horizontal.
                for (Tuple<int[], Double> edgeDistance : sortedEdgesDistances) {
                    if (edgeDistance.getFirst()[0] != 0) {
                        perpendicularNearestEdge = edgeDistance.getFirst();
                        break;
                    }
                }
            } else {
                // Was horizontal, perpendicular is vertical.
                for (Tuple<int[], Double> edgeDistance : sortedEdgesDistances) {
                    if (edgeDistance.getFirst()[0] == 0) {
                        perpendicularNearestEdge = edgeDistance.getFirst();
                        break;
                    }
                }
            }
            List<String> tempCells = new ArrayList<String>();
            for (String cell : curGeocells) {
                tempCells.add(GeocellUtils.adjacent(cell, perpendicularNearestEdge));
            }
            curGeocells.addAll(tempCells);
        }

        logger.debug("{} results found.", entityLocations.size());
    }

    // now we have our final sets, construct the results

    return new SearchResults(entityLocations, curGeocells);
}

From source file:org.uncommons.reportng.HTMLReporter.java

/**
 * Group test methods by class and sort alphabetically.
 */// w w w  .  jav  a2 s. co m
private SortedMap<IClass, List<ITestResult>> sortByTestClass(IResultMap results) {
    SortedMap<IClass, List<ITestResult>> sortedResults = new TreeMap<IClass, List<ITestResult>>(
            CLASS_COMPARATOR);
    for (ITestResult result : results.getAllResults()) {
        List<ITestResult> resultsForClass = sortedResults.get(result.getTestClass());
        if (resultsForClass == null) {
            resultsForClass = new ArrayList<ITestResult>();
            sortedResults.put(result.getTestClass(), resultsForClass);
        }
        int index = Collections.binarySearch(resultsForClass, result, RESULT_COMPARATOR);
        if (index < 0) {
            index = Math.abs(index + 1);
        }
        resultsForClass.add(index, result);
    }
    return sortedResults;
}

From source file:com.webcohesion.enunciate.modules.objc_json_client.ObjCJSONClientModule.java

@Override
public void call(EnunciateContext context) {
    if (this.jaxbModule == null || this.jaxbModule.getJaxbContext() == null
            || this.jaxbModule.getJaxbContext().getSchemas().isEmpty()) {
        info("No JAXB XML data types: Objective-C JSON client will not be generated.");
        return;/*from w  w w. ja  va  2  s  .  c  om*/
    }

    if (usesUnmappableElements()) {
        warn("Web service API makes use of elements that cannot be handled by the Objective-C XML client. Objective-C XML client will not be generated.");
        return;
    }

    List<String> namingConflicts = JAXBCodeErrors
            .findConflictingAccessorNamingErrors(this.jaxbModule.getJaxbContext());
    if (namingConflicts != null && !namingConflicts.isEmpty()) {
        error("JAXB naming conflicts have been found:");
        for (String namingConflict : namingConflicts) {
            error(namingConflict);
        }
        error("These naming conflicts are often between the field and it's associated property, in which case you need to use one or two of the following strategies to avoid the conflicts:");
        error("1. Explicitly exclude one or the other.");
        error("2. Put the annotations on the property instead of the field.");
        error("3. Tell JAXB to use a different process for detecting accessors using the @XmlAccessorType annotation.");
        throw new EnunciateException("JAXB naming conflicts detected.");
    }

    EnunciateJaxbContext jaxbContext = this.jaxbModule.getJaxbContext();

    Map<String, String> packageIdentifiers = getPackageIdentifiers();

    String packageIdentifierPattern = getPackageIdentifierPattern();
    if ((packageIdentifierPattern != null)) {
        for (SchemaInfo schemaInfo : jaxbContext.getSchemas().values()) {
            for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) {
                String pckg = typeDefinition.getPackage().getQualifiedName().toString();
                if (!packageIdentifiers.containsKey(pckg)) {
                    try {
                        packageIdentifiers.put(pckg,
                                String.format(packageIdentifierPattern, pckg.split("\\.", 9)));
                    } catch (IllegalFormatException e) {
                        warn("Unable to format package %s with format pattern %s (%s)", pckg,
                                packageIdentifierPattern, e.getMessage());
                    }
                }
            }
        }
    }

    Map<String, Object> model = new HashMap<String, Object>();

    String slug = getSlug();
    final String objectBaseName = slug + "_objc_json_client";

    model.put("slug", slug);

    File srcDir = getSourceDir();

    // TreeMap<String, String> translations = new TreeMap<String, String>();
    // translations.put("id", getTranslateIdTo());
    model.put("clientSimpleName", new ClientSimpleNameMethod());

    List<TypeDefinition> schemaTypes = new ArrayList<TypeDefinition>();
    ExtensionDepthComparator comparator = new ExtensionDepthComparator();
    for (SchemaInfo schemaInfo : jaxbContext.getSchemas().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(), slug, jaxbContext.getNamespacePrefixes(), packageIdentifiers);
    model.put("nameForTypeDefinition", nameForTypeDefinition);
    model.put("nameForEnumConstant", new NameForEnumConstantMethod(getEnumConstantNamePattern(), slug,
            jaxbContext.getNamespacePrefixes(), packageIdentifiers));
    TreeMap<String, String> conversions = new TreeMap<String, String>();
    for (SchemaInfo schemaInfo : jaxbContext.getSchemas().values()) {
        for (TypeDefinition typeDefinition : schemaInfo.getTypeDefinitions()) {
            if (typeDefinition.isEnum()) {
                // conversions.put(typeDefinition.getQualifiedName().toString(), "enum
                // " + nameForTypeDefinition.calculateName(typeDefinition));
                conversions.put(typeDefinition.getQualifiedName().toString(), "NSString");
            } else {
                conversions.put(typeDefinition.getQualifiedName().toString(),
                        (String) nameForTypeDefinition.calculateName(typeDefinition));
            }
        }
    }
    ClientClassnameForMethod classnameFor = new ClientClassnameForMethod(conversions, jaxbContext);
    model.put("classnameFor", classnameFor);
    model.put("memoryAccessTypeFor", new MemoryAccessTypeMethod());
    model.put("getFieldNameTransfer", new GetFieldNameTransferMethod());
    model.put("isAccessorPrimitive", new IsAccessorPrimitiveMethod());
    model.put("getEnumVariablesFor", new GetEnumVariablesMethod(jaxbContext));
    model.put("functionIdentifierFor", new FunctionIdentifierForMethod(nameForTypeDefinition, jaxbContext));
    model.put("objcBaseName", objectBaseName);
    model.put("separateCommonCode", isSeparateCommonCode());
    model.put("findRootElement", new FindRootElementMethod(jaxbContext));
    model.put("referencedNamespaces", new ReferencedNamespacesMethod(jaxbContext));
    model.put("prefix", new PrefixMethod(jaxbContext.getNamespacePrefixes()));
    model.put("accessorOverridesAnother", new AccessorOverridesAnotherMethod());
    model.put("file", new FileDirective(srcDir, this.enunciate.getLogger()));

    Set<String> facetIncludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetIncludes());
    facetIncludes.addAll(getFacetIncludes());
    Set<String> facetExcludes = new TreeSet<String>(this.enunciate.getConfiguration().getFacetExcludes());
    facetExcludes.addAll(getFacetExcludes());
    FacetFilter facetFilter = new FacetFilter(facetIncludes, facetExcludes);

    model.put("isFacetExcluded", new IsFacetExcludedMethod(facetFilter));

    if (!isUpToDateWithSources(srcDir)) {
        debug("Generating the C data structures and (de)serialization functions...");
        URL apiTemplate = getTemplateURL("api.fmt");
        try {
            processTemplate(apiTemplate, model);
        } catch (IOException e) {
            throw new EnunciateException(e);
        } catch (TemplateException e) {
            throw new EnunciateException(e);
        }
    } else {
        info("Skipping C code generation because everything appears up-to-date.");
    }

    ClientLibraryArtifact artifactBundle = new ClientLibraryArtifact(getName(), "objc.json.client.library",
            "Objective C JSON Client Library");
    FileArtifact sourceHeader = new FileArtifact(getName(), "objc.json.client.h",
            new File(srcDir, objectBaseName + ".h"));
    sourceHeader.setPublic(false);
    sourceHeader.setArtifactType(ArtifactType.sources);
    FileArtifact sourceImpl = new FileArtifact(getName(), "objc.json.client.m",
            new File(srcDir, objectBaseName + ".m"));
    sourceImpl.setPublic(false);
    sourceImpl.setArtifactType(ArtifactType.sources);
    String description = readResource("library_description.fmt", model, nameForTypeDefinition);
    artifactBundle.setDescription(description);
    artifactBundle.addArtifact(sourceHeader);
    artifactBundle.addArtifact(sourceImpl);
    if (isSeparateCommonCode()) {
        // FileArtifact commonSourceHeader = new FileArtifact(getName(),
        // "objc.json.common.client.h",
        // new File(srcDir, "enunciate-json-common.h"));
        // commonSourceHeader.setPublic(false);
        // commonSourceHeader.setArtifactType(ArtifactType.sources);
        // commonSourceHeader.setDescription("Common header needed for all
        // projects.");
        // FileArtifact commonSourceImpl = new FileArtifact(getName(),
        // "objc.json.common.client.m",
        // new File(srcDir, "enunciate-json-common.m"));
        // commonSourceImpl.setPublic(false);
        // commonSourceImpl.setArtifactType(ArtifactType.sources);
        // commonSourceImpl.setDescription("Common implementation code needed for
        // all projects.");
        // artifactBundle.addArtifact(commonSourceHeader);
        // artifactBundle.addArtifact(commonSourceImpl);
    }
    this.enunciate.addArtifact(artifactBundle);
}