Example usage for java.util LinkedHashSet addAll

List of usage examples for java.util LinkedHashSet addAll

Introduction

In this page you can find the example usage for java.util LinkedHashSet addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:org.apereo.portal.layout.StylesheetUserPreferencesServiceImpl.java

@Override
public Iterable<String> getAllLayoutAttributeNodeIds(HttpServletRequest request, PreferencesScope prefScope) {
    final StylesheetPreferencesKey stylesheetPreferencesKey = this.getStylesheetPreferencesKey(request,
            prefScope);// w  ww.java 2  s  . c  om

    final LinkedHashSet<String> allNodeIds = new LinkedHashSet<String>();

    final IStylesheetUserPreferences stylesheetUserPreferences = this.getStylesheetUserPreferences(request,
            stylesheetPreferencesKey);
    if (stylesheetUserPreferences != null) {
        allNodeIds.addAll(stylesheetUserPreferences.getAllLayoutAttributeNodeIds());
    }

    final HttpSession session = request.getSession(false);
    if (session != null) {
        final Map<String, Map<String, String>> sessionLayoutAttributes = getSessionLayoutAttributes(session,
                stylesheetPreferencesKey);
        if (sessionLayoutAttributes != null) {
            allNodeIds.addAll(sessionLayoutAttributes.keySet());
        }

    }

    final Map<String, Map<String, String>> requestLayoutAttributes = getRequestLayoutAttributes(request,
            stylesheetPreferencesKey);
    if (requestLayoutAttributes != null) {
        allNodeIds.addAll(requestLayoutAttributes.keySet());
    }

    final IStylesheetUserPreferences distributedStylesheetUserPreferences = this
            .getDistributedStylesheetUserPreferences(request, prefScope);
    if (distributedStylesheetUserPreferences != null) {
        allNodeIds.addAll(distributedStylesheetUserPreferences.getAllLayoutAttributeNodeIds());
    }

    return allNodeIds;
}

From source file:org.topazproject.otm.impl.SessionFactoryImpl.java

private void gatherSup(String entity, LinkedHashSet<SubClassResolver> resolvers) {
    ClassMetadata cm = getClassMetadata(entity);
    Set<String> sups = null;
    if (cm != null)
        sups = cm.getSuperEntities();/*from   w  w  w . j  ava  2 s .co  m*/

    if (sups != null) {
        // breadth first
        for (String s : sups) {
            Set<SubClassResolver> r = subClassResolvers.get(s);
            if (r != null)
                resolvers.addAll(r);
        }
        // now depth
        for (String s : sups)
            gatherSup(s, resolvers);
    }
}

From source file:shuffle.fwk.service.teams.EditTeamService.java

private void updateKeybindComboBoxes() {
    Team curTeam = getCurrentTeam();/*www.  j a  va 2 s .c  o  m*/
    for (String name : curTeam.getNames()) {
        ItemListener itemListener = nameToItemListenerMap.get(name);
        JComboBox<Character> box = nameToKeybindComboboxMap.get(name);
        box.removeItemListener(itemListener);
        Character prevSelected = box.getItemAt(box.getSelectedIndex());
        box.removeAllItems();
        Character curBinding = curTeam.getBinding(name);
        LinkedHashSet<Character> availableBindings = new LinkedHashSet<Character>(Arrays.asList(curBinding));
        availableBindings.addAll(myData.getAllAvailableBindingsFor(name, curTeam));
        for (Character ch : availableBindings) {
            if (ch != null) {
                box.addItem(ch);
            }
        }
        box.setSelectedItem(prevSelected);
        if (box.getSelectedIndex() < 0) {
            LOG.warning(getString(KEY_NO_BINDINGS));
        }
        box.addItemListener(itemListener);
    }
}

From source file:net.heroicefforts.viable.android.rep.it.GIssueTrackerRepository.java

