Example usage for java.util TreeSet size

List of usage examples for java.util TreeSet size

Introduction

In this page you can find the example usage for java.util TreeSet size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.gvsig.framework.web.service.impl.OGCInfoServiceImpl.java

/**
 * Recursive method to add list layers get by the WMSServer into tree list
 *
 * @param children Represents child layers of parentNode
 * @param tree Tree of layers/* w  w  w.  j ava 2  s .c  o  m*/
 * @param crs CRS that must have the layers to add these to the tree
 * @param parentNode Represents parent layer
 * @param layersMap Represents the map that contains the layers obtained
 * @param isCalledByWizard Indicate if the method is called by the wizard
 */
private void generateWMSChildrenNodes(ArrayList<WMSLayer> children, List<TreeNode> tree,
        TreeSet<String> listCrs, TreeNode parentNode,
        Map<String, org.gvsig.framework.web.ogc.WMSLayer> layersMap, WMSInfo wmsInfo) {
    for (WMSLayer layerChild : children) {
        // get crs (srs) (belong to layer)
        Vector crsVector = layerChild.getAllSrs();
        // Only get the layers with have crs parameter or if crs is null
        if (listCrs.isEmpty() || !Collections.disjoint(crsVector, listCrs)) {

            ArrayList<WMSLayer> layerChildChildren = layerChild.getChildren();
            TreeNode layerChildNode = new TreeNode(layerChild.getName());
            layerChildNode.setTitle(layerChild.getTitle());

            // Get the children and their information
            if (layerChildChildren.isEmpty()) {
                layerChildNode.setFolder(false);

                // Add layer to layer map
                org.gvsig.framework.web.ogc.WMSLayer wmsLayer = new org.gvsig.framework.web.ogc.WMSLayer();
                TreeSet<String> crsSet = new TreeSet<String>();
                crsSet.addAll(layerChild.getAllSrs());
                wmsLayer.setCrs(crsSet);
                List<WMSStyle> wmsStyles = createListWMSStyles(layerChild.getStyles());
                wmsLayer.setStyles(wmsStyles);
                wmsLayer.setTitle(layerChild.getTitle());
                wmsLayer.setName(layerChild.getName());
                layersMap.put(layerChild.getName(), wmsLayer);

                // add to wmsinfo the layers supported by this layer
                TreeSet<String> crsSupported = wmsInfo.getCrsSupported();
                crsSupported.addAll(layerChild.getAllSrs());
                wmsInfo.setCrsSupported(crsSupported);

                //create one child for each crs of the layer
                if (listCrs.isEmpty() || listCrs.size() > 1) {
                    for (String crs : crsSet) {
                        if (StringUtils.isNotEmpty(crs) && (listCrs.isEmpty() || listCrs.contains(crs))) {
                            TreeNode crsNode = new TreeNode(crs);
                            crsNode.setHideCheckbox(true);
                            crsNode.setUnselectable(true);
                            crsNode.setIconclass(" ");
                            layerChildNode.addChild(crsNode);
                        }
                    }
                }
            } else {
                layerChildNode.setFolder(true);
                layerChildNode.setExpanded(true);
                generateWMSChildrenNodes(layerChildChildren, tree, listCrs, layerChildNode, layersMap, wmsInfo);
            }
            parentNode.addChild(layerChildNode);
        }
    }

}

From source file:com.appeligo.search.actions.SearchResults.java

