Example usage for java.util SortedSet iterator

List of usage examples for java.util SortedSet iterator

Introduction

In this page you can find the example usage for java.util SortedSet iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:net.sf.jasperreports.engine.fill.JRFillChart.java

/**
 * The series colors set in the main plot of a multiple axis chart are used for
 * all the rendered charts in the plot.  This is a problem with multiple line
 * charts, using different scales and thus different axis.  All the lines will
 * be drawn using the first series color (since they are the first series for that
 * rendered) and it will be impossible to tell them apart.
 * <br>/* w w w.j ava 2 s  .c o m*/
 * For this reason we interpret series colors for charts included in a multiple
 * axis chart as specify absolute series colors for that renderer.
 *
 * @param renderer the renderer of the chart being created
 * @param jrPlot the Jasper view of that plot
 */
private void configureAxisSeriesColors(XYItemRenderer renderer, JRChartPlot jrPlot) {
    SortedSet<JRSeriesColor> seriesColors = jrPlot.getSeriesColors();

    if (seriesColors != null) {
        Iterator<JRSeriesColor> iter = seriesColors.iterator();
        while (iter.hasNext()) {
            JRSeriesColor seriesColor = iter.next();
            renderer.setSeriesPaint(seriesColor.getSeriesOrder(), seriesColor.getColor());
        }
    }
}

From source file:org.energy_home.jemma.ah.internal.configurator.Configuratore.java

public void exportConfiguration(OutputStream os) throws Exception {
    // Ottiene un riferimento al servizio Configuration Admin
    ServiceReference sr = bc.getServiceReference(ConfigurationAdmin.class.getName());
    ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) bc.getService(sr);

    // test();// w  ww.  j  ava 2  s. com

    // Ottiene un array contenente tutte le configurazioni salvate nel
    // Configuration Admin
    Configuration[] configs = configurationAdmin.listConfigurations(null);

    // Stampa nello stream di output il file XML
    PrintWriter pw = new PrintWriter(os);
    pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
    pw.println("<configurations>");

    // Export delle categories
    if (hacService != null) {
        ICategory[] categories = hacService.getCategories();
        if (categories != null) {
            pw.println("<categories>");
            for (int i = 0; i < categories.length; i++) {
                ICategory c = categories[i];
                pw.println("<category icon=\"" + c.getIconName() + "\" name = \"" + c.getName() + "\" pid = \""
                        + c.getPid() + "\"/>");
            }
            pw.println("</categories>");
        }
    }

    // Export delle rules
    if (connAdmin != null) {
        ArrayList rules = connAdmin.getBindRules();
        if (rules != null) {
            pw.println("<rules>");
            for (int i = 0; i < rules.size(); i++) {
                Filter f = (Filter) rules.get(i);
                pw.println("<rule filter =\"" + this.xmlContentEscape(f.toString()) + "\"/>");
            }
            pw.println("</rules>");
        }
    }

    // Export delle configurazioni
    if (configs != null && configs.length > 0) {
        Set factories = new HashSet();
        SortedMap sm = new TreeMap();
        for (int i = 0; i < configs.length; i++) {
            sm.put(configs[i].getPid(), configs[i]);
            String fpid = configs[i].getFactoryPid();
            if (null != fpid) {
                factories.add(fpid);
            }
        }

        for (Iterator mi = sm.values().iterator(); mi.hasNext();) {
            Configuration config = (Configuration) mi.next();
            pw.println("<configuration>");

            // Emette una ad una le proprieta' della configurazione
            Dictionary props = config.getProperties();
            if (props != null) {
                SortedSet keys = new TreeSet();
                for (Enumeration ke = props.keys(); ke.hasMoreElements();)
                    keys.add(ke.nextElement());
                for (Iterator ki = keys.iterator(); ki.hasNext();) {
                    String key = (String) ki.next();

                    pw.print("<property type=\"" + props.get(key).getClass().getSimpleName() + "\" name=\""
                            + key + "\">");

                    if (props.get(key).getClass().isArray() == true) {
                        pw.println();
                        Object value = props.get(key);
                        int len = Array.getLength(value);
                        for (int i = 0; i < len; i++) {
                            Object element = Array.get(value, i);
                            pw.print("<item>" + element.toString() + "</item>");
                        }
                    } else
                        pw.print(props.get(key));

                    pw.println("</property>");
                }
            }
            pw.println("</configuration>");
        }
    }
    pw.println("</configurations>");
    pw.flush();
}