public SearchResults search(SearchParams params) throws ServiceException {
    final int startIdx = (params.getPage() - 1) * params.getPageSize();
    final int pageSize = params.getPageSize();

    LinkedHashSet<Issue> issues = new LinkedHashSet<Issue>();
    for (int i = startIdx; i < params.getIds().size() && i < startIdx + pageSize + i; i++)
        issues.add(findById(params.getIds().get(i)));

    if (issues.size() <= pageSize) {
        Issue issue = findByHash(params.getHash());
        if (issue != null)
            issues.add(issue);/*from www  .  j a v a2 s  . c om*/
    }

    if (issues.size() <= pageSize) {
        long skip = startIdx;
        long skipped = params.getIds().size() + (params.getHash() != null ? 1 : 0);
        for (int i = 0; i < params.getAffectedVersions().size() && issues.size() <= pageSize; i++) {
            long count = countIssuesByVersion(params.getAffectedVersions().get(i));
            if (skipped + count > skip) {
                int needed = pageSize - issues.size() + 1;
                long startAt = skip - skipped;
                if (startAt < 0)
                    startAt = 0;
                issues.addAll(findIssuesByVersion(params.getAffectedVersions().get(i), startAt, needed));
                skipped = skip;
            } else {
                skipped += count;
            }
        }
    }

    setAppName(issues);

    if (issues.size() > pageSize)
        return new SearchResults(new ArrayList<Issue>(issues).subList(0, pageSize), true);
    else
        return new SearchResults(new ArrayList<Issue>(issues), false);
}

From source file:com.github.dozermapper.core.MappingProcessor.java

private Set<?> addToSet(Object srcObj, FieldMap fieldMap, Collection<?> srcCollectionValue, Object destObj) {
    // create a list here so we can keep track of which elements we have mapped, and remove all others if removeOrphans = true
    Set<Object> mappedElements = new HashSet<>();

    LinkedHashSet<Object> result = new LinkedHashSet<>();
    // don't want to create the set if it already exists.
    Object field = fieldMap.getDestValue(destObj);
    if (field != null) {
        result.addAll((Collection<?>) field);
    }/*  www. j a v a 2 s.c om*/
    Object destValue;

    Class<?> destEntryType = null;
    Class<?> prevDestEntryType = null;
    for (Object srcValue : srcCollectionValue) {
        if (destEntryType == null || (fieldMap.getDestHintContainer() != null
                && fieldMap.getDestHintContainer().hasMoreThanOneHint())) {
            destEntryType = determineCollectionItemType(fieldMap, destObj, srcValue, prevDestEntryType);
        }

        CopyByReferenceContainer copyByReferences = globalConfiguration.getCopyByReferences();
        if (srcValue != null && copyByReferences.contains(srcValue.getClass())) {
            destValue = srcValue;
        } else {
            destValue = mapOrRecurseObject(srcObj, srcValue, destEntryType, fieldMap, destObj);
        }
        prevDestEntryType = destEntryType;

        if (RelationshipType.NON_CUMULATIVE.equals(fieldMap.getRelationshipType())
                && result.contains(destValue)) {
            List<Object> resultAsList = new ArrayList<>(result);
            int index = resultAsList.indexOf(destValue);
            // perform an update if complex type - can't map strings
            Object obj = resultAsList.get(index);
            // make sure it is not a String
            if (!obj.getClass().isAssignableFrom(String.class)) {
                mapToDestObject(null, srcValue, obj, false, fieldMap.getMapId());
                mappedElements.add(obj);
            }
        } else {
            if (destValue != null || fieldMap.isDestMapNull()) {
                result.add(destValue);
            }
            mappedElements.add(destValue);
        }
    }

    // If remove orphans - we only want to keep the objects we've mapped from the src collection
    // so we'll clear result and replace all entries with the ones in mappedElements
    if (fieldMap.isRemoveOrphans()) {
        result.clear();
        result.addAll(mappedElements);
    }

    if (field == null) {
        Class<? extends Set<?>> destSetType = (Class<? extends Set<?>>) fieldMap
                .getDestFieldType(destObj.getClass());
        return CollectionUtils.createNewSet(destSetType, result);
    } else {
        // Bug #1822421 - Clear first so we don't end up with the removed orphans again
        ((Set) field).clear();
        ((Set) field).addAll(result);
        return (Set<?>) field;
    }
}

From source file:org.occiware.clouddesigner.occi.linkeddata.connector.LdprojectConnector.java

