Example usage for java.util SortedMap entrySet

List of usage examples for java.util SortedMap entrySet

Introduction

In this page you can find the example usage for java.util SortedMap entrySet.

Prototype

Set<Map.Entry<K, V>> entrySet();

Source Link

Document

Returns a Set view of the mappings contained in this map.

Usage

From source file:ch.algotrader.service.algo.VWAPOrderService.java

VWAPOrderStateVO createAlgoOrderState(final VWAPOrder algoOrder, final Date dateTime)
        throws OrderValidationException {

    Validate.notNull(algoOrder, "vwapOrder missing");

    Security security = algoOrder.getSecurity();
    SecurityFamily family = security.getSecurityFamily();
    Exchange exchange = family.getExchange();

    HistoricalDataService historicalDataService = this.applicationContext.getBean(HistoricalDataService.class);

    List<Bar> bars = historicalDataService.getHistoricalBars(security.getId(), //
            DateUtils.truncate(new Date(), Calendar.DATE), //
            algoOrder.getLookbackPeriod(), //
            TimePeriod.DAY, //
            algoOrder.getBucketSize(), //
            MarketDataEventType.TRADES, //
            Collections.emptyMap());

    TreeMap<LocalTime, Long> buckets = new TreeMap<>();
    Set<LocalDate> tradingDays = new HashSet<>();
    for (Bar bar : bars) {
        int vol = bar.getVol();
        LocalTime time = DateTimeLegacy.toLocalTime(bar.getDateTime());
        tradingDays.add(DateTimeLegacy.toLocalDate(bar.getDateTime()));
        if (buckets.containsKey(time)) {
            buckets.put(time, buckets.get(time) + vol);
        } else {/*w w w  . jav a 2s  .co m*/
            buckets.put(time, (long) vol);
        }
    }

    // verify start and end time
    if (algoOrder.getStartTime() == null) {
        if (this.calendarService.isOpen(exchange.getId())) {
            algoOrder.setStartTime(dateTime);
        } else {
            Date nextOpenTime = this.calendarService.getNextOpenTime(exchange.getId());
            algoOrder.setStartTime(nextOpenTime);
        }
    }

    Date closeTime = this.calendarService.getNextCloseTime(exchange.getId());
    if (algoOrder.getEndTime() == null) {
        algoOrder.setEndTime(closeTime);
    }

    if (algoOrder.getStartTime().compareTo(dateTime) < 0) {
        throw new OrderValidationException("startTime needs to be in the future " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(dateTime) <= 0) {
        throw new OrderValidationException("endTime needs to be in the future " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(closeTime) > 0) {
        throw new OrderValidationException("endTime needs to be before next market closeTime for " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(algoOrder.getStartTime()) <= 0) {
        throw new OrderValidationException("endTime needs to be after startTime for " + algoOrder);
    }

    int historicalVolume = 0;
    LocalTime startTime = DateTimeLegacy.toLocalTime(algoOrder.getStartTime());
    LocalTime endTime = DateTimeLegacy.toLocalTime(algoOrder.getEndTime());
    LocalTime firstBucketStart = buckets.floorKey(startTime);
    LocalTime lastBucketStart = buckets.floorKey(endTime);

    SortedMap<LocalTime, Long> subBuckets = buckets.subMap(firstBucketStart, true, lastBucketStart, true);
    for (Map.Entry<LocalTime, Long> bucket : subBuckets.entrySet()) {

        long vol = bucket.getValue() / tradingDays.size();
        bucket.setValue(vol);

        if (bucket.getKey().equals(firstBucketStart)) {
            LocalTime firstBucketEnd = firstBucketStart.plus(algoOrder.getBucketSize().getValue(),
                    ChronoUnit.MILLIS);
            double fraction = (double) ChronoUnit.MILLIS.between(startTime, firstBucketEnd)
                    / algoOrder.getBucketSize().getValue();
            historicalVolume += vol * fraction;
        } else if (bucket.getKey().equals(lastBucketStart)) {
            double fraction = (double) ChronoUnit.MILLIS.between(lastBucketStart, endTime)
                    / algoOrder.getBucketSize().getValue();
            historicalVolume += vol * fraction;
        } else {
            historicalVolume += vol;
        }
    }

    double participation = algoOrder.getQuantity() / (double) historicalVolume;

    if (participation > MAX_PARTICIPATION) {
        throw new OrderValidationException("participation rate " + twoDigitFormat.format(participation * 100.0)
                + "% is above 50% of historical market volume for " + algoOrder);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.debug("participation of {} is {}%", algoOrder.getDescription(),
                twoDigitFormat.format(participation * 100.0));
    }

    return new VWAPOrderStateVO(participation, buckets);
}

From source file:org.photovault.replication.ValueChange.java

@Override
public void addChange(FieldChange ch) {
    if (ch instanceof ValueChange) {
        ValueChange vc = (ValueChange) ch;
        for (Map.Entry<String, Object> e : vc.propChanges.entrySet()) {
            /*//from w  w  w. j a  v a  2 s  .  c o m
             * Remove all changes to a subproperty changed by vc, as it
             * will be overwritten by vc
             */
            SortedMap<String, Object> subprops = propChanges.subMap(e.getKey(), e.getKey() + "a");
            Iterator<Map.Entry<String, Object>> iter = subprops.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, Object> sub = iter.next();
                if (isSubProperty(e.getKey(), sub.getKey())) {
                    iter.remove();
                }
            }
        }
        propChanges.putAll(vc.propChanges);
    }
}

From source file:org.opendatakit.briefcase.ui.CharsetConverterDialog.java

protected void initialize() {
    DefaultListModel<CharsetEntry> defaultListModel = new DefaultListModel<CharsetEntry>();

    for (CharsetEntry commonCharsetEntry : commonCharsetEntries) {
        try {/*from   w ww . ja  va2 s .  c  om*/
            if (Charset.isSupported(commonCharsetEntry.getCharsetName())) {
                defaultListModel.addElement(commonCharsetEntry);
            }
        } catch (IllegalCharsetNameException e) {
            // just ignore it. It will happen for "Mac OS Roman" under Windows
        }
    }

    SortedMap<String, Charset> charsetSortedMap = Charset.availableCharsets();
    for (Map.Entry<String, Charset> charsetMapEntry : charsetSortedMap.entrySet()) {
        CharsetEntry charsetEntry = new CharsetEntry(charsetMapEntry.getValue().displayName(),
                charsetMapEntry.getKey());
        if (!defaultListModel.contains(charsetEntry)) {
            defaultListModel.addElement(charsetEntry);
        }
    }

    listCharset.setModel(defaultListModel);

    if (defaultListModel.size() > 0) {
        listCharset.setSelectedIndex(0);

        listCharset.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                updatePreview();
            }
        });
    } else {
        JOptionPane.showMessageDialog(this,
                "It appears that your installed Java Runtime Environment does not support any charset encodings!",
                "Error!", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.trnltk.apps.experiments.AmbiguityMatrixApp.java

private void printFirstNTopAmbiguousEntries(BufferedWriter writer, ImmutableMultiset<String> wordCountSet,
        Map<String, List<String>> resultMap, SortedMap<String, Integer> sortedTotalAmbiguityMap, int N) {
    final Formatter formatter = new Formatter(writer);
    int i = 0;//from   w  ww .  ja v  a  2 s  .c  o  m
    for (Map.Entry<String, Integer> entry : sortedTotalAmbiguityMap.entrySet()) {
        String surface = entry.getKey();
        Integer totalAmbiguity = entry.getValue();
        int occurrenceCount = wordCountSet.count(surface);
        List<String> parseResults = resultMap.get(surface);
        formatter.format(Locale.getDefault(), "%20s : %10d \t O:%10d \t A:%3d \t %s \n", surface,
                totalAmbiguity, occurrenceCount, parseResults.size(), Joiner.on("  ").join(parseResults));
        if (i++ == N)
            break;
    }
}

From source file:org.apache.ctakes.ytex.kernel.FoldGeneratorImpl.java

/**
 * inver the map of instance id to class, call createFolds
 * //  www .  ja v  a 2  s  .c  o m
 * @param nFolds
 * @param nMinPerClass
 * @param r
 * @param mapInstanceIdToClass
 * @return
 */
private List<Set<Long>> createFolds(int nFolds, int nMinPerClass, Random r,
        SortedMap<Long, String> mapInstanceIdToClass) {
    // invert the mapInstanceIdToClass
    Map<String, List<Long>> mapClassToInstanceId = new TreeMap<String, List<Long>>();
    for (Map.Entry<Long, String> instance : mapInstanceIdToClass.entrySet()) {
        String className = instance.getValue();
        long instanceId = instance.getKey();
        List<Long> classInstanceIds = mapClassToInstanceId.get(className);
        if (classInstanceIds == null) {
            classInstanceIds = new ArrayList<Long>();
            mapClassToInstanceId.put(className, classInstanceIds);
        }
        classInstanceIds.add(instanceId);
    }
    // stratified split into folds
    List<Set<Long>> folds = createFolds(mapClassToInstanceId, nFolds, nMinPerClass, r);
    return folds;
}

From source file:com.espertech.esper.schedule.SchedulingServiceImpl.java

public synchronized final void evaluate(Collection<ScheduleHandle> handles) {
    // Get the values on or before the current time - to get those that are exactly on the
    // current time we just add one to the current time for getting the head map
    SortedMap<Long, SortedMap<ScheduleSlot, ScheduleHandle>> headMap = timeHandleMap.headMap(currentTime + 1);

    if (headMap.isEmpty()) {
        return;//from  w w  w . j a v a2s . c o  m
    }

    // First determine all triggers to shoot
    List<Long> removeKeys = new ArrayList<Long>();
    for (Map.Entry<Long, SortedMap<ScheduleSlot, ScheduleHandle>> entry : headMap.entrySet()) {
        Long key = entry.getKey();
        SortedMap<ScheduleSlot, ScheduleHandle> value = entry.getValue();
        removeKeys.add(key);
        for (ScheduleHandle handle : value.values()) {
            handles.add(handle);
        }
    }

    // Next remove all handles
    for (Map.Entry<Long, SortedMap<ScheduleSlot, ScheduleHandle>> entry : headMap.entrySet()) {
        for (ScheduleHandle handle : entry.getValue().values()) {
            handleSetMap.remove(handle);
        }
    }

    // Remove all triggered msec values
    for (Long key : removeKeys) {
        timeHandleMap.remove(key);
    }
}

From source file:org.apache.falcon.unit.LocalExtensionManager.java

APIResult updateExtensionJob(String extensionName, String jobName, InputStream configStream,
        SortedMap<EntityType, List<Entity>> entityMap) throws FalconException, IOException {
    List<String> feedNames = new ArrayList<>();
    List<String> processNames = new ArrayList<>();
    checkIfExtensionIsEnabled(extensionName);
    checkIfExtensionJobNameExists(jobName, extensionName);
    for (Map.Entry<EntityType, List<Entity>> entry : entityMap.entrySet()) {
        for (Entity entity : entry.getValue()) {
            update(entity, entity.getEntityType().toString(), entity.getName(), true);
        }/*from w  ww.ja v  a 2s.  c  o  m*/
    }
    byte[] configBytes = null;
    if (configStream != null) {
        configBytes = IOUtils.toByteArray(configStream);
    }
    for (Map.Entry<EntityType, List<Entity>> entry : entityMap.entrySet()) {
        for (final Entity entity : entry.getValue()) {
            if (entity.getEntityType().equals(EntityType.FEED)) {
                feedNames.add(entity.getName());
            } else {
                processNames.add(entity.getName());
            }
        }
    }
    ExtensionStore.getMetaStore().updateExtensionJob(jobName, extensionName, feedNames, processNames,
            configBytes);
    return new APIResult(APIResult.Status.SUCCEEDED, "Updated successfully");
}

From source file:openlr.mapviewer.coding.ui.AbstractCodingOptionsDialog.java

/**
 * Sets up the form and sets the values from the given configuration.
 * //from  ww  w.ja  v  a  2s.c o  m
 * @param config
 *            The configuration to initialize the form with
 * @return The panel containing the form
 */
private JComponent buildForm(final FileConfiguration config) {

    JPanel formPanel = new JPanel();

    JScrollPane scrollPane = new JScrollPane(formPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    formPanel.setLayout(new MigLayout("insets 0", "[grow][]", ""));

    SortedMap<String, List<ConfigEntry>> topicsToKeyValuesMap = buildConfigurationMap(config);

    for (Map.Entry<String, List<ConfigEntry>> entry : topicsToKeyValuesMap.entrySet()) {

        String topic = entry.getKey();
        List<ConfigEntry> configEntries = entry.getValue();

        if (configEntries.size() == 1) {
            // it is a single property, just put a single line of label and
            // value directly on the formPanel
            addLabelledFields(configEntries, formPanel);

        } else {
            // multiple sub properties, create a separate panel collecting
            // all elements
            JPanel topicPanel = new JPanel();
            topicPanel.setLayout(new MigLayout("insets 0", "[grow][]", ""));
            topicPanel.setBorder(BorderFactory.createTitledBorder(topic));

            addLabelledFields(configEntries, topicPanel);

            formPanel.add(topicPanel, "span, grow, wrap");
        }
    }

    formPanel.invalidate();
    return scrollPane;
}

From source file:org.apache.falcon.unit.LocalExtensionManager.java

private void storeExtension(String extensionName, String jobName, InputStream configStream,
        SortedMap<EntityType, List<Entity>> entityMap) throws IOException {
    byte[] configBytes = null;
    if (configStream != null) {
        configBytes = IOUtils.toByteArray(configStream);
    }// www  .  j ava2  s  .  co m
    List<String> feedNames = new ArrayList<>();
    List<String> processNames = new ArrayList<>();
    for (Map.Entry<EntityType, List<Entity>> entry : entityMap.entrySet()) {
        for (final Entity entity : entry.getValue()) {
            if (entity.getEntityType().equals(EntityType.FEED)) {
                feedNames.add(entity.getName());
            } else {
                processNames.add(entity.getName());
            }
        }
    }
    ExtensionStore.getMetaStore().storeExtensionJob(jobName, extensionName, feedNames, processNames,
            configBytes);
}