Example usage for java.util TreeSet isEmpty

List of usage examples for java.util TreeSet isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:org.languagetool.rules.patterns.MatchState.java

/**
 * Gets all strings formatted using the match element.
 *//*from w  w  w.  j a  v  a2 s. c  o  m*/
public final String[] toFinalString(Language lang) throws IOException {
    String[] formattedString = new String[1];
    if (formattedToken != null) {
        int readingCount = formattedToken.getReadingsLength();
        formattedString[0] = formattedToken.getToken();

        Pattern pRegexMatch = match.getRegexMatch();
        String regexReplace = match.getRegexReplace();
        if (pRegexMatch != null) {
            formattedString[0] = pRegexMatch.matcher(formattedString[0]).replaceAll(regexReplace);
        }

        String posTag = match.getPosTag();
        if (posTag != null) {
            if (synthesizer == null) {
                formattedString[0] = formattedToken.getToken();
            } else if (match.isPostagRegexp()) {
                TreeSet<String> wordForms = new TreeSet<>();
                boolean oneForm = false;
                for (int k = 0; k < readingCount; k++) {
                    if (formattedToken.getAnalyzedToken(k).getLemma() == null) {
                        String posUnique = formattedToken.getAnalyzedToken(k).getPOSTag();
                        if (posUnique == null) {
                            wordForms.add(formattedToken.getToken());
                            oneForm = true;
                        } else {
                            if (SENTENCE_START_TAGNAME.equals(posUnique)
                                    || SENTENCE_END_TAGNAME.equals(posUnique)
                                    || PARAGRAPH_END_TAGNAME.equals(posUnique)) {
                                if (!oneForm) {
                                    wordForms.add(formattedToken.getToken());
                                }
                                oneForm = true;
                            } else {
                                oneForm = false;
                            }
                        }
                    }
                }
                String targetPosTag = getTargetPosTag();
                if (!oneForm) {
                    for (int i = 0; i < readingCount; i++) {
                        String[] possibleWordForms = synthesizer.synthesize(formattedToken.getAnalyzedToken(i),
                                targetPosTag, true);
                        if (possibleWordForms != null && possibleWordForms.length > 0) {
                            wordForms.addAll(Arrays.asList(possibleWordForms));
                        }
                    }
                }
                if (wordForms.isEmpty()) {
                    if (match.checksSpelling()) {
                        formattedString[0] = "";
                    } else {
                        formattedString[0] = "(" + formattedToken.getToken() + ")";
                    }
                } else {
                    formattedString = wordForms.toArray(new String[0]);
                }
            } else {
                TreeSet<String> wordForms = new TreeSet<>();
                for (int i = 0; i < readingCount; i++) {
                    String[] possibleWordForms = synthesizer.synthesize(formattedToken.getAnalyzedToken(i),
                            posTag);
                    if (possibleWordForms != null) {
                        wordForms.addAll(Arrays.asList(possibleWordForms));
                    }
                }
                formattedString = wordForms.toArray(new String[0]);
            }
        }
    }
    String original;
    if (match.isStaticLemma()) {
        original = matchedToken != null ? matchedToken.getToken() : "";
    } else {
        original = formattedToken != null ? formattedToken.getToken() : "";
    }
    for (int i = 0; i < formattedString.length; i++) {
        formattedString[i] = convertCase(formattedString[i], original, lang);
    }
    // TODO should case conversion happen before or after including skipped tokens?
    IncludeRange includeSkipped = match.getIncludeSkipped();
    if (includeSkipped != IncludeRange.NONE && skippedTokens != null && !skippedTokens.isEmpty()) {
        String[] helper = new String[formattedString.length];
        for (int i = 0; i < formattedString.length; i++) {
            if (formattedString[i] == null) {
                formattedString[i] = "";
            }
            helper[i] = formattedString[i] + skippedTokens;
        }
        formattedString = helper;
    }
    if (match.checksSpelling() && lang != null) {
        List<String> formattedStringElements = Arrays.asList(formattedString);
        // tagger-based speller
        List<AnalyzedTokenReadings> analyzed = lang.getTagger().tag(formattedStringElements);
        for (int i = 0; i < formattedString.length; i++) {
            AnalyzedToken analyzedToken = analyzed.get(i).getAnalyzedToken(0);
            if (analyzedToken.getLemma() == null && analyzedToken.hasNoTag()) {
                formattedString[i] = "";
            }
        }
    }
    return formattedString;
}

