Example usage for java.util TreeSet toArray

List of usage examples for java.util TreeSet toArray

Introduction

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

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

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);//from   w ww  . java 2  s.  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:org.languagetool.rules.patterns.MatchState.java

/**
 * Gets all strings formatted using the match element.
 *//*from   ww  w.  ja  v  a  2 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:org.apache.hadoop.hbase.regionserver.HRegionServer.java

public String[] getRegionServerCoprocessors() {
    TreeSet<String> coprocessors = new TreeSet<String>(this.hlog.getCoprocessorHost().getCoprocessors());
    Collection<HRegion> regions = getOnlineRegionsLocalContext();
    for (HRegion region : regions) {
        coprocessors.addAll(region.getCoprocessorHost().getCoprocessors());
    }/*w ww  .ja v a 2 s  .  co  m*/
    return coprocessors.toArray(new String[coprocessors.size()]);
}

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;
    }//from   w  ww .j a  v a2s .  c  o 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:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.GetEngine.java

/**
 * Prepare the results returned from the server for processing in the main
 * get loop.//  ww  w  .j ava2 s. co m
 *
 */
private GetOperation[] prepareGetOperations(final AsyncGetOperation asyncOp, final GetOperation[][] results) {
    Check.notNull(asyncOp, "asyncOp"); //$NON-NLS-1$
    Check.notNull(results, "results"); //$NON-NLS-1$

    /*
     * The common case is a single result, and we do not want to slow that
     * down. In the case where there are multiple requests (and thus
     * multiple results), we need to filter to make sure that we don't have
     * redundant getOps.
     */
    Map<String, GetOperation> newLocalItemHash = null;
    if (results.length > 1) {
        newLocalItemHash = new TreeMap<String, GetOperation>(LocalPath.TOP_DOWN_COMPARATOR);
    }

    System.currentTimeMillis();
    for (int i = 0; i < results.length; i++) {
        final GetOperation[] tempGetOps = results[i];

        for (final GetOperation getOp : tempGetOps) {
            /*
             * We need to build a hashtable of getOps that have a source
             * that is an existing item. In the multiple result case, we
             * also need to filter out redundant getOps. Each local item
             * currently on disk can only have one operation. Also, each
             * target local item can have only one operation. They must be
             * considered separately.
             */
            final String sourceLocalItem = getOp.getSourceLocalItem();
            if (sourceLocalItem != null) {
                if (results.length == 1) {
                    if (!asyncOp.getExistingLocalHash().containsKey(sourceLocalItem)) {
                        asyncOp.getExistingLocalHash().put(sourceLocalItem, getOp);
                    } else {
                        // This is a server problem.
                        onNonFatalError(new Exception(MessageFormat.format(
                                //@formatter:off
                                Messages.getString(
                                        "GetEngine.ServerGateUsTwoGetOperationsForSameLocalPathMayRequireMultipleGetsFormat"), //$NON-NLS-1$
                                //@formatter:on
                                sourceLocalItem)));
                    }
                } else {
                    // I think this test is redundant because of the test
                    // above
                    if (sourceLocalItem != null) {
                        if (!asyncOp.getExistingLocalHash().containsKey(sourceLocalItem)) {
                            asyncOp.getExistingLocalHash().put(sourceLocalItem, getOp);
                        } else {
                            final GetOperation existingOp = asyncOp.getExistingLocalHash().get(sourceLocalItem);

                            /*
                             * favor the get operation which has a target
                             * local item this happens in the case when the
                             * caller does 2 scoped gets See bug 416603 for
                             * details
                             */
                            if (existingOp.getTargetLocalItem() == null && getOp.getTargetLocalItem() != null) {
                                asyncOp.getExistingLocalHash().put(sourceLocalItem, getOp);
                            }
                        }
                    }
                }
            } else if (results.length != 1) {
                final String newLocalItem = getOp.getTargetLocalItem();
                if (newLocalItem != null && !newLocalItemHash.containsKey(newLocalItem)) {
                    newLocalItemHash.put(newLocalItem, getOp);
                }
            }
        }
    }

    /*
     * Since JDK 1.7 {@link Arrays.sort} algorithm has changed:
     *
     * The implementation was adapted from Tim Peters's list sort for Python
     * (<a href=
     * "http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
     * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic
     * Sorting and Information Theoretic Complexity", in Proceedings of the
     * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
     * January 1993.
     *
     * For some unknown reason the new implementation is not compatible with
     * the {@link GetOperation}'s compareTo method. We have to use another
     * means to get an ordered list of operation, e.g. to utilize {@link
     * TreeSet}.
     */

    // Sort the get operations for execution. Note that HatGui's cache
    // model relies on this.
    final TreeSet<GetOperation> getOps = new TreeSet<GetOperation>(GetOperation.GET_OPERATION_COMPARATOR);

    // Again, we've optimized the case of a single result.
    if (results.length == 1) {
        getOps.addAll(Arrays.asList(results[0]));
    } else {
        // copy our get ops to the output sorted set
        getOps.addAll(asyncOp.getExistingLocalHash().values());
        getOps.addAll(newLocalItemHash.values());
    }

    // Record the total number of operations for use in the events.
    asyncOp.totalNumOperations = getOps.size();

    return getOps.toArray(new GetOperation[getOps.size()]);
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings("unchecked")
static public PersistentCache<? extends CachedItem> getCacheWithSchema(
        @Nonnull Class<? extends CachedItem> forClass, @Nullable String alternateEntytName,
        @Nonnull String primaryKey, @Nonnull String schemaVersion, @Nullable SchemaMapper... mappers)
        throws PersistenceException {
    PersistentCache<? extends CachedItem> cache = null;
    String className = forClass.getName();

    synchronized (caches) {
        cache = caches.get(className);//from w w w .  j ava 2s .  com
        if (cache != null) {
            return cache;
        }
    }

    Properties props = new Properties();

    try {
        InputStream is = DaseinSequencer.class.getResourceAsStream(DaseinSequencer.PROPERTIES);

        if (is != null) {
            props.load(is);
        }
    } catch (Exception e) {
        logger.error("Problem reading " + DaseinSequencer.PROPERTIES + ": " + e.getMessage(), e);
    }

    TreeSet<Key> keys = new TreeSet<Key>();
    Class<?> cls = forClass;

    while (!cls.getName().equals(Object.class.getName())) {
        for (Field field : cls.getDeclaredFields()) {
            for (Annotation annotation : field.getDeclaredAnnotations()) {
                if (annotation instanceof Index) {

                    if (logger.isDebugEnabled()) {
                        logger.debug("Processing Index for: " + cls.getName() + "." + field.getName());
                    }

                    Index idx = (Index) annotation;

                    if (logger.isDebugEnabled()) {
                        logger.debug("Index is: " + idx);
                    }

                    if (idx.type().equals(IndexType.SECONDARY) || idx.type().equals(IndexType.FOREIGN)) {
                        String keyName = field.getName();

                        if (idx.multi() != null && idx.multi().length > 0) {
                            if (idx.cascade()) {
                                int len = idx.multi().length;

                                keys.add(new Key(keyName));
                                for (int i = 0; i < len; i++) {
                                    String[] parts = new String[i + 2];

                                    parts[0] = keyName;
                                    for (int j = 0; j <= i; j++) {
                                        parts[j + 1] = idx.multi()[j];
                                    }
                                    keys.add(new Key(parts));
                                }
                            } else {
                                String[] parts = new String[idx.multi().length + 1];
                                int i = 1;

                                parts[0] = keyName;
                                for (String name : idx.multi()) {
                                    parts[i++] = name;
                                }
                                Key k = new Key(parts);

                                keys.add(k);
                            }
                        } else {
                            Key k;

                            if (idx.type().equals(IndexType.FOREIGN)
                                    && !idx.identifies().equals(CachedItem.class)) {
                                k = new Key(idx.identifies(), keyName);
                            } else {
                                k = new Key(keyName);
                            }
                            keys.add(k);
                        }
                    }
                }
            }
        }
        cls = cls.getSuperclass();
    }
    String propKey = "dsn.persistentCache." + className;
    String prop;

    while (cache == null && !propKey.equals("dsn.persistentCache")) {
        prop = props.getProperty(propKey);
        if (prop != null) {
            try {
                cache = (PersistentCache<? extends CachedItem>) Class.forName(prop).newInstance();
                cache.initBase(forClass, alternateEntytName, schemaVersion, mappers, new Key(primaryKey),
                        keys.toArray(new Key[keys.size()]));
                break;
            } catch (Throwable t) {
                logger.error("Unable to load persistence cache " + prop + ": " + t.getMessage());
                throw new PersistenceException(
                        "Unable to load persistence cache " + prop + ": " + t.getMessage());
            }
        }
        int idx = propKey.lastIndexOf('.');

        propKey = propKey.substring(0, idx);
    }
    if (cache == null) {
        prop = props.getProperty("dsn.cache.default");
        if (prop == null) {
            throw new PersistenceException("No persistent cache implementations defined.");
        }
        try {
            cache = (PersistentCache<? extends CachedItem>) Class.forName(prop).newInstance();
            cache.initBase(forClass, alternateEntytName, schemaVersion, mappers, new Key(primaryKey),
                    keys.toArray(new Key[keys.size()]));
        } catch (Throwable t) {
            String err = "Unable to load persistence cache " + prop + ": " + t.getMessage();
            logger.error(err, t);
            throw new PersistenceException(err);
        }
    }
    synchronized (caches) {
        PersistentCache<? extends CachedItem> c = caches.get(className);

        if (c != null) {
            cache = c;
        } else {
            caches.put(className, cache);
        }
    }
    return cache;
}

From source file:ddf.catalog.source.solr.SolrProviderTest.java

@Test
public void testStartIndexWithSorting() throws Exception {
    deleteAllIn(provider);//  w  w  w .  ja  va2 s  .co  m

    List<Metacard> metacards = new ArrayList<Metacard>();

    DateTime dt = new DateTime(1985, 1, 1, 1, 1, 1, 1, DateTimeZone.UTC);

    TreeSet<Date> calculatedDates = new TreeSet<Date>();

    for (int j = 0; j < 10; j++) {
        for (int i = 0; i < 100; i = i + 10) {

            MetacardImpl metacard = new MockMetacard(Library.getFlagstaffRecord());

            // ingest sporadically the effective dates so the default return
            // order won't be ordered
            Date calculatedDate = dt.plusDays(100 - i + 10 - j).toDate();
            calculatedDates.add(calculatedDate);
            metacard.setEffectiveDate(calculatedDate);
            metacards.add(metacard);

        }
    }

    // The TreeSet will sort them, the array will give me access to everyone
    // without an iterator
    Date[] dates = new Date[calculatedDates.size()];
    calculatedDates.toArray(dates);

    /** CREATE **/
    CreateResponse response = create(metacards);

    LOGGER.info("CREATED {} records.", response.getCreatedMetacards().size());

    CommonQueryBuilder queryBuilder = new CommonQueryBuilder();

    QueryImpl query = queryBuilder.queryByProperty(Metacard.CONTENT_TYPE, MockMetacard.DEFAULT_TYPE);

    int maxSize = 20;
    int startIndex = 2;

    // STARTINDEX=2, MAXSIZE=20
    query.setPageSize(maxSize);
    query.setStartIndex(startIndex);
    SortByImpl sortBy = new SortByImpl(queryBuilder.filterFactory.property(Metacard.EFFECTIVE),
            org.opengis.filter.sort.SortOrder.ASCENDING);
    query.setSortBy(sortBy);

    SourceResponse sourceResponse = provider.query(new QueryRequestImpl(query));

    assertEquals(maxSize, sourceResponse.getResults().size());

    for (int i = 0; i < sourceResponse.getResults().size(); i++) {

        Result r = sourceResponse.getResults().get(i);

        Date effectiveDate = r.getMetacard().getEffectiveDate();

        DateTime currentDate = new DateTime(effectiveDate.getTime());

        LOGGER.debug("Testing current index: {}", startIndex + i);

        assertEquals(new DateTime(dates[startIndex - 1 + i].getTime()).getDayOfYear(),
                currentDate.getDayOfYear());

    }

    // STARTINDEX=20, MAXSIZE=5
    // a match-all queryByProperty
    query = queryBuilder.queryByProperty(Metacard.CONTENT_TYPE, MockMetacard.DEFAULT_TYPE);

    maxSize = 5;
    startIndex = 20;
    query.setPageSize(maxSize);
    query.setStartIndex(startIndex);
    sortBy = new SortByImpl(queryBuilder.filterFactory.property(Metacard.EFFECTIVE),
            org.opengis.filter.sort.SortOrder.ASCENDING);
    query.setSortBy(sortBy);

    sourceResponse = provider.query(new QueryRequestImpl(query));

    assertEquals(maxSize, sourceResponse.getResults().size());

    for (int i = 0; i < sourceResponse.getResults().size(); i++) {

        Result r = sourceResponse.getResults().get(i);

        Date effectiveDate = r.getMetacard().getEffectiveDate();

        DateTime currentDate = new DateTime(effectiveDate.getTime());

        LOGGER.debug("Testing current index: {}", startIndex + i);

        assertEquals(new DateTime(dates[startIndex - 1 + i].getTime()).getDayOfYear(),
                currentDate.getDayOfYear());

    }

    // STARTINDEX=80, MAXSIZE=20
    // a match-all queryByProperty
    query = queryBuilder.queryByProperty(Metacard.CONTENT_TYPE, MockMetacard.DEFAULT_TYPE);

    maxSize = 20;
    startIndex = 80;
    query.setPageSize(maxSize);
    query.setStartIndex(startIndex);
    sortBy = new SortByImpl(queryBuilder.filterFactory.property(Metacard.EFFECTIVE),
            org.opengis.filter.sort.SortOrder.ASCENDING);
    query.setSortBy(sortBy);

    sourceResponse = provider.query(new QueryRequestImpl(query));

    assertEquals(maxSize, sourceResponse.getResults().size());

    for (int i = 0; i < sourceResponse.getResults().size(); i++) {

        Result r = sourceResponse.getResults().get(i);

        Date effectiveDate = r.getMetacard().getEffectiveDate();

        DateTime currentDate = new DateTime(effectiveDate.getTime());

        LOGGER.debug("Testing current index: {}", startIndex + i);

        assertEquals(new DateTime(dates[startIndex - 1 + i].getTime()).getDayOfYear(),
                currentDate.getDayOfYear());

    }

    // STARTINDEX=1, MAXSIZE=100
    // a match-all queryByProperty
    query = queryBuilder.queryByProperty(Metacard.CONTENT_TYPE, MockMetacard.DEFAULT_TYPE);

    maxSize = 100;
    startIndex = 1;
    query.setPageSize(maxSize);
    query.setStartIndex(startIndex);
    sortBy = new SortByImpl(queryBuilder.filterFactory.property(Metacard.EFFECTIVE),
            org.opengis.filter.sort.SortOrder.ASCENDING);
    query.setSortBy(sortBy);

    sourceResponse = provider.query(new QueryRequestImpl(query));

    assertEquals(maxSize, sourceResponse.getResults().size());

    for (int i = 0; i < sourceResponse.getResults().size(); i++) {

        Result r = sourceResponse.getResults().get(i);

        Date effectiveDate = r.getMetacard().getEffectiveDate();

        DateTime currentDate = new DateTime(effectiveDate.getTime());

        LOGGER.debug("Testing current index: {}", startIndex + i);

        assertEquals(new DateTime(dates[startIndex - 1 + i].getTime()).getDayOfYear(),
                currentDate.getDayOfYear());

    }
}

From source file:org.wso2.carbon.service.mgt.ServiceGroupAdmin.java

/**
 * List all the available service groups
 *
 * @param pageNumber The number of the page to be retrieved
 * @return The service group metadata/*from  www  .  j  a  v a  2  s.co m*/
 * @throws org.apache.axis2.AxisFault If an error occurs while retrieving service groups
 */
public ServiceGroupMetaDataWrapper listServiceGroups(String serviceTypeFilter, String serviceGroupSearchString,
        int pageNumber) throws AxisFault {
    if (serviceTypeFilter == null) {
        serviceTypeFilter = "ALL";
    }
    if (pageNumber < 0 || pageNumber == Integer.MAX_VALUE) {
        pageNumber = 0;
    }
    List<ServiceGroupMetaData> sgList = new ArrayList<ServiceGroupMetaData>();
    TreeSet<String> serviceTypes = new TreeSet<String>();
    serviceTypes.add("axis2");

    List<AxisServiceGroup> axisServiceGroupList = new ArrayList<AxisServiceGroup>();

    for (Iterator sgs = getAxisConfig().getServiceGroups(); sgs.hasNext();) {
        AxisServiceGroup serviceGroup = (AxisServiceGroup) sgs.next();
        // Filtering the admin services
        if (SystemFilter.isFilteredOutService(serviceGroup)) {
            continue; // No advancement of currentIndex
        }
        String serviceType = "axis2";
        Parameter serviceTypeParam;
        if (serviceGroup.getServices().hasNext()) {
            serviceTypeParam = (serviceGroup.getServices().next()).getParameter(ServerConstants.SERVICE_TYPE);
            if (serviceTypeParam != null) {
                serviceType = (String) serviceTypeParam.getValue();
                serviceTypes.add(serviceType);
            }
        }
        if (!serviceTypeFilter.equals("ALL")) {
            if (!serviceTypeFilter.equals(serviceType)) {
                continue;
            }
        }
        if (serviceGroupSearchString != null && serviceGroupSearchString.trim().length() > 0 && !serviceGroup
                .getServiceGroupName().toLowerCase().contains(serviceGroupSearchString.toLowerCase())) {
            continue;
        }
        boolean isClientSide = false;
        int noOfServices = 0;
        for (Iterator serviceIter = serviceGroup.getServices(); serviceIter.hasNext();) {
            AxisService axisService = (AxisService) serviceIter.next();
            if (axisService.isClientSide()) {
                isClientSide = true;
                break;
            }
            noOfServices++;
        }
        if (noOfServices == 0 || isClientSide) {
            continue; // No advancement of currentIndex
        }
        axisServiceGroupList.add(serviceGroup);
    }

    if (axisServiceGroupList.size() > 0) {
        Collections.sort(axisServiceGroupList, new Comparator<AxisServiceGroup>() {
            public int compare(AxisServiceGroup arg0, AxisServiceGroup arg1) {
                return arg0.getServiceGroupName().compareToIgnoreCase(arg1.getServiceGroupName());
            }
        });
    }
    //
    //        String itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage");
    //        int itemsPerPageInt = 10; // the default number of item per page
    //        if (itemsPerPage != null) {
    //            itemsPerPageInt = Integer.parseInt(itemsPerPage);
    //        }
    //        int startIndex = pageNumber * itemsPerPageInt;
    //        int endIndex = (pageNumber + 1) * itemsPerPageInt;

    List<AxisServiceGroup> axisServiceGroupsRequiredForPage = new ArrayList<AxisServiceGroup>();
    //        for (int i = startIndex; i < endIndex && i < axisServiceGroupList.size(); i++) {
    //            axisServiceGroupsRequiredForPage.add(axisServiceGroupList.get(i));
    //        }
    for (AxisServiceGroup anAxisServiceGroupList : axisServiceGroupList) {
        axisServiceGroupsRequiredForPage.add(anAxisServiceGroupList);
    }
    for (AxisServiceGroup serviceGroup : axisServiceGroupsRequiredForPage) {
        String serviceType = "axis2";
        Parameter serviceTypeParam;
        if (serviceGroup.getServices().hasNext()) {
            serviceTypeParam = (serviceGroup.getServices().next()).getParameter(ServerConstants.SERVICE_TYPE);
            if (serviceTypeParam != null) {
                serviceType = (String) serviceTypeParam.getValue();
                serviceTypes.add(serviceType);
            }
        }

        ServiceGroupMetaData sgMetaData = new ServiceGroupMetaData();

        List<ServiceMetaData> services = new ArrayList<ServiceMetaData>();
        for (Iterator serviceIter = serviceGroup.getServices(); serviceIter.hasNext();) {
            AxisService axisService = (AxisService) serviceIter.next();

            ServiceMetaData service = new ServiceMetaData();
            String serviceName = axisService.getName();
            service.setName(serviceName);

            // extract service type
            serviceTypeParam = axisService.getParameter(ServerConstants.SERVICE_TYPE);
            if (serviceTypeParam != null) {
                serviceType = (String) serviceTypeParam.getValue();
            }
            service.setServiceType(serviceType);
            AxisConfiguration axisConfiguration = getAxisConfig();
            service.setWsdlURLs(Utils.getWsdlInformation(serviceName, axisConfiguration));
            service.setTryitURL(Utils.getTryitURL(serviceName, getConfigContext()));
            service.setActive(axisService.isActive());
            Parameter parameter = axisService.getParameter(ServiceAdmin.DISABLE_TRY_IT_PARAM);
            if (parameter != null && Boolean.TRUE.toString().equalsIgnoreCase((String) parameter.getValue())) {
                service.setDisableTryit(true);
            }
            parameter = axisService.getParameter(ServiceAdmin.DISABLE_DELETION_PARAM);
            if (parameter != null && Boolean.TRUE.toString().equalsIgnoreCase((String) parameter.getValue())) {
                sgMetaData.setDisableDeletion(true);
            }
            services.add(service);
        }

        String sgName = serviceGroup.getServiceGroupName();
        sgMetaData.setServices(services.toArray(new ServiceMetaData[services.size()]));
        sgMetaData.setServiceGroupName(sgName);
        sgMetaData.setServiceContextPath(getConfigContext().getServiceContextPath());
        Parameter parameter = serviceGroup.getParameter(Constants.Configuration.ENABLE_MTOM);
        if (parameter != null) {
            sgMetaData.setMtomStatus((String) parameter.getValue());
        } else {
            sgMetaData.setMtomStatus("false");
        }
        sgList.add(sgMetaData);
    }

    ServiceGroupMetaDataWrapper wrapper;
    wrapper = new ServiceGroupMetaDataWrapper();
    wrapper.setNumberOfCorrectServiceGroups(sgList.size());
    wrapper.setNumberOfFaultyServiceGroups(getAxisConfig().getFaultyServices().size());
    wrapper.setServiceTypes(serviceTypes.toArray(new String[serviceTypes.size()]));
    try {
        wrapper.setNumberOfActiveServices(new ServiceAdmin(getAxisConfig()).getNumberOfActiveServices());
    } catch (Exception e) {
        throw new AxisFault("Cannot get active services from ServiceAdmin", e);
    }
    //   DataPaginator.doPaging(pageNumber, axisServiceGroupList, sgList, wrapper);
    DataPaginator.doPaging(pageNumber, sgList, wrapper);
    return wrapper;
}

From source file:org.wso2.carbon.service.mgt.ServiceAdmin.java

/**
 * List all the available services//from   ww  w.jav a 2 s.  co  m
 *
 * @param serviceTypeFilter   Service type of services to be returned
 * @param serviceSearchString Service name or part of a service name
 * @param pageNumber          The number of the page to be retrieved
 * @return The service metadata
 * @throws org.apache.axis2.AxisFault If an error occurs while retrieving services
 */
public ServiceMetaDataWrapper listServices(String serviceTypeFilter, String serviceSearchString, int pageNumber)
        throws AxisFault {
    if (serviceTypeFilter == null) {
        serviceTypeFilter = "ALL";
    }
    if (pageNumber < 0 || pageNumber == Integer.MAX_VALUE) {
        pageNumber = 0;
    }
    List<ServiceMetaData> serviceList = new ArrayList<ServiceMetaData>();
    TreeSet<String> serviceTypes = new TreeSet<String>();
    serviceTypes.add("axis2");

    HashMap<String, AxisService> axisServices = getAxisConfig().getServices();
    Set<String> axisFaultServices = (getAxisConfig().getFaultyServices()).keySet();
    List<AxisService> axisServicesList = new ArrayList<AxisService>();

    // we have to check services in transit ghost state as well..
    Map<String, AxisService> originalTransitGhosts = GhostDeployerUtils
            .getTransitGhostServicesMap(getAxisConfig());
    Map<String, AxisService> clonedTransitGhosts = new HashMap<String, AxisService>();
    clonedTransitGhosts.putAll(originalTransitGhosts);

    for (Map.Entry<String, AxisService> entry : axisServices.entrySet()) {
        AxisService axisService = entry.getValue();
        // Filtering the admin services
        if (SystemFilter.isAdminService(axisService) || SystemFilter.isHiddenService(axisService)) {
            continue; // No advancement of currentIndex
        }
        String serviceType = "axis2";
        Parameter serviceTypeParam;
        serviceTypeParam = axisService.getParameter(ServerConstants.SERVICE_TYPE);
        if (serviceTypeParam != null) {
            serviceType = (String) serviceTypeParam.getValue();
            serviceTypes.add(serviceType);
        }
        // Filter out client side services
        if (axisService.isClientSide()) {
            continue;
        }
        // Filter out services based on service type
        if (!serviceTypeFilter.equals("ALL") && !serviceTypeFilter.equals(serviceType)) {
            continue;
        }
        // Filter out services based on serviceSearchString
        if (serviceSearchString != null && serviceSearchString.trim().length() > 0
                && !isServiceSatisfySearchString(serviceSearchString, axisService.getName())) {
            continue;
        }
        axisServicesList.add(axisService);
        if (clonedTransitGhosts.containsKey(axisService.getName())) {
            clonedTransitGhosts.remove(axisService.getName());
        }
    }

    java.util.Collection<AxisService> transitGhosts = clonedTransitGhosts.values();
    for (AxisService transitGhost : transitGhosts) {
        axisServicesList.add(transitGhost);
    }

    if (axisServicesList.size() > 0) {
        Collections.sort(axisServicesList, new Comparator<AxisService>() {
            public int compare(AxisService arg0, AxisService arg1) {
                return arg0.getName().compareToIgnoreCase(arg1.getName());
            }
        });
    }

    //        String itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage");
    //        int itemsPerPageInt = 10; // the default number of item per page
    //        if (itemsPerPage != null) {
    //            itemsPerPageInt = Integer.parseInt(itemsPerPage);
    //        }
    //        int startIndex = pageNumber * itemsPerPageInt;
    //        int endIndex = (pageNumber + 1) * itemsPerPageInt;

    //Get only required services for page.
    List<AxisService> axisServicesRequiredForPage = new ArrayList<AxisService>();
    //        for (int i = startIndex; i < endIndex && i < axisServicesList.size(); i++) {
    //            axisServicesRequiredForPage.add(axisServicesList.get(i));
    //        }
    for (AxisService anAxisServicesList : axisServicesList) {
        axisServicesRequiredForPage.add(anAxisServicesList);
    }

    for (AxisService axisService : axisServicesRequiredForPage) {
        String serviceType = "axis2";
        Parameter serviceTypeParam;
        serviceTypeParam = axisService.getParameter(ServerConstants.SERVICE_TYPE);
        if (serviceTypeParam != null) {
            serviceType = (String) serviceTypeParam.getValue();
            serviceTypes.add(serviceType);
        }

        ServiceMetaData service = new ServiceMetaData();
        String serviceName = axisService.getName();
        service.setName(serviceName);

        // extract service type
        serviceTypeParam = axisService.getParameter(ServerConstants.SERVICE_TYPE);
        if (serviceTypeParam != null) {
            serviceType = (String) serviceTypeParam.getValue();
        }
        service.setServiceType(serviceType);
        AxisConfiguration axisConfiguration = getAxisConfig();
        service.setWsdlURLs(Utils.getWsdlInformation(serviceName, axisConfiguration));
        service.setTryitURL(Utils.getTryitURL(serviceName, getConfigContext()));
        service.setActive(axisService.isActive());
        Parameter parameter = axisService.getParameter(ServiceAdmin.DISABLE_TRY_IT_PARAM);
        if (parameter != null && Boolean.TRUE.toString().equalsIgnoreCase((String) parameter.getValue())) {
            service.setDisableTryit(true);
        }
        parameter = axisService.getParameter(ServiceAdmin.DISABLE_DELETION_PARAM);
        if (parameter != null && Boolean.TRUE.toString().equalsIgnoreCase((String) parameter.getValue())) {
            service.setDisableDeletion(true);
        }
        service.setServiceGroupName(axisService.getAxisServiceGroup().getServiceGroupName());

        // find the current security scenario id
        if (GhostDeployerUtils.isGhostService(axisService)) {
            Parameter secParam = axisService.getParameter(CarbonConstants.GHOST_ATTR_SECURITY_SCENARIO);
            if (secParam != null) {
                service.setSecurityScenarioId((String) secParam.getValue());
            }
        } else {
            SecurityScenarioData securityScenario = getSecurityScenario(serviceName);
            if (securityScenario != null) {
                service.setSecurityScenarioId(securityScenario.getScenarioId());
            }
        }
        if (!axisFaultServices.contains(axisService.getName())) {
            serviceList.add(service);
        }
    }

    ServiceMetaDataWrapper wrapper;
    wrapper = new ServiceMetaDataWrapper();
    wrapper.setNumberOfCorrectServiceGroups(getNumberOfServiceGroups());
    wrapper.setNumberOfFaultyServiceGroups(getNumberOfFaultyServices());
    wrapper.setServiceTypes(serviceTypes.toArray(new String[serviceTypes.size()]));
    wrapper.setNumberOfActiveServices(getNumberOfActiveServices());
    //  DataPaginator.doPaging(pageNumber, axisServicesList, serviceList, wrapper);
    DataPaginator.doPaging(pageNumber, serviceList, wrapper);
    return wrapper;
}