/**
 * /*  w  w  w  .j a  va  2  s.  c  om*/
 * @param resource must come from getExistingOrNew()
 */
private void updateAttributes(DCResource resource) {
    resource.set("dcmpv:name", this.getName()); // (actually only if creation)         
    ///resource.set("dcmp:frozenModelNames", ); // NO ONLY ACTIONS ELSE VOIDS VALUE
    resource.set("dcmpvdb:robust", this.getRobustness() == Robustness.CLUSTER);

    ///resource.set("dcmpvdb:uri", this.dburi); // rather using links :
    String ldDbUri = null;
    if (this.links != null) { // ex. in Mart
        List<Link> lddLinks = this.links.stream()
                .filter(l -> l instanceof Lddatabaselink && l.getTarget() instanceof Compute)
                .collect(Collectors.toList());
        if (!lddLinks.isEmpty()) {
            Lddatabaselink lddLink = (Lddatabaselink) lddLinks.iterator().next(); // first one matters only
            Compute customSecondaryCompute = (Compute) lddLink.getTarget();
            if (customSecondaryCompute.getHostname() == null
                    || customSecondaryCompute.getHostname().trim().length() == 0) {
                throw new RuntimeException("Lddatabaselink's target Compute has no hostname");
            }
            ldDbUri = "mongodb://" + customSecondaryCompute.getHostname() + ":" + lddLink.getPort() + "/"
                    + lddLink.getDatabase();
        }
    }
    resource.set("dcmpvdb:uri", ldDbUri);

    LinkedHashSet<String> lvp = new LinkedHashSet<String>();
    @SuppressWarnings("unchecked")
    Collection<String> lvpFound = (Collection<String>) resource.get("dcmp:localVisibleProjects"); // else java.lang.ClassCastException: java.util.LinkedHashSet cannot be cast to java.util.List !
    if (lvpFound == null) {
        lvp = new LinkedHashSet<String>();
        lvp.add(UriHelper.buildUri(ldContainerUrl, "dcmp:Project_0", "oasis.meta")); // all projects must see metamodel
    } else {
        lvp = new LinkedHashSet<String>(lvpFound);
    }
    if (this.links != null) { // ex. in Mart
        List<String> ldpLinkTargetProjectUris = this.links.stream()
                .filter(l -> l instanceof Ldprojectlink && l.getTarget() instanceof Ldproject)
                .map(ldpl -> UriHelper.buildUri(ldContainerUrl, "dcmp:Project_0",
                        ((Ldproject) ldpl.getTarget()).getName()))
                .collect(Collectors.toList());
        lvp.addAll(ldpLinkTargetProjectUris);
    }
    resource.set("dcmp:localVisibleProjects", lvp);
}

From source file:restaurant.dozer.custom.mapper.CustomMappingProcessor.java