From source file:edu.ehu.galan.lite.utils.wikiminer.WikiminnerHelper.java

/**
 * Relate a list of topics with the important topics of the domain
 *
 * @param pTtopicList/*from  w w w  .j a  v  a 2  s.  c o m*/
 * @param cGold
 * @param relatedness
 * @param minRelationship
 * @return
 */
public List<Comparison> parallelRelate(List<Topic> pTtopicList, List<Integer> cGold, float relatedness,
        int minRelationship) {
    List<Comparison> kust = new ArrayList<>();
    if (!localMode) {
        long timeStart = System.nanoTime();
        List<Topic> topicList = new ArrayList<>();
        Gson son = new GsonBuilder().create();
        JsonParser parser = new JsonParser();
        int i = 0;
        List<Integer> intList = new ArrayList<>();
        Comparisons ex = null;
        try {
            ProgressTracker tracker = new ProgressTracker((pTtopicList.size() / maxTopics) + 1, "....",
                    this.getClass());

            while (i < pTtopicList.size()) {
                String cacheElem = "";
                String req = wikiminerUrl + "services/compare?ids1=";
                int sum = 0;
                for (; i < pTtopicList.size(); i++) {
                    int id = (pTtopicList.get(i).getId());
                    cacheElem += id;
                    sum++;
                    req = req + id + ",";
                    if (sum == maxTopics) {
                        break;
                    }
                }
                req = req.substring(0, req.length() - 1);
                req += "&ids2=";
                for (Integer gold : cGold) {
                    req = req + gold.toString() + ",";
                    cacheElem += gold.toString();
                }
                req = req.substring(0, req.length() - 1);
                //                Element elem = cache.get(cacheElem);
                //                if (elem == null) {
                HttpGet getRequest = new HttpGet(req + "&wikipedia=" + lang + "&responseFormat=JSON");
                getRequest.addHeader("accept", "application/json");
                getRequest.addHeader("Accept-Encoding", "gzip");
                HttpResponse response = httpClient.execute(getRequest);
                GzipDecompressingEntity entity = new GzipDecompressingEntity(response.getEntity());
                String jsonText = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                EntityUtils.consume(entity);
                ex = son.fromJson(jsonText, Comparisons.class);
                //                    elem = new Element(cacheElem, ex);
                //                    cache.put(elem);
                //                } else {
                //                    ex = (Comparisons) elem.getObjectValue();
                //                }
                for (Comparison comp : ex.getComparisons()) {
                    if (cGold.contains(comp.getHighId())) {
                        comp.setHighId(null);
                        kust.add(comp);
                    } else {
                        comp.setLowId(comp.getHighId());
                        comp.setHighId(null);
                        kust.add(comp);
                    }

                }
                //                for (Integer id : ex.getIds()) {
                //                    intList.add(id);
                ////                    System.out.println(id);
                //                }
                //            }
                //            for (Integer integer : intList) {
                //                for (Topic top : pTtopicList) {
                //                    if (top.getId() == integer) {
                //                        topicList.add(top);
                //                        break;
                //                    }
                //                }
                tracker.update();
            }
            long timeEnd = System.nanoTime();
            logger.debug("Parallel Relate processed in: " + ((timeEnd - timeStart) / 1000000) + " for size: "
                    + pTtopicList.size());
            return kust;
        } catch (IOException ex1) {
            logger.error(null, ex1);
        }
        return null;
    } else {
        if (wikipedia != null) {
            ArticleComparer artComparer = null;
            try {
                artComparer = new ArticleComparer(wikipedia);
            } catch (Exception ex) {
                logger.error("Error getting article comparer for this wikipedia");
            }
            if (artComparer == null) {
                logger.error("No comparisons available for this Wikipedia");
            }
            //gather articles from ids1 ;
            TreeSet<Article> articles1 = new TreeSet<>();
            for (Topic id : pTtopicList) {
                try {
                    Article art = (Article) wikipedia.getPageById(id.getId());
                    articles1.add(art);
                } catch (Exception e) {
                    //msg.addInvalidId(id.);
                }
            }

            //gather articles from ids2 ;
            TreeSet<Article> articles2 = new TreeSet<>();
            for (Integer id : cGold) {
                try {
                    Article art = (Article) wikipedia.getPageById(id);
                    articles2.add(art);
                } catch (Exception e) {
                    //msg.addInvalidId(id);
                }
            }
            //if ids2 is not specified, then we want to compare each item in ids1 with every other one
            if (articles2.isEmpty()) {
                articles2 = articles1;
            }
            TLongHashSet doneKeys = new TLongHashSet();
            float minRelatedness = relatedness;
            //  boolean showTitles = prmTitles.getValue(request);
            for (Article a1 : articles1) {
                for (Article a2 : articles2) {
                    if (a1.equals(a2)) {
                        continue;
                    }
                    //relatedness is symmetric, so create a unique key for this pair of ids were order doesnt matter 
                    Article min, max;
                    if (a1.getId() < a2.getId()) {
                        min = a1;
                        max = a2;
                    } else {
                        min = a2;
                        max = a1;
                    }
                    //long min = Math.min(a1.getId(), a2.getId()) ;
                    //long max = Math.max(a1.getId(), a2.getId()) ;
                    long key = ((long) min.getId()) + (((long) max.getId()) << 30);
                    if (doneKeys.contains(key)) {
                        continue;
                    }
                    double related = 0;
                    try {
                        related = artComparer.getRelatedness(a1, a2);
                    } catch (Exception ex) {
                    }
                    if (relatedness >= minRelatedness) {
                        Comparison comp = new Comparison();
                        comp.setRelatedness(related);
                        comp.setHighId(max.getId());
                        comp.setLowId(min.getId());
                        if (cGold.contains(comp.getHighId())) {
                            comp.setHighId(null);
                            kust.add(comp);
                        } else {
                            comp.setLowId(comp.getHighId());
                            comp.setHighId(null);
                            kust.add(comp);
                        }
                    }

                    doneKeys.add(key);
                }
            }

            return kust;
        } else {
            return null;
        }
    }
}