public List<SearchResult> getSearchResults(int startIndex) {

    initializeStatics();//from   w  w  w .  j av  a  2 s  .co  m

    hasMoreResults = false;
    try {
        IndexSearcher searcher = null;

        try {
            searcher = newIndexSearcher();
            IndexReader reader = searcher.getIndexReader();

            Query luceneQuery = generateLuceneQuery(searcher);
            luceneQuery = luceneQuery.rewrite(reader);
            Hits hits = searcher.search(luceneQuery);

            usingSuggestedQuery = false;
            suggestedQuery = null;
            if ((didYouMeanParser != null)
                    && ((hits.length() < minimumHits) || (calcScore(searcher, getQuery()) < minimumScore))) {
                if (log.isDebugEnabled()) {
                    log.debug("Need to suggest because either num hits " + hits.length() + " < " + minimumHits
                            + "\n or top hit score " + (hits.length() > 0 ? hits.score(0) : "[NO HITS]") + " < "
                            + minimumScore);
                }
                IndexSearcher compositeSearcher = new IndexSearcher(compositeIndexLocation);
                try {
                    log.debug("calling suggest() with query=" + getQuery() + " and composite index from "
                            + compositeIndexLocation);
                    //Query didYouMean = didYouMeanParser.suggest(getQuery(), compositeSearcher.getIndexReader());
                    Query suggestedQueries[] = didYouMeanParser.getSuggestions(getQuery(),
                            compositeSearcher.getIndexReader());
                    TreeSet<Suggestion> suggestions = new TreeSet<Suggestion>();

                    if (suggestedQueries != null) {
                        for (int i = 0; i < suggestedQueries.length; i++) {
                            log.debug("trying suggested query: " + suggestedQueries[i].toString(defaultField));
                            String suggestedQueryString = suggestedQueries[i].toString(defaultField);
                            String constrainedQueryString = suggestedQueryString;
                            if (constrainedQueryString.indexOf('"') < 0
                                    && constrainedQueryString.indexOf('\'') < 0) {
                                constrainedQueryString = "\"" + constrainedQueryString + "\"~5"; // proximity/distance query (within 5 words of each other)
                            }
                            Query suggestedLuceneQuery = generateLuceneQuery(constrainedQueryString, searcher);
                            suggestedLuceneQuery = suggestedLuceneQuery.rewrite(reader);
                            Hits suggestedHits = searcher.search(suggestedLuceneQuery);

                            float score = calcScore(suggestedQueryString, suggestedHits);

                            log.debug("=========================================");
                            log.debug("SCORE = " + score);
                            log.debug("=========================================");

                            suggestions.add(
                                    new Suggestion(suggestedQueryString, suggestedLuceneQuery, suggestedHits,
                                            score, ((i == 0) ? didYouMeanParser.includesOriginal() : false)));
                            log.debug("hits=" + suggestedHits.length() + ", score=" + score);
                        }
                    }

                    Suggestion best = null;
                    if (suggestions.size() > 0) {
                        best = suggestions.last();
                    }

                    if (best != null && !best.isOriginal()) {
                        suggestedQuery = best.getQueryString();
                        if (suggestedQuery != null && suggestedQuery.indexOf('+') >= 0
                                && getQuery().indexOf('+') < 0) {
                            suggestedQuery = suggestedQuery.replaceAll("\\+", "");
                        }
                        if (hits.length() == 0) {
                            if (best.getHits().length() > 0) {
                                // Requery probably required because we added proximity before
                                String suggestedQueryString = best.getQueryString();
                                luceneQuery = generateLuceneQuery(suggestedQueryString, searcher);
                                luceneQuery = luceneQuery.rewrite(reader);
                                hits = searcher.search(luceneQuery);
                                //hits = best.getHits();
                                //luceneQuery = best.getLuceneQuery();
                                usingSuggestedQuery = true;
                            }
                        }
                        log.debug("DidYouMeanParser suggested " + suggestedQuery);
                    } else {
                        if (best != null && best.isOriginal()) {
                            log.debug("The suggestion was the original query after all");
                        }
                        log.debug("DidYouMeanParser did not suggest anything");
                    }
                } finally {
                    compositeSearcher.close();
                }
            }
            /*
            if (hits.length() == 0 && suggestedQuery != null) {
            // If we didn't find anything at all, go ahead and show them what the suggested query
            // will give them
            Query suggestedLuceneQuery = generateLuceneQuery(suggestedQuery, searcher);
            suggestedLuceneQuery = suggestedLuceneQuery.rewrite(reader);
               Hits suggestedHits = searcher.search(suggestedLuceneQuery);
               if (suggestedHits.length() > 0) {
             hits = suggestedHits;
             luceneQuery = suggestedLuceneQuery;
             usingSuggestedQuery = true;
               }
            }
               */
            totalHits = hits.length();
            //Get the genere matches:
            try {
                BitSetFacetHitCounter facetHitCounter = new BitSetFacetHitCounter();
                facetHitCounter.setSearcher(searcher);
                String baseQueryString = (isUsingSuggestedQuery() ? suggestedQuery : query);
                String quotedQueryString = baseQueryString;
                if (quotedQueryString.indexOf('"') == -1 && quotedQueryString.indexOf(' ') > -1) {
                    quotedQueryString = "\"" + quotedQueryString + "\"";
                }
                facetHitCounter.setBaseQuery(luceneQuery, baseQueryString);

                List<HitCount> subQueries = new ArrayList<HitCount>();
                for (Map.Entry<String, Query> entry : genreQueries.entrySet()) {
                    subQueries.add(
                            new HitCount(entry.getKey(), entry.getValue(), entry.getValue().toString(), 0));
                }
                facetHitCounter.setSubQueries(subQueries);
                genreCounts = facetHitCounter.getFacetHitCounts(true);

                whatMatchedCounts = new ArrayList<HitCount>();
                whatMatchedCounts
                        .add(new HitCount("Title", getFieldQuery(baseQueryString, "programTitle", searcher),
                                "programTitle:" + quotedQueryString, 0));
                whatMatchedCounts.add(
                        new HitCount("Episode Title", getFieldQuery(baseQueryString, "episodeTitle", searcher),
                                "episodeTitle:" + quotedQueryString, 0));
                whatMatchedCounts.add(
                        new HitCount("Description", getFieldQuery(baseQueryString, "description", searcher),
                                "description:" + quotedQueryString, 0));
                whatMatchedCounts.add(new HitCount("Content", getFieldQuery(baseQueryString, "text", searcher),
                        "text:" + quotedQueryString, 0));
                whatMatchedCounts
                        .add(new HitCount("Credits", getFieldQuery(baseQueryString, "credits", searcher),
                                "credits:" + quotedQueryString, 0));
                facetHitCounter.setSubQueries(whatMatchedCounts);
                whatMatchedCounts = facetHitCounter.getFacetHitCounts(true);

                //Program Count  -- Not sure if there is a better way to do this.
                HashSet<String> programTitles = new HashSet<String>();
                programCounts = new ArrayList<HitCount>();
                for (int i = 0; i < hits.length() && programCounts.size() < 5; i++) {
                    String title = hits.doc(i).get("programTitle");
                    if (!programTitles.contains(title)) {
                        String queryTitle = title;
                        queryTitle = QueryParser.escape(title);
                        if (queryTitle.indexOf('"') > -1) {
                            queryTitle.replace("\"", "\\\"");
                        }
                        if (queryTitle.indexOf(' ') > -1) {
                            queryTitle = "\"" + queryTitle + "\"";
                        }

                        programCounts
                                .add(new HitCount(title, getFieldQuery(queryTitle, "programTitle", searcher),
                                        "programTitle:" + queryTitle, 0));
                        programTitles.add(title);
                    }
                }
                facetHitCounter.setSubQueries(programCounts);
                programCounts = facetHitCounter.getFacetHitCounts(false);
            } catch (Exception e) {
                e.printStackTrace();
            }

            results = new ArrayList<SearchResult>();
            programToSearchResult.clear();
            Query userQuery = getContentQuery(query, searcher);
            userQuery.rewrite(reader);
            Highlighter highlighter = new Highlighter(new TermFormatter(), new QueryScorer(userQuery, "text"));

            log.debug("#hits=" + hits.length());

            EPGProvider epgProvider = DefaultEpg.getInstance();

            boolean missingWebPaths = false; // We added this to the index midstream, so some do and some don't.
            // Next index rebuild, and they'll all have it.
            for (int i = 0; i < pageSize && i + startIndex < hits.length(); i++) {
                if (hits.doc(i + startIndex).get("webPath") == null) {
                    missingWebPaths = true;
                    break;
                }
            }
            Program[] programs = null;
            if (missingWebPaths) {
                List<String> programIds = new ArrayList<String>(pageSize);
                for (int i = 0; i < pageSize && i + startIndex < hits.length(); i++) {
                    programIds.add(hits.doc(i + startIndex).get("programID"));
                }
                programs = DefaultEpg.getInstance().getProgramList(programIds);
            }
            for (int i = 0; i < pageSize && i + startIndex < hits.length(); i++) {
                addDocument(hits.doc(i + startIndex), hits.score(i + startIndex), epgProvider, highlighter,
                        analyzer, null, null, (programs == null ? null : programs[i]));
            }
            if (results.size() + startIndex < hits.length()) {
                hasMoreResults = true;
            }
        } finally {
            if (searcher != null) {
                searcher.close();
            }
        }
    } catch (IOException e) {
        log.error("Error searching index", e);
    } catch (ParseException e) {
        log.error("Error searching index", e);
    }
    return results;
}