private Set<?> addToSet(Object srcObj, FieldMap fieldMap, Collection<?> srcCollectionValue, Object destObj) {
    // create a list here so we can keep track of which elements we have
    // mapped, and remove all others if removeOrphans = true
    Set<Object> mappedElements = new HashSet<Object>();

    LinkedHashSet<Object> result = new LinkedHashSet<Object>();
    // don't want to create the set if it already exists.
    Object field = fieldMap.getDestValue(destObj);
    if (field != null) {
        result.addAll((Collection<?>) field);
    }/*w  w  w  .j a va2s .c o  m*/
    Object destValue;

    Class<?> destEntryType = null;
    Class<?> prevDestEntryType = null;
    for (Object srcValue : srcCollectionValue) {
        if (destEntryType == null || (fieldMap.getDestHintContainer() != null
                && fieldMap.getDestHintContainer().hasMoreThanOneHint())) {
            destEntryType = determineCollectionItemType(fieldMap, destObj, srcValue, prevDestEntryType);
        }

        CopyByReferenceContainer copyByReferences = globalConfiguration.getCopyByReferences();
        if (srcValue != null && copyByReferences.contains(srcValue.getClass())) {
            destValue = srcValue;
        } else {
            destValue = mapOrRecurseObject(srcObj, srcValue, destEntryType, fieldMap, destObj);
        }
        prevDestEntryType = destEntryType;

        if (RelationshipType.NON_CUMULATIVE.equals(fieldMap.getRelationshipType())
                && result.contains(destValue)) {
            List<Object> resultAsList = new ArrayList<Object>(result);
            int index = resultAsList.indexOf(destValue);
            // perform an update if complex type - can't map strings
            Object obj = resultAsList.get(index);
            // make sure it is not a String
            if (!obj.getClass().isAssignableFrom(String.class)) {
                mapToDestObject(null, srcValue, obj, false, fieldMap.getMapId());
                mappedElements.add(obj);
            }
        } else {
            if (destValue != null || fieldMap.isDestMapNull()) {
                result.add(destValue);
            }
            mappedElements.add(destValue);
        }
    }

    // If remove orphans - we only want to keep the objects we've mapped
    // from the src collection
    // so we'll clear result and replace all entries with the ones in
    // mappedElements
    if (fieldMap.isRemoveOrphans()) {
        result.clear();
        result.addAll(mappedElements);
    }

    if (field == null) {
        Class<? extends Set<?>> destSetType = (Class<? extends Set<?>>) fieldMap
                .getDestFieldType(destObj.getClass());
        return CollectionUtils.createNewSet(destSetType, result);
    } else {
        // Bug #1822421 - Clear first so we don't end up with the removed
        // orphans again
        ((Set) field).clear();
        ((Set) field).addAll(result);
        return (Set<?>) field;
    }
}

From source file:net.yacy.peers.Protocol.java

/**
 * Execute solr query against specified target.
 * @param event search event ot feed with results
 * @param solrQuery solr query//from w  w w  .ja  va 2 s  .  c  o  m
 * @param offset pagination start indice
 * @param count expected maximum results
 * @param target target peer to query. May be null : in that case, local peer is queried.
 * @param partitions
 * @param blacklist url list to exclude from results
 * @param useSolrFacets when true, use Solr computed facets when possible to update the event navigators counters
 * @param incrementNavigators when true, increment event navigators either with facet counts or with individual results
 * @return the size of results list
 * @throws InterruptedException when interrupt status on calling thread is detected while processing
 */