From source file:net.sourceforge.fenixedu.domain.student.Student.java

final public Enrolment getDissertationEnrolment(DegreeCurricularPlan degreeCurricularPlan,
        final ExecutionYear executionYear) {
    TreeSet<Enrolment> enrolments = getDissertationEnrolments(degreeCurricularPlan);
    CollectionUtils.filter(enrolments, new Predicate() {

        @Override/*from   w  w w.j  a  v  a  2  s  . co m*/
        public boolean evaluate(Object enrolment) {
            return ((Enrolment) enrolment).getExecutionYear().equals(executionYear);
        }
    });
    return enrolments.isEmpty() ? null : enrolments.last();
}

From source file:plugin.lsttokens.DefineStatLst.java

@Override
public String[] unparse(LoadContext context, CDOMObject obj) {
    Changes<StatLock> lockChanges = context.getObjectContext().getListChanges(obj, ListKey.STAT_LOCKS);
    Changes<CDOMSingleRef<PCStat>> ulchanges = context.getObjectContext().getListChanges(obj,
            ListKey.UNLOCKED_STATS);/*ww w. j  a  va2s .c  o  m*/
    Changes<CDOMSingleRef<PCStat>> nonStatChanges = context.getObjectContext().getListChanges(obj,
            ListKey.NONSTAT_STATS);
    Changes<CDOMSingleRef<PCStat>> nonStatToStatChanges = context.getObjectContext().getListChanges(obj,
            ListKey.NONSTAT_TO_STAT_STATS);
    Changes<StatLock> minValueChanges = context.getObjectContext().getListChanges(obj, ListKey.STAT_MINVALUE);
    Changes<StatLock> maxValueChanges = context.getObjectContext().getListChanges(obj, ListKey.STAT_MAXVALUE);
    TreeSet<String> set = new TreeSet<>();
    if (lockChanges != null && !lockChanges.isEmpty()) {
        if (lockChanges.includesGlobalClear()) {
            context.addWriteMessage("DEFINE:LOCK does not support .CLEAR");
            return null;
        }
        if (lockChanges.hasAddedItems()) {
            for (StatLock sl : lockChanges.getAdded()) {
                set.add("LOCK|" + sl.getLSTformat() + Constants.PIPE + sl.getLockValue());
            }
        }
    }
    if (ulchanges != null && !ulchanges.isEmpty()) {
        if (ulchanges.includesGlobalClear()) {
            context.addWriteMessage("DEFINE:UNLOCK " + "does not support .CLEAR");
            return null;
        }
        if (ulchanges.hasAddedItems()) {
            for (CDOMSingleRef<PCStat> st : ulchanges.getAdded()) {
                set.add("UNLOCK|" + st.getLSTformat(false));
            }
        }
    }
    if (nonStatChanges != null && !nonStatChanges.isEmpty()) {
        if (nonStatChanges.hasAddedItems()) {
            for (CDOMSingleRef<PCStat> st : nonStatChanges.getAdded()) {
                set.add("NONSTAT|" + st.getLSTformat(false));
            }
        }
    }
    if (nonStatToStatChanges != null && !nonStatToStatChanges.isEmpty()) {
        if (nonStatToStatChanges.hasAddedItems()) {
            for (CDOMSingleRef<PCStat> st : nonStatToStatChanges.getAdded()) {
                set.add("STAT|" + st.getLSTformat(false));
            }
        }
    }
    if (minValueChanges != null && !minValueChanges.isEmpty()) {
        if (minValueChanges.hasAddedItems()) {
            for (StatLock sl : minValueChanges.getAdded()) {
                set.add("MINVALUE|" + sl.getLSTformat() + Constants.PIPE + sl.getLockValue());
            }
        }
    }
    if (maxValueChanges != null && !maxValueChanges.isEmpty()) {
        if (maxValueChanges.hasAddedItems()) {
            for (StatLock sl : maxValueChanges.getAdded()) {
                set.add("MAXVALUE|" + sl.getLSTformat() + Constants.PIPE + sl.getLockValue());
            }
        }
    }
    if (set.isEmpty()) {
        return null;
    }
    return set.toArray(new String[set.size()]);
}