From source file:org.lockss.servlet.SubscriptionManagement.java

/**
 * Populates the tabs with the subscription data to be displayed.
 * /*from ww  w . java 2  s  .  com*/
 * @param subscriptions
 *          A List<Subscription> with the subscriptions to be used to populate
 *          the tabs.
 * @param divTableMap
 *          A Map<String, Table> with the tabs tables mapped by the first
 *          letter of the tab letter group.
 */
private void populateTabsSubscriptions(List<Subscription> subscriptions, Map<String, Table> divTableMap) {
    final String DEBUG_HEADER = "populateTabsSubscriptions(): ";
    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "subscriptions = " + subscriptions);

    Map.Entry<String, TreeSet<Subscription>> subEntry;
    String publisherName;
    TreeSet<Subscription> subSet;

    // Get a map of the subscriptions keyed by their publisher.
    MultiValueMap subscriptionMap = orderSubscriptionsByPublisher(subscriptions);
    if (log.isDebug3()) {
        if (subscriptionMap != null) {
            log.debug3(DEBUG_HEADER + "subscriptionMap.size() = " + subscriptionMap.size());
        } else {
            log.debug3(DEBUG_HEADER + "subscriptionMap is null");
        }
    }

    // Loop through all the subscriptions mapped by their publisher.
    Iterator<Map.Entry<String, TreeSet<Subscription>>> subIterator = (Iterator<Map.Entry<String, TreeSet<Subscription>>>) subscriptionMap
            .entrySet().iterator();

    while (subIterator.hasNext()) {
        subEntry = subIterator.next();

        // Get the publisher name.
        publisherName = subEntry.getKey();
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "publisherName = " + publisherName);

        // Get the set of subscriptions for this publisher.
        subSet = subEntry.getValue();
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "subSet.size() = " + subSet.size());

        // Populate a tab with the subscriptions for this publisher.
        populateTabPublisherSubscriptions(publisherName, subSet, divTableMap);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}

From source file:org.lockss.servlet.SubscriptionManagement.java