protected static int solrQuery(final SearchEvent event, final SolrQuery solrQuery, final int offset,
        final int count, final Seed target, final int partitions, final Blacklist blacklist,
        final boolean useSolrFacets, final boolean incrementNavigators) throws InterruptedException {

    //try {System.out.println("*** debug-query *** " + URLDecoder.decode(solrQuery.toString(), "UTF-8"));} catch (UnsupportedEncodingException e) {}

    if (event.query.getQueryGoal().getQueryString(false) == null
            || event.query.getQueryGoal().getQueryString(false).length() == 0) {
        return -1; // we cannot query solr only with word hashes, there is no clear text string
    }
    event.addExpectedRemoteReferences(count);
    if (partitions > 0)
        solrQuery.set("partitions", partitions);
    solrQuery.setStart(offset);
    solrQuery.setRows(count);

    boolean localsearch = target == null || target.equals(event.peers.mySeed());
    Map<String, ReversibleScoreMap<String>> facets = new HashMap<String, ReversibleScoreMap<String>>(
            event.query.facetfields.size());
    Map<String, LinkedHashSet<String>> snippets = new HashMap<String, LinkedHashSet<String>>(); // this will be a list of urlhash-snippet entries
    final QueryResponse[] rsp = new QueryResponse[] { null };
    final SolrDocumentList[] docList = new SolrDocumentList[] { null };
    {// encapsulate expensive solr QueryResponse object
        if (localsearch && !Switchboard.getSwitchboard()
                .getConfigBool(SwitchboardConstants.DEBUG_SEARCH_REMOTE_SOLR_TESTLOCAL, false)) {
            // search the local index
            try {
                SolrConnector sc = event.getQuery().getSegment().fulltext().getDefaultConnector();
                if (!sc.isClosed()) {
                    rsp[0] = sc.getResponseByParams(solrQuery);
                    docList[0] = rsp[0].getResults();
                }
            } catch (final Throwable e) {
                Network.log.info("SEARCH failed (solr), localpeer (" + e.getMessage() + ")", e);
                return -1;
            }
        } else {
            String targetBaseURL = null;
            try {
                final boolean myseed = target == event.peers.mySeed();
                if (myseed) {
                    targetBaseURL = "http://localhost:" + target.getPort();
                } else {
                    final Set<String> ips = target.getIPs();
                    if (ips.isEmpty()) {
                        /* This should not happen : seeds db maintains only seeds with at least one IP */
                        Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName()
                                + " has no known IP address");
                        target.setFlagSolrAvailable(false);
                        return -1;
                    }
                    final String ip = ips.iterator().next();

                    targetBaseURL = target.getPublicURL(ip,
                            Switchboard.getSwitchboard().getConfigBool(
                                    SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED,
                                    SwitchboardConstants.REMOTESEARCH_HTTPS_PREFERRED_DEFAULT));
                }
                if (!myseed && !target.getFlagSolrAvailable()) { // skip if peer.dna has flag that last try resulted in error
                    Network.log.info("SEARCH skip (solr), remote Solr interface not accessible, peer="
                            + target.getName());
                    return -1;
                }
                final int solrtimeout = Switchboard.getSwitchboard()
                        .getConfigInt(SwitchboardConstants.FEDERATED_SERVICE_SOLR_INDEXING_TIMEOUT, 6000);
                SolrRequestTask remoteRequest = new SolrRequestTask(solrQuery, targetBaseURL, target, myseed,
                        solrtimeout, rsp, docList);
                remoteRequest.start();
                remoteRequest.join(solrtimeout); // just wait until timeout appears
                if (remoteRequest.isAlive()) {
                    /* Try to free the request thread resources properly */
                    remoteRequest.close();
                    if (remoteRequest.isAlive()) {
                        /* Thread still running : try also with interrupt*/
                        remoteRequest.interrupt();
                    }
                    Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + "/"
                            + targetBaseURL + " does not answer (time-out)");
                    target.setFlagSolrAvailable(false || myseed);
                    return -1; // give up, leave remoteRequest abandoned.
                }

                if (rsp[0] == null || docList[0] == null) {
                    Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName() + "/"
                            + targetBaseURL + " returned null");
                    if (!myseed) {
                        if (targetBaseURL.startsWith("https")) {
                            /* First mark https unavailable on this peer before removing anything else */
                            target.setFlagSSLAvailable(false);
                            event.peers.updateConnected(target);
                        } else {
                            target.setFlagSolrAvailable(false);
                        }
                    }
                    return -1;
                }
            } catch (InterruptedException e) {
                /* Current thread might be interrupted by SearchEvent.cleanup() : 
                 * we must not in that case mark the target as not available but rather transmit the exception to the caller (likely RemoteSearch.solrRemoteSearch) */
                throw e;
            } catch (final Throwable e) {
                if (Network.log.isInfo()) {
                    Network.log.info("SEARCH failed (solr), remote Peer: " + target.getName()
                            + (targetBaseURL != null ? "/" + targetBaseURL : "") + " (" + e.getMessage() + ")");
                }
                target.setFlagSolrAvailable(false || localsearch);
                return -1;
            }
        }

        // evaluate facets
        if (useSolrFacets) {
            for (String field : event.query.facetfields) {
                FacetField facet = rsp[0].getFacetField(field);
                ReversibleScoreMap<String> result = new ClusteredScoreMap<String>(
                        UTF8.insensitiveUTF8Comparator);
                List<Count> values = facet == null ? null : facet.getValues();
                if (values == null) {
                    continue;
                }
                for (Count ff : values) {
                    int c = (int) ff.getCount();
                    if (c == 0) {
                        continue;
                    }
                    if (ff.getName().length() == 0) {
                        continue; // facet entry without text is not useful
                    }
                    result.set(ff.getName(), c);
                }
                if (result.size() > 0) {
                    facets.put(field, result);
                }
            }
        }

        // evaluate snippets
        final Map<String, Map<String, List<String>>> rawsnippets = rsp[0].getHighlighting(); // a map from the urlhash to a map with key=field and value = list of snippets
        if (rawsnippets != null) {
            nextsnippet: for (final Map.Entry<String, Map<String, List<String>>> re : rawsnippets.entrySet()) {
                final Map<String, List<String>> rs = re.getValue();
                for (final String field : solrQuery.getHighlightFields()) {
                    if (rs.containsKey(field)) {
                        final List<String> s = rs.get(field);
                        if (s.size() > 0) {
                            final LinkedHashSet<String> ls = new LinkedHashSet<String>();
                            ls.addAll(s);
                            snippets.put(re.getKey(), ls);
                            continue nextsnippet;
                        }
                    }
                }
                // no snippet found :( --we don't assign a value here by default; that can be done as an evaluation outside this method
            }
        }
        rsp[0] = null;
    }

    // evaluate result
    if (docList == null || docList[0].size() == 0) {
        Network.log.info("SEARCH (solr), returned 0 out of 0 documents from "
                + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())) + " query = "
                + solrQuery.toString());
        return 0;
    }

    List<URIMetadataNode> resultContainer = new ArrayList<URIMetadataNode>();
    Network.log.info("SEARCH (solr), returned " + docList[0].size() + " out of " + docList[0].getNumFound()
            + " documents and " + facets.size() + " facets " + facets.keySet().toString() + " from "
            + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));
    int term = count;
    Collection<SolrInputDocument> docs;
    if (event.addResultsToLocalIndex) { // only needed to store remote results
        docs = new ArrayList<SolrInputDocument>(docList[0].size());
    } else
        docs = null;
    for (final SolrDocument tmpdoc : docList[0]) {
        //System.out.println("***DEBUG*** " + ((String) doc.getFieldValue("sku")));
        if (term-- <= 0) {
            break; // do not process more that requested (in case that evil peers fill us up with rubbish)
        }
        // get one single search result
        if (tmpdoc == null) {
            continue;
        }
        URIMetadataNode urlEntry;
        try {
            urlEntry = new URIMetadataNode(tmpdoc);
        } catch (MalformedURLException ex) {
            continue;
        }

        if (blacklist.isListed(BlacklistType.SEARCH, urlEntry.url())) {
            if (Network.log.isInfo()) {
                if (localsearch) {
                    Network.log.info("local search (solr): filtered blacklisted url "
                            + urlEntry.url().toNormalform(true));
                } else {
                    Network.log.info("remote search (solr): filtered blacklisted url "
                            + urlEntry.url().toNormalform(true) + " from "
                            + (target == null ? "shard" : ("peer " + target.hash + ":" + target.getName())));
                }
            }
            continue; // block with blacklist
        }

        final String urlRejectReason = Switchboard.getSwitchboard().crawlStacker
                .urlInAcceptedDomain(urlEntry.url());
        if (urlRejectReason != null) {
            if (Network.log.isInfo()) {
                if (localsearch) {
                    Network.log.info("local search (solr): rejected url '" + urlEntry.url().toNormalform(true)
                            + "' (" + urlRejectReason + ")");
                } else {
                    Network.log.info("remote search (solr): rejected url '" + urlEntry.url().toNormalform(true)
                            + "' (" + urlRejectReason + ") from peer " + target.getName());
                }
            }
            continue; // reject url outside of our domain
        }

        // passed all checks, store url
        if (!localsearch) {

            // put the remote documents to the local index. We must convert the solr document to a solr input document:
            if (event.addResultsToLocalIndex) {
                /* Check document size, only if a limit is set on remote documents size allowed to be stored to local index */
                if (checkDocumentSize(tmpdoc, event.getRemoteDocStoredMaxSize() * 1024)) {
                    final SolrInputDocument sid = event.query.getSegment().fulltext().getDefaultConfiguration()
                            .toSolrInputDocument(tmpdoc);

                    // the input document stays untouched because it contains top-level cloned objects
                    docs.add(sid);
                    // will be stored to index, and is a full solr document, can be added to firstseen
                    event.query.getSegment().setFirstSeenTime(urlEntry.hash(),
                            Math.min(urlEntry.moddate().getTime(), System.currentTimeMillis()));
                } else {
                    Network.log.info("Document size greater than " + event.getRemoteDocStoredMaxSize()
                            + " kbytes, excludes it from being stored to local index. Url : "
                            + urlEntry.urlstring());
                }
            }

            // after this conversion we can remove the largest and not used field text_t and synonyms_sxt from the document
            // because that goes into a search cache and would take a lot of memory in the search cache
            //doc.removeFields(CollectionSchema.text_t.getSolrFieldName());
            tmpdoc.removeFields(CollectionSchema.synonyms_sxt.getSolrFieldName());

            ResultURLs.stack(ASCII.String(urlEntry.url().hash()), urlEntry.url().getHost(),
                    event.peers.mySeed().hash.getBytes(), UTF8.getBytes(target.hash), EventOrigin.QUERIES);
        }

        // add the url entry to the checked results
        resultContainer.add(urlEntry);
    }
    final int numFound = (int) docList[0].getNumFound();
    docList[0].clear();
    docList[0] = null;
    if (localsearch) {
        event.addNodes(resultContainer, facets, snippets, true, "localpeer", numFound, incrementNavigators);
        event.addFinalize();
        event.addExpectedRemoteReferences(-count);
        Network.log.info("local search (solr): localpeer sent " + resultContainer.size() + "/" + numFound
                + " references");
    } else {
        if (event.addResultsToLocalIndex) {
            /*
            * Current thread might be interrupted by SearchEvent.cleanup()
             */
            if (Thread.interrupted()) {
                throw new InterruptedException("solrQuery interrupted");
            }
            WriteToLocalIndexThread writeToLocalIndexThread = new WriteToLocalIndexThread(
                    event.query.getSegment(), docs); // will clear docs on return
            writeToLocalIndexThread.start();
        }
        event.addNodes(resultContainer, facets, snippets, false, target.getName() + "/" + target.hash, numFound,
                incrementNavigators);
        event.addFinalize();
        event.addExpectedRemoteReferences(-count);
        Network.log.info("remote search (solr): peer " + target.getName() + " sent " + (resultContainer.size())
                + "/" + numFound + " references");
    }
    return resultContainer.size();
}