From source file:org.apache.accumulo.server.gc.SimpleGarbageCollector.java

/**
 * This method attempts to do its best to remove files from the filesystem that have been confirmed for deletion.
 */// w  w w.j  a  v a2s .  c  om
private void deleteFiles(SortedSet<String> confirmedDeletes) {
    // create a batchwriter to remove the delete flags for successful
    // deletes
    BatchWriter writer = null;
    if (!offline) {
        Connector c;
        try {
            c = instance.getConnector(SecurityConstants.getSystemCredentials());
            writer = c.createBatchWriter(Constants.METADATA_TABLE_NAME, 10000000, 60000l, 3);
        } catch (Exception e) {
            log.error("Unable to create writer to remove file from the !METADATA table", e);
        }
    }

    // when deleting a dir and all files in that dir, only need to delete the dir
    // the dir will sort right before the files... so remove the files in this case
    // to minimize namenode ops
    Iterator<String> cdIter = confirmedDeletes.iterator();
    String lastDir = null;
    while (cdIter.hasNext()) {
        String delete = cdIter.next();
        if (isDir(delete)) {
            lastDir = delete;
        } else if (lastDir != null) {
            if (delete.startsWith(lastDir)) {
                log.debug("Ignoring " + delete + " because " + lastDir + " exist");
                Mutation m = new Mutation(new Text(Constants.METADATA_DELETE_FLAG_PREFIX + delete));
                m.putDelete(EMPTY_TEXT, EMPTY_TEXT);
                try {
                    writer.addMutation(m);
                } catch (MutationsRejectedException e) {
                    throw new RuntimeException(e);
                }
                cdIter.remove();
            } else {
                lastDir = null;
            }

        }
    }

    final BatchWriter finalWriter = writer;

    ExecutorService deleteThreadPool = Executors.newFixedThreadPool(numDeleteThreads);

    for (final String delete : confirmedDeletes) {

        Runnable deleteTask = new Runnable() {
            @Override
            public void run() {
                boolean removeFlag;

                log.debug("Deleting " + ServerConstants.getTablesDir() + delete);
                try {

                    Path p = new Path(ServerConstants.getTablesDir() + delete);

                    if (fs.delete(p, true)) {
                        // delete succeeded, still want to delete
                        removeFlag = true;
                        synchronized (SimpleGarbageCollector.this) {
                            ++status.current.deleted;
                        }
                    } else if (fs.exists(p)) {
                        // leave the entry in the METADATA table; we'll try again
                        // later
                        removeFlag = false;
                        synchronized (SimpleGarbageCollector.this) {
                            ++status.current.errors;
                        }
                        log.warn("File exists, but was not deleted for an unknown reason: " + p);
                    } else {
                        // this failure, we still want to remove the METADATA table
                        // entry
                        removeFlag = true;
                        synchronized (SimpleGarbageCollector.this) {
                            ++status.current.errors;
                        }
                        String parts[] = delete.split("/");
                        if (parts.length > 1) {
                            String tableId = parts[1];
                            TableManager.getInstance().updateTableStateCache(tableId);
                            TableState tableState = TableManager.getInstance().getTableState(tableId);
                            if (tableState != null && tableState != TableState.DELETING)
                                log.warn("File doesn't exist: " + p);
                        } else {
                            log.warn("Very strange path name: " + delete);
                        }
                    }

                    // proceed to clearing out the flags for successful deletes and
                    // non-existent files
                    if (removeFlag && finalWriter != null) {
                        Mutation m = new Mutation(new Text(Constants.METADATA_DELETE_FLAG_PREFIX + delete));
                        m.putDelete(EMPTY_TEXT, EMPTY_TEXT);
                        finalWriter.addMutation(m);
                    }
                } catch (Exception e) {
                    log.error(e, e);
                }

            }
        };

        deleteThreadPool.execute(deleteTask);
    }

    deleteThreadPool.shutdown();

    try {
        while (!deleteThreadPool.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
        }
    } catch (InterruptedException e1) {
        log.error(e1, e1);
    }

    if (writer != null) {
        try {
            writer.close();
        } catch (MutationsRejectedException e) {
            log.error("Problem removing entries from the metadata table: ", e);
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportJobsQuartzScheduler.java

protected String enumerateCronVals(SortedSet vals, int totalCount) {
    if (vals == null || vals.isEmpty()) {
        throw new JSException("jsexception.no.values.to.enumerate");
    }/*from  w w w .j a v a  2s.  co  m*/

    if (vals.size() == totalCount) {
        return "*";
    }

    StringBuffer enumStr = new StringBuffer();
    for (Iterator it = vals.iterator(); it.hasNext();) {
        Byte val = (Byte) it.next();
        enumStr.append(val.byteValue());
        enumStr.append(',');
    }
    return enumStr.substring(0, enumStr.length() - 1);
}

From source file:cerrla.LocalCrossEntropyDistribution.java

/**
 * Modifies the policy values before updating (cutting the values down to
 * size)./*  w ww . ja va 2 s .c om*/
 * 
 * @param elites
 *            The policy values to modify.
 * @param numElite
 *            The minimum number of elite samples.
 * @param staleValue
 *            The number of policies a sample hangs around for.
 * @param minValue
 *            The minimum observed value.
 * @return The policy values that were removed.
 */
private SortedSet<PolicyValue> preUpdateModification(SortedSet<PolicyValue> elites, int numElite,
        int staleValue, double minValue) {
    // Firstly, remove any policy values that have been around for more
    // than N steps

    // Make a backup - just in case the elites are empty afterwards
    SortedSet<PolicyValue> backup = new TreeSet<PolicyValue>(elites);

    // Only remove stuff if the elites are a representative solution
    if (!ProgramArgument.GLOBAL_ELITES.booleanValue()) {
        int iteration = policyGenerator_.getPoliciesEvaluated();
        for (Iterator<PolicyValue> iter = elites.iterator(); iter.hasNext();) {
            PolicyValue pv = iter.next();
            if (iteration - pv.getIteration() >= staleValue) {
                if (ProgramArgument.RETEST_STALE_POLICIES.booleanValue())
                    policyGenerator_.retestPolicy(pv.getPolicy());
                iter.remove();
            }
        }
    }
    if (elites.isEmpty())
        elites.addAll(backup);

    SortedSet<PolicyValue> tailSet = null;
    if (elites.size() > numElite) {
        // Find the N_E value
        Iterator<PolicyValue> pvIter = elites.iterator();
        PolicyValue currentPV = null;
        for (int i = 0; i < numElite; i++)
            currentPV = pvIter.next();

        // Iter at N_E value. Remove any values less than N_E's value
        tailSet = new TreeSet<PolicyValue>(elites.tailSet(new PolicyValue(null, currentPV.getValue(), -1)));
        elites.removeAll(tailSet);
    }

    return tailSet;
}

From source file:net.sourceforge.fenixedu.domain.Lesson.java

public SortedSet<YearMonthDay> getAllPossibleDatesToInsertSummary() {

    HourMinuteSecond now = new HourMinuteSecond();
    YearMonthDay currentDate = new YearMonthDay();
    SortedSet<YearMonthDay> datesToInsert = getAllLessonDatesUntil(currentDate);

    for (Summary summary : getAssociatedSummaries()) {
        YearMonthDay summaryDate = summary.getSummaryDateYearMonthDay();
        datesToInsert.remove(summaryDate);
    }/*from w  w w  .j  av a2 s .  c om*/

    for (Iterator<YearMonthDay> iter = datesToInsert.iterator(); iter.hasNext();) {
        YearMonthDay date = iter.next();
        if (!isTimeValidToInsertSummary(now, date)) {
            iter.remove();
        }
    }

    return datesToInsert;
}

From source file:carskit.data.processor.DataDAO.java

/**
 * @param rawId/*from w  ww. j  av  a2 s .c  om*/
 *            raw context id as String
 * @return inner context id as int
 */
public int getContextId(String rawId) {
    //System.out.println(rawId);
    int id;
    if (rawId.contains(":")) { // in shape of dim:c, dim:c
        String[] ccs = rawId.toLowerCase().split(",");
        SortedSet<Integer> set = new TreeSet<Integer>();
        for (int i = 0; i < ccs.length; ++i)
            set.add(this.getContextConditionId(ccs[i].trim()));
        StringBuilder sb = new StringBuilder();
        Iterator<Integer> itor = set.iterator();
        while (itor.hasNext()) {
            if (sb.length() > 0)
                sb.append(",");
            sb.append(itor.next());
        }
        return getContextId(sb.toString());
    } else // in shape of 1,2,3,
        id = ctxIds.get(rawId);
    return id;
}

From source file:org.apache.maven.report.projectinfo.dependencies.renderer.DependenciesRenderer.java

private void printGroupedLicenses() {
    for (Map.Entry<String, Object> entry : licenseMap.entrySet()) {
        String licenseName = entry.getKey();
        sink.paragraph();/*from  w  ww  .  j  av a 2  s.  c o m*/
        sink.bold();
        if (StringUtils.isEmpty(licenseName)) {
            sink.text(getI18nString("unamed"));
        } else {
            sink.text(licenseName);
        }
        sink.text(": ");
        sink.bold_();

        @SuppressWarnings("unchecked")
        SortedSet<String> projects = (SortedSet<String>) entry.getValue();

        for (Iterator<String> iterator = projects.iterator(); iterator.hasNext();) {
            String projectName = iterator.next();
            sink.text(projectName);
            if (iterator.hasNext()) {
                sink.text(", ");
            }
        }

        sink.paragraph_();
    }
}

From source file:visolate.Visolate.java

public void mouseClicked(double x, double y, int modifiers) {

    SortedSet<Net> clickedNets = new TreeSet<Net>();

    model.getNetsAtPoint(x, y, 1.0 / display.getDPI(), clickedNets);

    if (manualTopology.isSelected()) {
        clearSelection();/* w w w  .  j a v a2 s  . c  om*/
        TopologyProcessor.mergeNets(clickedNets);
        return;
    }

    if ((selectedNet != null) && clickedNets.contains(selectedNet)) {

        Iterator<Net> it = (clickedNets.tailSet(selectedNet)).iterator();

        it.next();

        if (it.hasNext()) {
            selectedNet = it.next();
        } else {
            selectedNet = clickedNets.iterator().next();
        }

    } else {

        selectedNet = null;

        if (!clickedNets.isEmpty()) {
            selectedNet = clickedNets.iterator().next();
        }
    }

    Net selectedNetSave = selectedNet;

    if (!((modifiers & MouseEvent.CTRL_DOWN_MASK) != 0))
        clearSelection();

    selectedNet = selectedNetSave;

    if (selectedNet != null) {
        selectedNets.add(selectedNet);
        selectedNet.setHighlighted(true);
    }
}

From source file:org.apache.hadoop.hbase.regionserver.Memcache.java

private void getRowKeyAtOrBefore(final ConcurrentSkipListSet<KeyValue> set, final KeyValue kv,
        final NavigableSet<KeyValue> candidates, final NavigableSet<KeyValue> deletes, final long now) {
    if (set.isEmpty()) {
        return;//from www .  j a v a2s .c  om
    }
    // We want the earliest possible to start searching from.  Start before
    // the candidate key in case it turns out a delete came in later.
    KeyValue search = candidates.isEmpty() ? kv : candidates.first();

    // Get all the entries that come equal or after our search key
    SortedSet<KeyValue> tailset = set.tailSet(search);

    // if there are items in the tail map, there's either a direct match to
    // the search key, or a range of values between the first candidate key
    // and the ultimate search key (or the end of the cache)
    if (!tailset.isEmpty() && this.comparator.compareRows(tailset.first(), search) <= 0) {
        // Keep looking at cells as long as they are no greater than the 
        // ultimate search key and there's still records left in the map.
        KeyValue deleted = null;
        KeyValue found = null;
        for (Iterator<KeyValue> iterator = tailset.iterator(); iterator.hasNext()
                && (found == null || this.comparator.compareRows(found, kv) <= 0);) {
            found = iterator.next();
            if (this.comparator.compareRows(found, kv) <= 0) {
                if (found.isDeleteType()) {
                    Store.handleDeletes(found, candidates, deletes);
                    if (deleted == null) {
                        deleted = found;
                    }
                } else {
                    if (Store.notExpiredAndNotInDeletes(this.ttl, found, now, deletes)) {
                        candidates.add(found);
                    } else {
                        if (deleted == null) {
                            deleted = found;
                        }
                        // TODO: Check this removes the right key.
                        // Its expired.  Remove it.
                        iterator.remove();
                    }
                }
            }
        }
        if (candidates.isEmpty() && deleted != null) {
            getRowKeyBefore(set, deleted, candidates, deletes, now);
        }
    } else {
        // The tail didn't contain any keys that matched our criteria, or was 
        // empty. Examine all the keys that proceed our splitting point.
        getRowKeyBefore(set, search, candidates, deletes, now);
    }
}