/**
 * Populates the tabs with the publication data to be displayed.
 * /*  ww  w  . java2  s.  co  m*/
 * @param publications
 *          A List<SerialPublication> with the publications to be used to
 *          populate the tabs.
 * @param divTableMap
 *          A Map<String, Table> with the tabs tables mapped by the first
 *          letter of the tab letter group.
 */
private void populateTabsPublications(List<SerialPublication> publications, Map<String, Table> divTableMap) {
    final String DEBUG_HEADER = "populateTabsPublications(): ";
    if (log.isDebug2()) {
        if (publications != null) {
            log.debug2(DEBUG_HEADER + "publications.size() = " + publications.size());
        } else {
            log.debug2(DEBUG_HEADER + "publications is null");
        }
    }

    Map.Entry<String, TreeSet<SerialPublication>> pubEntry;
    String publisherName;
    TreeSet<SerialPublication> pubSet;

    // Get a map of the publications keyed by their publisher.
    MultiValueMap publicationMap = orderPublicationsByPublisher(publications);
    if (log.isDebug3()) {
        if (publicationMap != null) {
            log.debug3(DEBUG_HEADER + "publicationMap.size() = " + publicationMap.size());
        } else {
            log.debug3(DEBUG_HEADER + "publicationMap is null");
        }
    }

    // Loop through all the publications mapped by their publisher.
    Iterator<Map.Entry<String, TreeSet<SerialPublication>>> pubIterator = (Iterator<Map.Entry<String, TreeSet<SerialPublication>>>) publicationMap
            .entrySet().iterator();

    while (pubIterator.hasNext()) {
        pubEntry = pubIterator.next();

        // Get the publisher name.
        publisherName = pubEntry.getKey();
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "publisherName = " + publisherName);

        // Get the set of publications for this publisher.
        pubSet = pubEntry.getValue();
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "pubSet.size() = " + pubSet.size());

        // Populate a tab with the publications for this publisher.
        populateTabPublisherPublications(publisherName, pubSet, divTableMap);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}

From source file:org.dasein.cloud.gogrid.network.lb.GoGridLBSupport.java

private @Nullable LoadBalancer toLoadBalancer(@Nullable JSONObject json, @Nullable JSONArray servers)
        throws CloudException, InternalException {
    if (json == null) {
        return null;
    }//w w w .j  a  v a  2 s .co  m

    LoadBalancer lb = new LoadBalancer();
    String regionId = getRegionId(getContext());

    lb.setProviderOwnerId(getContext().getAccountNumber());
    lb.setProviderRegionId(regionId);
    lb.setSupportedTraffic(new IPVersion[] { IPVersion.IPV4 });
    lb.setCurrentState(LoadBalancerState.PENDING);
    lb.setAddressType(LoadBalancerAddressType.IP);
    try {
        LbAlgorithm algorithm = LbAlgorithm.ROUND_ROBIN;
        int publicPort = -1;

        if (json.has("type")) {
            JSONObject type = json.getJSONObject("type");

            if (type.has("id")) {
                algorithm = toAlgorithm(type.getInt("id"));
            }
        }
        if (json.has("id")) {
            lb.setProviderLoadBalancerId(json.getString("id"));
        }
        if (json.has("name")) {
            lb.setName(json.getString("name"));
        }
        if (json.has("description")) {
            lb.setDescription(json.getString("description"));
        }
        if (json.has("datacenter")) {
            JSONObject dc = json.getJSONObject("datacenter");

            if (dc.has("id")) {
                lb.setProviderRegionId(dc.getString("id"));
                if (!regionId.equals(lb.getProviderRegionId())) {
                    return null;
                }
            }
        }
        if (json.has("state")) {
            /*
            {"id":1,"description":"Loadbalancer is enabled and on.","name":"On","object":"option"},
            {"id":2,"description":"Loadbalancer is disabled and off.","name":"Off","object":"option"},
            {"id":3,"description":"Loadbalancer is enabled, but real ips are unreachable.","name":"Unavailable","object":"option"},
            {"id":4,"description":"Loadbalancer state is unknown.","name":"Unknown","object":"option"}
             */
            JSONObject state = json.getJSONObject("state");

            if (state.has("id")) {
                int id = state.getInt("id");

                switch (id) {
                case 1:
                case 3:
                    lb.setCurrentState(LoadBalancerState.ACTIVE);
                    break;
                case 2:
                case 4:
                    lb.setCurrentState(LoadBalancerState.PENDING);
                    break;
                }
            }
        }
        if (json.has("virtualip")) {
            JSONObject vip = json.getJSONObject("virtualip");

            if (vip.has("ip")) {
                JSONObject ip = vip.getJSONObject("ip");

                if (ip.has("ip")) {
                    lb.setAddress(ip.getString("ip"));
                }
            }
            if (vip.has("port")) {
                publicPort = vip.getInt("port");
                lb.setPublicPorts(new int[] { publicPort });
            }
        }
        if (json.has("realiplist")) {
            ArrayList<LbListener> listeners = new ArrayList<LbListener>();
            TreeSet<String> serverIds = new TreeSet<String>();
            JSONArray ips = json.getJSONArray("realiplist");

            for (int i = 0; i < ips.length(); i++) {
                JSONObject ip = ips.getJSONObject(i);
                LbListener listener = new LbListener();

                listener.setPublicPort(publicPort);
                listener.setAlgorithm(algorithm);
                listener.setNetworkProtocol(LbProtocol.RAW_TCP);
                if (ip.has("port")) {
                    listener.setPrivatePort(ip.getInt("port"));
                }
                if (ip.has("ip")) {
                    JSONObject address = ip.getJSONObject("ip");

                    if (address.has("id") && servers != null) {
                        String id = address.getString("id");

                        for (int j = 0; j < servers.length(); j++) {
                            JSONObject server = servers.getJSONObject(j);
                            String serverId = null;

                            if (server.has("privateip")) {
                                JSONObject sip = server.getJSONObject("privateip");

                                if (sip.has("id") && id.equals(sip.getString("id")) && server.has("id")) {
                                    serverId = server.getString("id");
                                }
                            }
                            if (serverId == null && server.has("ip")) {
                                JSONObject sip = server.getJSONObject("ip");

                                if (sip.has("id") && id.equals(sip.getString("id")) && server.has("id")) {
                                    serverId = server.getString("id");
                                }
                            }
                            if (serverId != null) {
                                serverIds.add(serverId);
                                break;
                            }
                        }
                    }
                }
                listeners.add(listener);
            }
            lb.setProviderServerIds(serverIds.toArray(new String[serverIds.size()]));
            lb.setListeners(listeners.toArray(new LbListener[listeners.size()]));
        }
    } catch (JSONException e) {
        logger.error("Failed to parse load balancer JSON from cloud: " + e.getMessage());
        e.printStackTrace();
        throw new CloudException(e);
    }
    if (lb.getProviderLoadBalancerId() == null) {
        return null;
    }
    if (lb.getName() == null) {
        lb.setName(lb.getProviderLoadBalancerId());
    }
    if (lb.getDescription() == null) {
        lb.setDescription(lb.getName());
    }
    return lb;
}