From source file:org.topazproject.otm.impl.SessionFactoryImpl.java

public ClassMetadata getSubClassMetadata(ClassMetadata clazz, EntityMode mode, Collection<String> typeUris,
        TripleStore.Result result) {
    Set<ClassMetadata> candidates = new HashSet<ClassMetadata>();

    if (typeUris == null)
        typeUris = Collections.emptySet();

    buildCandidates(candidates, clazz, clazz, mode, typeUris);

    Set<ClassMetadata> solutions = new HashSet<ClassMetadata>(candidates);

    // Eliminate super classes from an rdf:type perspective
    for (ClassMetadata sup : candidates) {
        for (ClassMetadata cm : candidates) {
            if ((sup != cm) && cm.getAllTypes().size() > sup.getAllTypes().size()
                    && cm.getAllTypes().containsAll(sup.getAllTypes())) {
                solutions.remove(sup);//from   w  ww.j av  a2 s.  c om
                break;
            }
        }
    }

    if (solutions.isEmpty())
        return null;

    if (solutions.size() == 1)
        return solutions.iterator().next();

    // narrow down based on other rdf statements
    if (result != null) {
        LinkedHashSet<SubClassResolver> resolvers = new LinkedHashSet<SubClassResolver>();

        // resolvers for sub-classes of the solutions (excluding the solutions)
        for (ClassMetadata cl : solutions)
            gatherSub(cl.getName(), resolvers);
        for (ClassMetadata cl : solutions)
            resolvers.removeAll(listRegisteredSubClassResolvers(cl.getName()));

        // resolvers for the solutions
        for (ClassMetadata cl : solutions)
            resolvers.addAll(listRegisteredSubClassResolvers(cl.getName()));

        // resolvers for the super-classes
        for (ClassMetadata cl : solutions)
            gatherSup(cl.getName(), resolvers);

        // add the root as the last
        Set<SubClassResolver> rs = subClassResolvers.get(null);
        if (rs != null)
            resolvers.addAll(rs);

        for (SubClassResolver r : resolvers) {
            ClassMetadata cm = r.resolve(clazz, mode, this, typeUris, result);
            if ((cm != null) && isAcceptable(cm, clazz, mode, typeUris))
                return cm;
        }
    }

    // That didn't help. Eliminate super classes from an EntityBinder perspective
    if (mode != null) {
        candidates = new HashSet<ClassMetadata>(solutions);
        for (ClassMetadata sup : candidates) {
            EntityBinder supBinder = sup.getEntityBinder(mode);
            for (ClassMetadata cm : candidates) {
                EntityBinder binder = cm.getEntityBinder(mode);
                if ((sup != cm) && supBinder.isAssignableFrom(binder)) {
                    solutions.remove(sup);
                    break;
                }
            }
        }
    }

    ClassMetadata solution = solutions.iterator().next();

    if (solutions.size() > 1) {
        // That didn't help either. Pick the first in the solutions set
        log.warn("Randomly chose " + solution + " as a subclass for " + clazz + " from the set " + solutions);
    }

    return solution;
}