From source file:net.sourceforge.fenixedu.domain.student.Student.java

public PersonalIngressionData getLatestPersonalIngressionData() {
    TreeSet<PersonalIngressionData> personalInformations = new TreeSet<PersonalIngressionData>(
            Collections.reverseOrder(PersonalIngressionData.COMPARATOR_BY_EXECUTION_YEAR));
    ExecutionYear currentExecutionYear = ExecutionYear.readCurrentExecutionYear();
    for (PersonalIngressionData pid : getPersonalIngressionsDataSet()) {
        if (!pid.getExecutionYear().isAfter(currentExecutionYear)) {
            personalInformations.add(pid);
        }//ww w .  jav a2s.co m
    }

    if (personalInformations.isEmpty()) {
        return null;
    }
    return personalInformations.iterator().next();
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();//from   w w  w  .j av a2 s .  c  o  m

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:org.cloudata.core.tabletserver.DiskSSTable.java

public ColumnValue findClosestMeta(Row.Key rowKey, String columnName, boolean great) throws IOException {
    lock.obtainReadLock();//from   w  w w .j  av  a 2s.co  m
    try {
        if (columnMemoryCaches.containsKey(columnName)) {
            ColumnMemoryCache cache = columnMemoryCaches.get(columnName);
            return cache.findClosest(rowKey);
        }
        List<TabletMapFile> tabletMapFiles = mapFiles.get(columnName);
        if (tabletMapFiles == null || tabletMapFiles.isEmpty()) {
            return null;
        }

        MapFileReader[] readers = new MapFileReader[tabletMapFiles.size()];

        TreeSet<MetaValue> metaValues = new TreeSet<MetaValue>();

        TreeSet<ColumnValue> workPlace = new TreeSet<ColumnValue>();

        try {
            //init
            CellFilter cellFilter = new CellFilter(columnName);
            int index = 0;
            for (TabletMapFile tabletMapFile : tabletMapFiles) {
                MapFileReader reader = tabletMapFile.getMapFileReader(rowKey, Row.Key.MAX_KEY, cellFilter);
                ColumnValue columnValue = null;
                while ((columnValue = reader.next()) != null) {
                    if (great) {
                        if (columnValue.getRowKey().compareTo(rowKey) < 0) {
                            continue;
                        }
                    } else {
                        if (columnValue.getRowKey().compareTo(rowKey) <= 0) {
                            continue;
                        }
                    }
                    break;
                }
                if (columnValue != null) {
                    workPlace.add(columnValue);
                    readers[index] = reader;
                } else {
                    reader.close();
                    readers[index] = null;
                }
                index++;
            }

            //findClosestMeta
            while (true) {
                if (workPlace.isEmpty()) {
                    return null;
                }
                ColumnValue winnerColumnValue = workPlace.first();
                metaValues.add(new MetaValue(winnerColumnValue));
                workPlace.remove(winnerColumnValue);
                Row.Key winnerRowKey = winnerColumnValue.getRowKey();

                List<ColumnValue> tempWorkPlace = new ArrayList<ColumnValue>();
                tempWorkPlace.addAll(workPlace);
                for (ColumnValue eachColumnValue : tempWorkPlace) {
                    if (winnerRowKey.equals(eachColumnValue.getRowKey())) {
                        metaValues.add(new MetaValue(eachColumnValue));
                        workPlace.remove(eachColumnValue);
                    }
                }

                for (int i = 0; i < readers.length; i++) {
                    if (readers[i] == null) {
                        continue;
                    }
                    ColumnValue columnValue = null;
                    while ((columnValue = readers[i].next()) != null) {
                        if (winnerRowKey.equals(columnValue.getRowKey())) {

                            metaValues.add(new MetaValue(columnValue));
                        } else {
                            workPlace.add(columnValue);
                            break;
                        }
                    }
                    if (columnValue == null) {
                        readers[i].close();
                        readers[i] = null;
                    }
                }

                if (metaValues.size() > 0) {
                    MetaValue firstValue = metaValues.first();
                    if (!firstValue.columnValue.isDeleted()) {
                        return firstValue.columnValue;
                    } else {
                        metaValues.clear();
                    }
                }
            }
        } finally {
            for (int i = 0; i < readers.length; i++) {
                try {
                    if (readers[i] != null) {
                        readers[i].close();
                    }
                } catch (Exception e) {
                    LOG.warn("Can't close MapFileReader:" + e.getMessage());
                }
            }
        }
    } finally {
        lock.releaseReadLock();
    }
}

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

public WMTSInfo getCapabilitiesFromWMTS(String urlServerWMTS, TreeSet<String> listCrs, boolean useCrsSelected)
        throws ServerGeoException {

    TreeSet<String> formatsSupported = new TreeSet<String>();
    TreeSet<String> crsSupported = new TreeSet<String>();
    boolean isFormatsSupported = false;

    WMTSInfo wmtsInfo = new WMTSInfo();
    // put url on object WMSInfo
    wmtsInfo.setServiceUrl(urlServerWMTS);

    // Create hashmap to add the layers getted to the WMTSInfo object
    Map<String, org.gvsig.framework.web.ogc.WMTSLayer> layersMap = new HashMap<String, org.gvsig.framework.web.ogc.WMTSLayer>();

    // get WMTS manager
    WMTSOGCManager wmtsMan = WMTSOGCLocator.getManager();

    try {//  w  w  w .j a v a2s .  c o m
        WMTSClient wmtsClient = wmtsMan.createWMTSClient(urlServerWMTS);
        wmtsClient.connect(true, null);

        WMTSServiceIdentification wmtsServIden = wmtsClient.getServiceIdentification();

        // set server info
        wmtsInfo.setServiceAbstract(wmtsServIden.getAbstract());
        wmtsInfo.setServiceTitle(wmtsServIden.getTitle());
        wmtsInfo.setVersion(wmtsServIden.getServiceTypeVersion());
        wmtsInfo.setServiceType(wmtsServIden.getServiceType());

        // set id of the request wmst (service title + calendar)
        int hashCode = (wmtsServIden.getTitle() + Calendar.getInstance()).hashCode();
        wmtsInfo.setId(hashCode);

        // set tile matrix and check if has support to crs of the map
        List<String> patternList = new ArrayList<String>();
        if (!listCrs.isEmpty()) {
            for (String crs : listCrs) {
                String[] crsSplit = crs.split(":");
                String pattern = "(.*)(:?)".concat(crsSplit[0]).concat("((:)(.*)(:)").concat(crsSplit[1])
                        .concat("|(:)").concat(crsSplit[1]).concat(")");
                patternList.add(pattern);
            }
        }

        // hashmap with: identifier of tile matrix, supported crs
        Map<String, String> tileMatrixCrsSupported = new HashMap<String, String>();
        TreeSet<String> tileMatrixSelectedId = new TreeSet<String>();
        List<WMTSTileMatrixSet> tileMatrixSet = wmtsClient.getTileMatrixSet();
        for (int i = 0; i < tileMatrixSet.size(); i++) {
            WMTSTileMatrixSet tileMatrix = tileMatrixSet.get(i);
            String identifier = tileMatrix.getIdentifier();
            String supportedCRS = tileMatrix.getSupportedCRS();
            crsSupported.add(supportedCRS);
            // add to map the tile matrix with its crs supported
            tileMatrixCrsSupported.put(identifier, supportedCRS);
            if (!listCrs.isEmpty()) {
                if (listCrs.contains(supportedCRS)) {
                    tileMatrixSelectedId.add(identifier);
                } else {
                    // check supportedCrs with the expReg generated by the
                    // list of crs passed
                    for (String expReg : patternList) {
                        if (supportedCRS.matches(expReg)) {
                            tileMatrixSelectedId.add(identifier);
                        }
                    }
                }
            }
        }
        // Add map of tile matrix and the tile matrix selected to WMTSInfo
        // object
        wmtsInfo.setTileMatrixCrsSupported(tileMatrixCrsSupported);
        wmtsInfo.setTileMatrixSelectedId(tileMatrixSelectedId);

        // Only set layers if has a tile matrix with crs of the map
        // supported
        // or crs is null
        WMTSThemes layerListAsThemes = wmtsClient.getLayerListAsThemes();
        // Create tree with layer values
        List<TreeNode> tree = new ArrayList<TreeNode>();

        // Create children layers
        for (int i = 0; i < layerListAsThemes.getChildCount(); i++) {
            WMTSTheme wmtsTheme = layerListAsThemes.getChildren(i);
            WMTSLayer layer = wmtsTheme.getLayer();
            TreeSet<String> wmtsLinkSelected = new TreeSet<String>();
            TreeSet<String> wmtsLinkSupported = new TreeSet<String>();
            // check crs
            List<WMTSTileMatrixSetLink> tileMatrixSetLink = layer.getTileMatrixSetLink();
            for (int j = 0; j < tileMatrixSetLink.size(); j++) {
                WMTSTileMatrixSetLink wmtsLink = tileMatrixSetLink.get(j);
                wmtsLinkSupported.add(wmtsLink.getTileMatrixSetId());
                if (!tileMatrixSelectedId.isEmpty()
                        && tileMatrixSelectedId.contains(wmtsLink.getTileMatrixSetId())) {
                    wmtsLinkSelected.add(wmtsLink.getTileMatrixSetId());
                }
            }
            // check format
            TreeSet<String> setFormats = new TreeSet<String>();
            setFormats.addAll(layer.getFormat());
            String format = getFirstFormatSupported(setFormats);
            formatsSupported.addAll(setFormats);
            if ((!wmtsLinkSelected.isEmpty() || listCrs.isEmpty()) && format != null) {
                isFormatsSupported = true;
                TreeNode node = new TreeNode(layer.getIdentifier());
                node.setTitle(layer.getTitle());
                node.setFolder(false);
                tree.add(node);

                // Add layer to layer map
                org.gvsig.framework.web.ogc.WMTSLayer wmtsLayer = new org.gvsig.framework.web.ogc.WMTSLayer();
                TreeSet<String> crsSet = new TreeSet<String>();
                crsSet.addAll(layer.getSrsList());
                wmtsLayer.setCrs(crsSet);
                wmtsLayer.setName(layer.getIdentifier());
                wmtsLayer.setTitle(layer.getTitle());
                wmtsLayer.setFormatSelected(format);
                wmtsLayer.setFormatsSupported(setFormats);
                if (listCrs.isEmpty()) {
                    wmtsLayer.setTileMatrixSelected(wmtsLinkSupported);
                } else {
                    wmtsLayer.setTileMatrixSelected(wmtsLinkSelected);
                }
                layersMap.put(layer.getIdentifier(), wmtsLayer);
            }
        }
        wmtsInfo.setFormatsSupported(formatsSupported);
        wmtsInfo.setLayersTree(tree);
        wmtsInfo.setLayers(layersMap);
        wmtsInfo.setIsFormatsSupported(isFormatsSupported);
        wmtsInfo.setCrsSupported(crsSupported);
    } catch (Exception exc) {
        logger.error("Exception on getCapabilitiesFromWMS", exc);
        throw new ServerGeoException();
    }

    return wmtsInfo;
}

From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java

private void _writeAccessibilityGuidelines(Writer out, ComponentBean bean) throws IOException {
    // accAttributes and accFacets are sorted lists of attributes and facets, respectively,
    // that have an associated accessibility guideline
    TreeSet<PropertyBean> accAttributes = new TreeSet<PropertyBean>();
    TreeSet<String> accFacets = new TreeSet<String>();

    // see if any of the component's properties has an associated accessibility guideline
    Iterator<PropertyBean> attrs = bean.properties();
    while (attrs.hasNext()) {
        PropertyBean property = attrs.next();
        if (!property.isTagAttributeExcluded() && property.hasAccessibilityGuidelines()) {
            accAttributes.add(property);
        }/*  ww  w  .j a  va 2 s .com*/
    }

    // see if any of the component's facets has an associated accessibility guideline
    if (bean.hasFacets()) {
        Iterator<FacetBean> facets = bean.facets(true);
        while (facets.hasNext()) {
            FacetBean facetBean = facets.next();
            if (!facetBean.isHidden() && facetBean.hasAccessibilityGuidelines()) {
                accFacets.add(facetBean.getFacetName());
            }
        }
    }

    // if neither the component nor the component's attributes nor the component's facets
    // has an accessibility guideline, return
    if (!bean.hasAccessibilityGuidelines() && accAttributes.isEmpty() && accFacets.isEmpty())
        return;

    String accGuideline;

    // Write header
    out.write(" <section name=\"Accessibility Guideline(s)\">\n");
    out.write(" <p>\n");
    out.write("   <html>\n");
    out.write("     <ul>");

    // write out component-generic accessibility guidelines, i.e. accessibility
    // guidelines that apply to the component as a whole, not associated with a
    // specific attribute
    if (bean.hasAccessibilityGuidelines()) {
        Iterator<String> iter = bean.accessibilityGuidelines();
        while (iter.hasNext()) {
            accGuideline = iter.next();
            _writeAccessibilityGuideline(out, "", accGuideline);
        }
    }

    // Write out attribute-specific accessibility guidelines.  Each attribute can have
    // one or more associated accessibility guidelines.
    if (!accAttributes.isEmpty()) {
        Iterator<PropertyBean> propIter = accAttributes.iterator();
        while (propIter.hasNext()) {
            PropertyBean property = propIter.next();
            Iterator<String> propAccIter = property.accessibilityGuidelines();
            while (propAccIter.hasNext()) {
                accGuideline = propAccIter.next();
                _writeAccessibilityGuideline(out, property.getPropertyName() + " attribute", accGuideline);
            }
        }
    }

    // Write out facet-specific accessibility guidelines. A facet in the accFacets iterator
    // can have one or more associated accessibility guidelines
    if (!accFacets.isEmpty()) {
        Iterator<String> facetIter = accFacets.iterator();
        while (facetIter.hasNext()) {
            String facetName = facetIter.next();
            FacetBean facet = bean.findFacet(facetName, true);

            Iterator<String> facetAccIter = facet.accessibilityGuidelines();
            while (facetAccIter.hasNext()) {
                accGuideline = facetAccIter.next();
                _writeAccessibilityGuideline(out, facetName + " facet", accGuideline);
            }
        }
    }

    out.write("     </ul>");
    out.write("   </html>\n");
    out.write(" </p>\n");
    out.write(" </section>\n");
}

From source file:org.wso2.andes.kernel.slot.SlotManager.java

/**
 * Re-assign the slot when there are no local subscribers in the node
 *
 * @param nodeId    node ID of the node without subscribers
 * @param queueName name of the queue whose slots to be reassigned
 *//* w ww.  jav  a2 s .c o m*/
public void reAssignSlotWhenNoSubscribers(String nodeId, String queueName) {
    TreeSet<Slot> assignedSlotList = null;
    String lockKeyForNodeId = nodeId + SlotManager.class;
    synchronized (lockKeyForNodeId.intern()) {

        //Get assigned slots from Hazelcast, delete all belonging to queue
        //and set back
        HashmapStringTreeSetWrapper wrapper = slotAssignmentMap.get(nodeId);
        HashMap<String, TreeSet<Slot>> queueToSlotMap = null;
        if (wrapper != null) {
            queueToSlotMap = wrapper.getStringListHashMap();
        }
        if (queueToSlotMap != null) {
            assignedSlotList = queueToSlotMap.remove(queueName);
            wrapper.setStringListHashMap(queueToSlotMap);
            slotAssignmentMap.set(nodeId, wrapper);
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleared assigned slots of queue " + queueName + " Assigned to node " + nodeId);
        }

        //Get overlapped slots from Hazelcast, delete all belonging to queue and
        //set back
        HashmapStringTreeSetWrapper overlappedSlotWrapper = overLappedSlotMap.get(nodeId);
        HashMap<String, TreeSet<Slot>> queueToOverlappedSlotMap = null;
        if (overlappedSlotWrapper != null) {
            queueToOverlappedSlotMap = overlappedSlotWrapper.getStringListHashMap();
        }
        if (queueToOverlappedSlotMap != null) {
            assignedSlotList = queueToOverlappedSlotMap.remove(queueName);
            overlappedSlotWrapper.setStringListHashMap(queueToOverlappedSlotMap);
            overLappedSlotMap.set(nodeId, overlappedSlotWrapper);
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleared overlapped slots of queue " + queueName + " to be assigned to " + "node "
                    + nodeId);
        }

    }

    //add the deleted slots to un-assigned slot map, so that they can be assigned again.
    if (assignedSlotList != null && !assignedSlotList.isEmpty()) {
        String lockKeyForQueueName = queueName + SlotManager.class;
        synchronized (lockKeyForQueueName.intern()) {
            TreeSetSlotWrapper treeSetStringWrapper = unAssignedSlotMap.get(queueName);

            TreeSet<Slot> unAssignedSlotSet = new TreeSet<Slot>();
            if (treeSetStringWrapper != null) {
                unAssignedSlotSet = treeSetStringWrapper.getSlotTreeSet();
            } else {
                treeSetStringWrapper = new TreeSetSlotWrapper();
            }
            if (unAssignedSlotSet == null) {
                unAssignedSlotSet = new TreeSet<Slot>();
            }
            for (Slot slotToBeReAssigned : assignedSlotList) {
                //Reassign only if the slot is not empty
                if (!SlotUtils.checkSlotEmptyFromMessageStore(slotToBeReAssigned)) {
                    if (slotToBeReAssigned.addState(SlotState.RETURNED)) {
                        unAssignedSlotSet.add(slotToBeReAssigned);
                        if (log.isDebugEnabled()) {
                            log.debug("Slot is returned by node " + nodeId + " slot = " + slotToBeReAssigned);
                        }
                    }
                }
            }
            treeSetStringWrapper.setSlotTreeSet(unAssignedSlotSet);
            unAssignedSlotMap.set(queueName, treeSetStringWrapper);
        }
    }
}