From source file:org.prom5.analysis.performance.PerformanceAnalysisGUI.java

/**
 * Initializes the waiting time levels. If no manual peformance settings are
 * filled in by the user, standard settings are calculated and used.
 * Standard settings: approximately 33% low, 33% high, 33% medium level
 * note that a set is used instead of a list however, so if a time occurs
 * multiple times (this can happen easily with a waiting time of 0.0s for
 * instance) of such places only one is used, so the 33-33-33 estimation can
 * be quite wrong, though this is not considered to be a problem.
 *//*from   w  w  w.  j  av  a2s  . c  o  m*/
public void initializeWaitingTimeLevels() {
    if (!manualSettings) {
        //no manual settings are present
        TreeSet waitingTimes = new TreeSet();
        ListIterator it = extendedPetriNet.getPlaces().listIterator();
        while (it.hasNext()) {
            //place the mean waiting time of each place in the tree set
            ExtendedPlace p = (ExtendedPlace) it.next();
            p.calculateMetrics(extendedLog.getLogTraceIDs(), advancedSettings[1], failedInstances);
            if (p.getMeanWaitingTime() >= 0) {
                //only add correct times
                double waitTime = p.getMeanWaitingTime() / timeDivider;
                waitingTimes.add(Double.valueOf(waitTime));
            }
        }
        int num = waitingTimes.size() / 3;
        //remove the first 'num' measurements and the last 'num' measurements
        //from waitingTimes
        for (int i = 0; i < num; i++) {
            //there should be at least one waiting time measurement remaining
            if (!(waitingTimes.size() < 2)) {
                waitingTimes.remove(waitingTimes.first());
                waitingTimes.remove(waitingTimes.last());
            }
        }

        //give new values to the bounds and the colors
        if (waitingTimes.size() != 0) {
            Double bnd = (Double) waitingTimes.first();
            bounds.set(0, bnd);
            bnd = (Double) waitingTimes.last();
            bounds.set(1, bnd);
        } else {
            //in case there are no valid waiting times
            waitingTimes.add(Double.valueOf(0));
            Double bnd = (Double) waitingTimes.first();
            bounds.set(0, bnd);
            bounds.set(1, bnd);
        }
        levelColors.set(0, Color.BLUE);
        levelColors.set(1, Color.YELLOW);
        levelColors.set(2, Color.MAGENTA);
    }
    extendedPetriNet.setAdvancedSettings(advancedSettings);
    extendedPetriNet.setBounds(bounds);
    extendedPetriNet.setLevelColors(levelColors);
    extendedPetriNet.setTimeDivider(timeDivider);
    extendedPetriNet.setFailedInstances(failedInstances);
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * Build the type tree//from w w w  .  j  av  a 2 s .c  o  m
 */
/*private void buildTypeTree(XSTypeDefinition type, TreeSet descendents) {
if (type != null) {
        
    if (descendents.size() > 0) {
        TreeSet compatibleTypes = (TreeSet) typeTree.get(type.getName());
        
        if (compatibleTypes == null) {
            compatibleTypes = new TreeSet(descendents);
            typeTree.put(type.getName(), compatibleTypes);
        } else {
            compatibleTypes.addAll(descendents);
        }
    }
        
    XSTypeDefinition parentType = type.getBaseType();
        
    if (parentType != null
        && type.getTypeCategory() == parentType.getTypeCategory()) {
        String typeName = type.getName();
        String parentTypeName = parentType.getName();
        if ((typeName == null && parentTypeName != null)
            || (typeName != null && parentTypeName == null)
            || (typeName != null
                && parentTypeName != null
                && !type.getName().equals(parentType.getName())
                && !parentType.getName().equals("anyType"))) {
        
TreeSet newDescendents=new TreeSet(descendents);
//extension (we only add it to "newDescendants" because we don't want
//to have a type descendant to itself, but to consider it for the parent
if (type.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) {
XSComplexTypeDefinition complexType =
            (XSComplexTypeDefinition) type;
if (complexType.getDerivationMethod()
            == XSConstants.DERIVATION_EXTENSION
            && !complexType.getAbstract()
            && !descendents.contains(type.getName()) //to be tested
            ) {
newDescendents.add(type.getName());
}
}
//note: extensions are impossible on simpleTypes !
        
        buildTypeTree(parentType, newDescendents);
        }
    }
}
}*/
private void buildTypeTree(XSTypeDefinition type, TreeSet descendents) {
    if (type != null) {

        if (descendents.size() > 0) {
            //TreeSet compatibleTypes = (TreeSet) typeTree.get(type.getName());
            TreeSet compatibleTypes = (TreeSet) typeTree.get(type.getName());

            if (compatibleTypes == null) {
                //compatibleTypes = new TreeSet(descendents);
                compatibleTypes = new TreeSet(TypeExtensionSorter.getInstance());
                compatibleTypes.addAll(descendents);
                //typeTree.put(type.getName(), compatibleTypes);
                typeTree.put(type.getName(), compatibleTypes);
            } else {
                compatibleTypes.addAll(descendents);
            }
        }

        XSTypeDefinition parentType = type.getBaseType();

        if (parentType != null && type.getTypeCategory() == parentType.getTypeCategory()) {
            /*String typeName = type.getName();
            String parentTypeName = parentType.getName();
            if ((typeName == null && parentTypeName != null)
            || (typeName != null && parentTypeName == null)
            || (typeName != null
                && parentTypeName != null
                && !type.getName().equals(parentType.getName())
                && !parentType.getName().equals("anyType"))) {*/
            if (type != parentType
                    && (parentType.getName() == null || !parentType.getName().equals("anyType"))) {

                //TreeSet newDescendents=new TreeSet(descendents);
                TreeSet newDescendents = new TreeSet(TypeExtensionSorter.getInstance());
                newDescendents.addAll(descendents);

                //extension (we only add it to "newDescendants" because we don't want
                //to have a type descendant to itself, but to consider it for the parent
                if (type.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) {
                    XSComplexTypeDefinition complexType = (XSComplexTypeDefinition) type;
                    if (complexType.getDerivationMethod() == XSConstants.DERIVATION_EXTENSION
                            && !complexType.getAbstract() && !descendents.contains(type) //to be tested
                    //&& !descendents.contains(type.getName()) //to be tested
                    ) {
                        //newDescendents.add(type.getName());
                        newDescendents.add(type);
                    }
                }
                //note: extensions are impossible on simpleTypes !

                buildTypeTree(parentType, newDescendents);
            }
        }
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 * add an element to the XForms document: the bind + the control
 * (only the control if "withBind" is false)
 *//*from w  w w.ja  va  2s.c  o  m*/
private Element addElement(final Document xformsDocument, final Element modelSection,
        final Element defaultInstanceElement, final Element formSection, final XSModel schema,
        final XSElementDeclaration elementDecl, final String pathToRoot, final SchemaUtil.Occurrence occurs,
        final ResourceBundle resourceBundle) throws FormBuilderException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[addElement] adding element " + elementDecl + " at path " + pathToRoot);

    XSTypeDefinition controlType = elementDecl.getTypeDefinition();
    if (controlType == null) {
        // TODO!!! Figure out why this happens... for now just warn...
        // seems to happen when there is an element of type IDREFS
        LOGGER.warn("WARNING!!! controlType is null for " + elementDecl + ", " + elementDecl.getName());
        return null;
    }

    if (controlType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE
            && ((XSComplexTypeDefinition) controlType)
                    .getContentType() == XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) {
        controlType = ((XSComplexTypeDefinition) controlType).getSimpleType();
    }

    if (controlType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) {
        return this.addSimpleType(xformsDocument, modelSection, formSection, schema,
                (XSSimpleTypeDefinition) controlType, elementDecl.getName(), elementDecl, pathToRoot, occurs,
                resourceBundle);
    }

    if (controlType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE
            && "anyType".equals(controlType.getName())) {
        return this.addSimpleType(xformsDocument, modelSection, formSection, schema,
                (XSComplexTypeDefinition) controlType, elementDecl.getName(), elementDecl, pathToRoot, occurs,
                resourceBundle);
    }

    if (controlType.getTypeCategory() != XSTypeDefinition.COMPLEX_TYPE) {
        throw new FormBuilderException(
                "Unsupported type [" + elementDecl.getType() + "] for node [" + controlType.getName() + "]");
    }

    boolean relative = true;
    final String typeName = controlType.getName();
    final boolean typeIsAbstract = ((XSComplexTypeDefinition) controlType).getAbstract();
    final TreeSet<XSTypeDefinition> compatibleTypes = typeName != null ? this.typeTree.get(typeName) : null;

    if (compatibleTypes == null && typeName != null && LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addElement] No compatible type found for " + typeName);
    }

    if (typeName != null && compatibleTypes != null) {
        relative = false;

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addElement] compatible types for " + typeName + ":");
            for (XSTypeDefinition compType : compatibleTypes) {
                LOGGER.debug("[addElement]   compatible type name = " + compType.getName());
            }
        }

        if (!typeIsAbstract && compatibleTypes.size() == 0) {
            relative = true;
        } else if (typeIsAbstract && compatibleTypes.size() == 1) {
            // only one compatible type, set the controlType value
            // and fall through
            controlType = compatibleTypes.first();
            relative = true;
        } else if (typeIsAbstract && compatibleTypes.size() == 0) {
            // name not null but no compatibleType?
            relative = false;
        } else {
            return this.addElementWithMultipleCompatibleTypes(xformsDocument, modelSection,
                    defaultInstanceElement, formSection, schema, elementDecl, compatibleTypes, pathToRoot,
                    resourceBundle, occurs);
        }
    }

    if (!relative) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[addElement] bind is not relative for " + elementDecl.getName());
    } else {
        //         final SchemaUtil.Occurrence occurs = SchemaUtil.getOccurrence(elementDecl);
        //create the bind in case it is a repeat
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addElement] Adding empty bind for control " + controlType + " type " + typeName
                    + " nodeset " + pathToRoot + " occurs " + occurs);
        }

        // create the <xforms:bind> element and add it to the model.
        boolean isRepeated = isRepeated(occurs, controlType);
        final Element bindElement = this.createBind(xformsDocument,
                pathToRoot + (isRepeated ? "[position() != last()]" : ""));

        modelSection.appendChild(bindElement);
        this.startBindElement(bindElement, schema, controlType, null, occurs);
    }
    return this.addComplexType(xformsDocument, modelSection, defaultInstanceElement, formSection, schema,
            (XSComplexTypeDefinition) controlType, elementDecl, pathToRoot, occurs, true, false,
            resourceBundle);
}