From source file:shuffle.fwk.service.teams.EditTeamService.java

private Component createTeamComponent(Species s) {
    Team curTeam = getCurrentTeam();//from  www.  ja  v a 2s . co m
    JPanel ret = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 1;
    c.gridy = 1;
    c.gridwidth = 2;
    Indicator<SpeciesPaint> ind = new Indicator<SpeciesPaint>(this);
    boolean isMega = megaProgress >= megaThreshold && s.getName().equals(curTeam.getMegaSlotName());
    SpeciesPaint paint = new SpeciesPaint(s, s.equals(Species.FREEZE), isMega);
    ind.setVisualized(paint);
    ret.add(ind, c);
    c.gridy += 1;
    c.gridwidth = 1;
    JButton removeButton = new JButton(getString(KEY_REMOVE));
    removeButton.setToolTipText(getString(KEY_REMOVE_TOOLTIP));
    removeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            removeSpeciesFromTeam(s.getName());
            updateTeamPanel();
        }
    });
    removeButton.setEnabled(
            s.getEffect(getUser().getRosterManager()).isPickable() && !s.getType().equals(PkmType.NONE));
    ret.add(removeButton, c);

    c.gridx += 1;
    JComboBox<Character> keybindsComboBox = new JComboBox<Character>();
    Character curBinding = curTeam.getBinding(s);
    LinkedHashSet<Character> allBindingsFor = new LinkedHashSet<Character>(Arrays.asList(curBinding));
    LinkedHashSet<Character> availableBindings = myData.getAllAvailableBindingsFor(s.getName(), curTeam);
    allBindingsFor.addAll(availableBindings);
    for (Character ch : allBindingsFor) {
        keybindsComboBox.addItem(ch);
    }
    keybindsComboBox.setSelectedItem(curBinding);
    final ItemListener bindingListener = new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            JComboBox<?> source = (JComboBox<?>) e.getSource();
            int selectedIndex = source.getSelectedIndex();
            Character selected = (Character) source.getItemAt(selectedIndex);
            setBinding(s, selected);
            updateKeybindComboBoxes();
        }
    };
    nameToKeybindComboboxMap.put(s.getName(), keybindsComboBox);
    nameToItemListenerMap.put(s.getName(), bindingListener);
    keybindsComboBox.addItemListener(bindingListener);
    keybindsComboBox.setToolTipText(getString(KEY_KEYBINDS_TOOLTIP));
    ret.add(keybindsComboBox, c);

    MouseAdapter ma = new PressToggleMouseAdapter() {

        @Override
        protected void onRight(MouseEvent e) {
            doToggle();
        }

        @Override
        protected void onLeft(MouseEvent e) {
            doToggle();
        }

        private void doToggle() {
            toggleSupport(s);
            updateTeamPanel();
        }
    };
    ret.addMouseListener(ma);

    setBorderFor(ret, false, false);
    if (!Species.FIXED_SPECIES.contains(s)) {
        boolean isSupport = !curTeam.isNonSupport(s);
        Color indColor = isSupport ? Color.GREEN : Color.RED;
        ret.setBackground(indColor);
        ret.setOpaque(true);
    }
    return ret;
}