From source file:com.cloudera.recordbreaker.schemadict.SchemaSuggest.java

/**
 * This method infers new schema labels for each element in the input.  It returns a Schema object that
 * has the identical format as the input file's Schema object, but the labels may be changed.
 *///from  ww  w . j av  a2s.  c o m
public List<DictionaryMapping> inferSchemaMapping(File avroFile, int k) throws IOException {
    SchemaStatisticalSummary srcSummary = new SchemaStatisticalSummary("input");
    Schema srcSchema = srcSummary.createSummaryFromData(avroFile);
    srcSummary.setUseAttributeLabels(useAttributeLabels);

    //
    // Compare the statistics to the database of schema statistics.  Find the closest matches, both
    // on a per-attribute basis and structurally.
    //
    int schemaSize = srcSchema.getFields().size();
    //
    // We start testing the input database against known schemas that have an identical
    // number of attributes, which should allow for the best matches.  This gives us an
    // initial set of distances.  We then expand the search to schemas of greater or fewer
    // attributes, as long as a given bucket of size-k schemas has a min-distance of less
    // than the current top-k matches.
    //
    //
    TreeSet<DictionaryMapping> sorter = new TreeSet<DictionaryMapping>();
    int numMatches = 0;
    List<Integer> seenIndexes = new ArrayList<Integer>();
    int searchRadius = 0;
    boolean seenAllCandidates = false;
    int srcSchemaSize = srcSchema.getFields().size();
    int totalSchemasExamined = 0;

    while (!seenAllCandidates) {
        // Examine the relevant schema buckets, compute all matches to those schemas
        for (int j = Math.max(1, srcSchemaSize - searchRadius); j <= Math.min(NUM_BUCKETS,
                srcSchemaSize + searchRadius); j++) {

            if (seenIndexes.contains(j - 1)) {
                continue;
            }
            for (SchemaDictionaryEntry elt : dictBySize.get(j - 1)) {
                /////////////////////////////
                // This is where we instrument the mapping stuff.
                // If the pair is an interesting one, then emit the mapping that
                // we discover.  Why are good matches going undiscovered?
                /////////////////////////////
                SchemaMapping mapping = srcSummary.getBestMapping(elt.getSummary());
                if (srcSchema.getName().equals(elt.getSchema().getName())) {
                    System.err
                            .println("Comparing " + srcSchema.getName() + " with " + elt.getSchema().getName());
                    System.err.println("Obtained mapping: " + mapping.toString());
                }

                totalSchemasExamined++;
                sorter.add(new DictionaryMapping(mapping, elt));
                numMatches++;
            }
            seenIndexes.add(j - 1);
        }

        // Have we examined the entire corpus of known schemas?
        if ((srcSchemaSize - searchRadius) <= 1 && (srcSchemaSize + searchRadius) >= NUM_BUCKETS) {
            seenAllCandidates = true;
        } else {
            // Test to see if the best matches are good enough that we can stop looking.
            // We compare the lowest known match distance to the minimum distance for matches
            // in the closest non-examined buckets.
            int lowestSize = srcSchemaSize - searchRadius - 1;
            int highestSize = srcSchemaSize + searchRadius + 1;
            double minNearbyDistance = Double.MAX_VALUE;
            if (lowestSize >= 1) {
                minNearbyDistance = Math.min(minNearbyDistance,
                        SchemaStatisticalSummary.getMinimumMappingCost(srcSchemaSize, lowestSize));
            }
            if (highestSize <= NUM_BUCKETS) {
                minNearbyDistance = Math.min(minNearbyDistance,
                        SchemaStatisticalSummary.getMinimumMappingCost(srcSchemaSize, highestSize));
            }
            // Grab from the Sorter the elt that is MIN_ELTS_SUGGESTED into the sorted list
            if (sorter.size() >= k) {
                DictionaryMapping testDictMapping = null;
                int idx = 0;
                for (DictionaryMapping cur : sorter) {
                    idx++;
                    if (idx == k) {
                        testDictMapping = cur;
                        break;
                    }
                }
                if (testDictMapping.getMapping().getDist() < minNearbyDistance) {
                    seenAllCandidates = true;
                }
            }
        }
        searchRadius++;
    }

    // Return the k best schema mappings
    double smallestDistance = sorter.first().getMapping().getDist();
    List<DictionaryMapping> dsts = new ArrayList<DictionaryMapping>();
    for (DictionaryMapping dp : sorter) {
        if (dsts.size() > k && dp.getMapping().getDist() > smallestDistance) {
            break;
        }
        dsts.add(dp);
    }
    double pct = totalSchemasExamined / (1.0 * dict.contents().size());
    System.err.println("Final search radius of " + searchRadius + " yielded a search over " + pct
            + " of all known databases.");
    return dsts;
}

From source file:org.lockss.servlet.SubscriptionManagement.java

/**
 * Populates a tab with the subscriptions for a publisher.
 * /*www  .j av a  2  s  .com*/
 * @param publisherName
 *          A String with the name of the publisher.
 * @param subSet
 *          A TreeSet<Subscription> with the publisher subscriptions.
 * @param divTableMap
 *          A Map<String, Table> with the tabs tables mapped by the first
 *          letter of the tab letter group.
 */
private void populateTabPublisherSubscriptions(String publisherName, TreeSet<Subscription> subSet,
        Map<String, Table> divTableMap) {
    final String DEBUG_HEADER = "populateTabPublisherSubscriptions(): ";
    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "publisherName = " + publisherName);

    // The publisher name first letter.
    String firstLetterPub = publisherName.substring(0, 1).toUpperCase();
    if (log.isDebug3())
        log.debug3(DEBUG_HEADER + "firstLetterPub = " + firstLetterPub);

    // Get the tab table that corresponds to this publisher.
    Table divTable = divTableMap.get(firstLetterPub);

    // Check whether no table corresponds naturally to this publisher.
    if (divTable == null) {
        // Yes: Use the first table.
        divTable = divTableMap.get("A");

        // Check whether no table is found.
        if (divTable == null) {
            // Yes: Report the problem and skip this publisher.
            log.error("Publisher '" + publisherName + "' belongs to an unknown tab: Skipped.");

            return;
        }
    }

    // Sanitize the publisher name so that it can be used as an HTML division
    // identifier.
    String cleanNameString = StringUtil.sanitizeToIdentifier(publisherName);
    if (log.isDebug3())
        log.debug3(DEBUG_HEADER + "cleanNameString = " + cleanNameString);

    String publisherRowTitle = publisherName;

    // Check whether there are any publications to show.
    if (subSet != null && subSet.size() > 0) {
        // Yes: Get the publisher row title.
        publisherRowTitle += " (" + subSet.size() + ")";
    }

    if (log.isDebug3())
        log.debug3(DEBUG_HEADER + "publisherRowTitle = " + publisherRowTitle);

    // Create in the table the title row for the publisher.
    createPublisherRow(publisherRowTitle, cleanNameString, divTable);

    // Check whether there are any subscriptions to show.
    if (subSet != null) {
        // Yes: Add them.
        int rowIndex = 0;

        // Loop through all the subscriptions.
        for (Subscription subscription : subSet) {
            // Create in the table a row for the subscription.
            createSubscriptionRow(subscription, cleanNameString, rowIndex, divTable);
            rowIndex++;
        }
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}