Example usage for java.util TreeMap TreeMap

List of usage examples for java.util TreeMap TreeMap

Introduction

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

Prototype

public TreeMap() 

Source Link

Document

Constructs a new, empty tree map, using the natural ordering of its keys.

Usage

From source file:io.fabric8.maven.core.extenvvar.ExternalEnvVarHandler.java

private static Map<String, String> getEnvironmentVarsFromJsonSchema(MavenProject project,
        Map<String, String> envVars) {
    Map<String, String> ret = new TreeMap<>();
    JsonSchema schema = getEnvironmentVariableJsonSchema(project, envVars);
    Map<String, JsonSchemaProperty> properties = schema.getProperties();
    Set<Map.Entry<String, JsonSchemaProperty>> entries = properties.entrySet();
    for (Map.Entry<String, JsonSchemaProperty> entry : entries) {
        String name = entry.getKey();
        String value = entry.getValue().getDefaultValue();
        ret.put(name, value != null ? value : "");
    }/*w ww.  j a  v  a 2 s.com*/
    return ret;
}

From source file:com.opengamma.financial.analytics.cashflow.FloatingPaymentMatrix.java

public FloatingPaymentMatrix() {
    _values = new TreeMap<LocalDate, List<Pair<CurrencyAmount, String>>>();
    _maxEntries = 0;
}

From source file:com.l2jfree.sql.L2DatabaseInstaller.java

public static void check() throws SAXException, IOException, ParserConfigurationException {
    final TreeMap<String, String> tables = new TreeMap<String, String>();
    final TreeMap<Double, String> updates = new TreeMap<Double, String>();

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false); // FIXME add validation
    factory.setIgnoringComments(true);/* w  ww  .j  a  v a  2  s .  c  o  m*/

    final List<Document> documents = new ArrayList<Document>();

    InputStream is = null;
    try {
        // load default database schema from resources
        is = L2DatabaseInstaller.class.getResourceAsStream("database_schema.xml");

        documents.add(factory.newDocumentBuilder().parse(is));
    } finally {
        IOUtils.closeQuietly(is);
    }

    final File f = new File("./config/database_schema.xml");

    // load optional project specific database tables/updates (fails on already existing)
    if (f.exists())
        documents.add(factory.newDocumentBuilder().parse(f));

    for (Document doc : documents) {
        for (Node n1 : L2XML.listNodesByNodeName(doc, "database")) {
            for (Node n2 : L2XML.listNodesByNodeName(n1, "table")) {
                final String name = L2XML.getAttribute(n2, "name");
                final String definition = L2XML.getAttribute(n2, "definition");

                final String oldDefinition = tables.put(name, definition);
                if (oldDefinition != null)
                    throw new RuntimeException("Found multiple tables with name " + name + "!");
            }

            for (Node n2 : L2XML.listNodesByNodeName(n1, "update")) {
                final Double revision = Double.valueOf(L2XML.getAttribute(n2, "revision"));
                final String query = L2XML.getAttribute(n2, "query");

                final String oldQuery = updates.put(revision, query);
                if (oldQuery != null)
                    throw new RuntimeException("Found multiple updates with revision " + revision + "!");
            }
        }
    }

    createRevisionTable();

    final double databaseRevision = getDatabaseRevision();

    if (databaseRevision == -1) // no table exists
    {
        for (Entry<String, String> table : tables.entrySet()) {
            final String tableName = table.getKey();
            final String tableDefinition = table.getValue();

            installTable(tableName, tableDefinition);
        }

        if (updates.isEmpty())
            insertRevision(0);
        else
            insertRevision(updates.lastKey());
    } else
    // check for possibly required updates
    {
        for (Entry<String, String> table : tables.entrySet()) {
            final String tableName = table.getKey();
            final String tableDefinition = table.getValue();

            if (L2Database.tableExists(tableName))
                continue;

            System.err.println("Table '" + tableName + "' is missing, so the server attempts to install it.");
            System.err.println("WARNING! It's highly recommended to check the results manually.");

            installTable(tableName, tableDefinition);
        }

        for (Entry<Double, String> update : updates.entrySet()) {
            final double updateRevision = update.getKey();
            final String updateQuery = update.getValue();

            if (updateRevision > databaseRevision) {
                executeUpdate(updateQuery);

                insertRevision(updateRevision);
            }
        }
    }
}

From source file:net.meltdowntech.steamstats.SteamGame.java

private SteamGame() {
    values = new TreeMap<>();
}

From source file:com.qpark.eip.core.spring.AbstractPlaceholderConfigurer.java

/**
 * @param properties// w  ww  .  j a  v  a 2s  . c  om
 *            The loaded properties
 * @return the {@link TreeMap} containing the translations.
 */
public static TreeMap<String, String> setupTranslationMap(final Map<String, String> properties) {
    TreeMap<String, String> translationMap = new TreeMap<String, String>();
    String number;
    String source;
    String translated;
    for (String s0 : properties.keySet()) {
        if (s0.trim().length() > 0 && !s0.trim().startsWith("#") && s0.indexOf('.') > 0) {
            number = s0.substring(0, s0.indexOf('.'));
            for (String s1 : properties.keySet()) {
                source = null;
                translated = null;
                if (s1.trim().length() > 0 && !s1.trim().startsWith("#") && s1.startsWith(number)
                        && !s1.equals(s0)) {
                    if (s0.contains("source")) {
                        source = s0;
                    } else if (s1.contains("source")) {
                        source = s1;
                    }
                    if (s0.contains("translated")) {
                        translated = s0;
                    } else if (s1.contains("translated")) {
                        translated = s1;
                    }
                    if (source != null && translated != null) {
                        translationMap.put(properties.get(source), properties.get(translated));
                    }
                }
            }
        }
    }
    return translationMap;
}

From source file:com.fatwire.dta.sscrawler.util.UriUtil.java

public static Map<String, String> extractParams(final String uri) {
    final String qs = URI.create(uri).getRawQuery();
    final Map<String, String> map = new TreeMap<String, String>();
    if (qs != null) {
        for (final String p : qs.split("&")) {
            final String[] nvp = p.split("=");
            try {
                final String key = URLDecoder.decode(nvp[0], UriUtil.UTF8);
                if (nvp.length > 0) {
                    map.put(key, URLDecoder.decode(nvp[1], UriUtil.UTF8));

                } else {
                    map.put(key, null);//from   w  w w . j a  v a 2  s . com
                }
            } catch (final UnsupportedEncodingException e) {
                UriUtil.log.error(e, e);
            }
        }

    }
    return map;
}

From source file:net.sourceforge.msscodefactory.cfgcash.v2_0.CFGCashRam.CFGCashRamServiceTable.java

public CFGCashCursor openServiceCursorByTypeIdx(CFGCashAuthorization Authorization, int ServiceTypeId) {
    CFGCashCursor cursor;/*  w w  w .j a va2 s  .co  m*/
    CFGCashServiceByTypeIdxKey key = schema.getFactoryService().newTypeIdxKey();
    key.setRequiredServiceTypeId(ServiceTypeId);

    if (dictByTypeIdx.containsKey(key)) {
        SortedMap<CFGCashServicePKey, CFGCashServiceBuff> subdictTypeIdx = dictByTypeIdx.get(key);
        cursor = new CFGCashRamServiceCursor(Authorization, schema, subdictTypeIdx.values());
    } else {
        cursor = new CFGCashRamServiceCursor(Authorization, schema, new ArrayList<CFGCashServiceBuff>());
    }
    return (cursor);
}

From source file:gov.va.chir.tagline.dao.DatasetUtil.java

public static Instances createDataset(final Collection<Document> documents) {

    // Key = feature name | Value = number representing NUMERIC, NOMINAL, etc.
    final Map<String, Integer> featureType = new TreeMap<String, Integer>();

    // Key = feature name | Values = distinct values for NOMINAL values
    final Map<String, Set<String>> nominalFeatureMap = new HashMap<String, Set<String>>();

    final Set<String> labels = new TreeSet<String>();
    final Set<String> docIds = new TreeSet<String>();

    // First scan -- determine attribute values
    for (Document document : documents) {
        processFeatures(document.getFeatures(), featureType, nominalFeatureMap);
        docIds.add(document.getName());/*from w ww .  ja v  a  2 s.  co m*/

        for (Line line : document.getLines()) {
            processFeatures(line.getFeatures(), featureType, nominalFeatureMap);

            labels.add(line.getLabel());
        }
    }

    final ArrayList<Attribute> attributes = new ArrayList<Attribute>();

    // Add Document and Line IDs as first two attributes
    //final Attribute docId = new Attribute(DOC_ID, (ArrayList<String>) null);
    final Attribute docId = new Attribute(DOC_ID, new ArrayList<String>(docIds));
    final Attribute lineId = new Attribute(LINE_ID);

    attributes.add(docId);
    attributes.add(lineId);

    // Build attributes
    for (String feature : featureType.keySet()) {
        final int type = featureType.get(feature);

        if (type == Attribute.NUMERIC) {
            attributes.add(new Attribute(feature));
        } else {
            if (nominalFeatureMap.containsKey(feature)) {
                attributes.add(new Attribute(feature, new ArrayList<String>(nominalFeatureMap.get(feature))));
            }
        }
    }

    // Add class attribute
    Attribute classAttr = new Attribute(LABEL, new ArrayList<String>(labels));
    attributes.add(classAttr);

    final Instances instances = new Instances("train", attributes, documents.size());

    // Second scan -- add data
    for (Document document : documents) {
        final Map<String, Object> docFeatures = document.getFeatures();

        for (Line line : document.getLines()) {
            final Instance instance = new DenseInstance(attributes.size());

            final Map<String, Object> lineFeatures = line.getFeatures();
            lineFeatures.putAll(docFeatures);

            instance.setValue(docId, document.getName());
            instance.setValue(lineId, line.getLineId());
            instance.setValue(classAttr, line.getLabel());

            for (Attribute attribute : attributes) {
                if (!attribute.equals(docId) && !attribute.equals(lineId) && !attribute.equals(classAttr)) {
                    final String name = attribute.name();
                    final Object obj = lineFeatures.get(name);

                    if (obj instanceof Double) {
                        instance.setValue(attribute, ((Double) obj).doubleValue());
                    } else if (obj instanceof Integer) {
                        instance.setValue(attribute, ((Integer) obj).doubleValue());
                    } else {
                        instance.setValue(attribute, obj.toString());
                    }
                }
            }

            instances.add(instance);
        }
    }

    // Set last attribute as class
    instances.setClassIndex(attributes.size() - 1);

    return instances;
}

From source file:com.mirth.connect.server.util.AttachmentUtil.java

public static byte[] reAttachMessage(String raw, ImmutableConnectorMessage connectorMessage,
        String charsetEncoding, boolean binary) {
    try {/* ww w  .  j  a  v a2 s .  co  m*/
        Map<Integer, Map<Integer, Object>> replacementObjects = new TreeMap<Integer, Map<Integer, Object>>();
        // Determine the buffersize during the first pass for better memory performance
        int bufferSize = raw.length();
        int index = 0;
        int endIndex;
        // Initialize the objects here so only one retrieval of the attachment content is ever needed.
        byte[] dicomObject = null;
        Map<String, Attachment> attachmentMap = null;

        // Handle the special case if only a dicom message is requested. 
        // In this case we can skip any byte appending and thus do not need to base64 encode the dicom object
        // if the type is binary.
        if (raw.trim().equals(PREFIX + DICOM_KEY + SUFFIX)) {
            dicomObject = DICOMUtil.getDICOMRawBytes(connectorMessage);

            if (!binary) {
                dicomObject = Base64Util.encodeBase64(dicomObject);
            }

            return dicomObject;
        }

        // Check the raw string in one pass for any attachments.
        // Stores the start and end indices to replace, along with the attachment content.
        while ((index = raw.indexOf(PREFIX, index)) != -1) {
            if (raw.startsWith(DICOM_KEY + SUFFIX, index + PREFIX.length())) {
                if (dicomObject == null) {
                    // Unfortunately, if the dicom data needs to appended to other base64 data, it must be done so in base64.
                    dicomObject = Base64Util.encodeBase64(DICOMUtil.getDICOMRawBytes(connectorMessage));
                }

                endIndex = index + PREFIX.length() + DICOM_KEY.length() + SUFFIX.length();

                Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                replacementMap.put(KEY_END_INDEX, endIndex);
                replacementMap.put(KEY_DATA, dicomObject);
                replacementObjects.put(index, replacementMap);

                bufferSize += dicomObject.length;
                index += endIndex - index;
            } else if (raw.startsWith(ATTACHMENT_KEY, index + PREFIX.length())) {
                if (attachmentMap == null) {
                    List<Attachment> list = getMessageAttachments(connectorMessage);

                    // Store the attachments in a map with the attachment's Id as the key
                    attachmentMap = new HashMap<String, Attachment>();
                    for (Attachment attachment : list) {
                        attachmentMap.put(attachment.getId(), attachment);
                    }
                }

                int attachmentIdStartIndex = index + PREFIX.length() + ATTACHMENT_KEY.length();
                int attachmentIdEndIndex = attachmentIdStartIndex + ATTACHMENT_ID_LENGTH;
                endIndex = attachmentIdEndIndex + SUFFIX.length();
                String attachmentId = raw.substring(attachmentIdStartIndex,
                        attachmentIdStartIndex + ATTACHMENT_ID_LENGTH);

                if (raw.substring(attachmentIdEndIndex, endIndex).equals(SUFFIX)) {
                    Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                    replacementMap.put(KEY_END_INDEX, endIndex);

                    if (attachmentMap.containsKey(attachmentId)) {
                        Attachment attachment = attachmentMap.get(attachmentId);
                        replacementMap.put(KEY_DATA, attachment.getContent());

                        bufferSize += attachment.getContent().length;
                    } else {
                        replacementMap.put(KEY_DATA, new byte[0]);
                    }

                    replacementObjects.put(index, replacementMap);
                }
            } else {
                endIndex = index + PREFIX.length();
            }

            index += endIndex - index;
        }
        // Release the object pointers of the attachment content so they aren't held in memory for the entire method
        dicomObject = null;
        attachmentMap = null;

        // Initialize the stream's buffer size. The buffer size will always be slightly large than needed,
        // because the template keys are never removed from the buffer size.
        // It is not worth doing any extra calculations for the amount of memory saved. 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize);

        int segmentStartIndex = 0;
        for (Map.Entry<Integer, Map<Integer, Object>> entry : replacementObjects.entrySet()) {
            int startReplacementIndex = entry.getKey();
            int endReplacementIndex = (Integer) entry.getValue().get(KEY_END_INDEX);
            byte[] data = (byte[]) entry.getValue().get(KEY_DATA);

            // Allows the memory used by the attachments to be released at the end of the loop
            entry.getValue().clear();

            byte[] templateSegment;
            // If the data is binary, the content should be in base64, so using US-ASCII as the charset encoding should be sufficient.
            if (binary) {
                templateSegment = StringUtils
                        .getBytesUsAscii(raw.substring(segmentStartIndex, startReplacementIndex));
            } else {
                templateSegment = StringUtil.getBytesUncheckedChunked(
                        raw.substring(segmentStartIndex, startReplacementIndex), Constants.ATTACHMENT_CHARSET);
            }

            baos.write(templateSegment);
            baos.write(data);

            segmentStartIndex = endReplacementIndex;
        }

        byte[] templateSegment;
        if (binary) {
            templateSegment = StringUtils.getBytesUsAscii(raw.substring(segmentStartIndex));
        } else {
            templateSegment = StringUtil.getBytesUncheckedChunked(raw.substring(segmentStartIndex),
                    Constants.ATTACHMENT_CHARSET);
        }

        byte[] combined;
        // If there are no attachments, don't bother writing to the output stream.
        if (segmentStartIndex == 0) {
            combined = templateSegment;
        } else {
            // Write the segment after the last replacement.
            baos.write(templateSegment);

            combined = baos.toByteArray();
            // Release the memory used by the byte array stream. ByteArrayOutputStreams do not need to be closed. 
            baos = null;
        }

        templateSegment = null;

        // If binary, the content should be in base64 so it is necessary to decode the data.
        if (binary) {
            combined = Base64Util.decodeBase64(combined);
        } else if (charsetEncoding != null
                && !charsetEncoding.toUpperCase().equals(Constants.ATTACHMENT_CHARSET.toUpperCase())) {
            // Convert the byte array to a string using the internal encoding.
            String combinedString = StringUtils.newString(combined, Constants.ATTACHMENT_CHARSET);
            // First release the reference to the old byte data so it can be reallocated if necessary.
            combined = null;
            // Convert the string to a byte array using the requested encoding
            combined = StringUtil.getBytesUncheckedChunked(combinedString, charsetEncoding);
        }

        return combined;
    } catch (Exception e) {
        logger.error("Error reattaching attachments", e);
        return null;
    }
}

From source file:com.mirth.connect.server.util.MessageAttachmentUtil.java

public static byte[] reAttachMessage(String raw, ImmutableConnectorMessage connectorMessage,
        String charsetEncoding, boolean binary) {
    try {// w  w w.  j  a  v  a2s  .co  m
        Map<Integer, Map<Integer, Object>> replacementObjects = new TreeMap<Integer, Map<Integer, Object>>();
        // Determine the buffersize during the first pass for better memory performance
        int bufferSize = raw.length();
        int index = 0;
        int endIndex;
        // Initialize the objects here so only one retrieval of the attachment content is ever needed.
        byte[] dicomObject = null;
        Map<String, Attachment> attachmentMap = null;

        // Handle the special case if only a dicom message is requested. 
        // In this case we can skip any byte appending and thus do not need to base64 encode the dicom object
        // if the type is binary.
        if (raw.trim().equals(PREFIX + DICOM_KEY + SUFFIX)) {
            dicomObject = DICOMMessageUtil.getDICOMRawBytes(connectorMessage);

            if (!binary) {
                dicomObject = Base64Util.encodeBase64(dicomObject);
            }

            return dicomObject;
        }

        // Check the raw string in one pass for any attachments.
        // Stores the start and end indices to replace, along with the attachment content.
        while ((index = raw.indexOf(PREFIX, index)) != -1) {
            if (raw.startsWith(DICOM_KEY + SUFFIX, index + PREFIX.length())) {
                if (dicomObject == null) {
                    // Unfortunately, if the dicom data needs to appended to other base64 data, it must be done so in base64.
                    dicomObject = Base64Util.encodeBase64(DICOMMessageUtil.getDICOMRawBytes(connectorMessage));
                }

                endIndex = index + PREFIX.length() + DICOM_KEY.length() + SUFFIX.length();

                Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                replacementMap.put(KEY_END_INDEX, endIndex);
                replacementMap.put(KEY_DATA, dicomObject);
                replacementObjects.put(index, replacementMap);

                bufferSize += dicomObject.length;
                index += endIndex - index;
            } else if (raw.startsWith(ATTACHMENT_KEY, index + PREFIX.length())) {
                if (attachmentMap == null) {
                    List<Attachment> list = getMessageAttachments(connectorMessage);

                    // Store the attachments in a map with the attachment's Id as the key
                    attachmentMap = new HashMap<String, Attachment>();
                    for (Attachment attachment : list) {
                        attachmentMap.put(attachment.getId(), attachment);
                    }
                }

                int attachmentIdStartIndex = index + PREFIX.length() + ATTACHMENT_KEY.length();
                int attachmentIdEndIndex = attachmentIdStartIndex + ATTACHMENT_ID_LENGTH;
                endIndex = attachmentIdEndIndex + SUFFIX.length();
                String attachmentId = raw.substring(attachmentIdStartIndex,
                        attachmentIdStartIndex + ATTACHMENT_ID_LENGTH);

                if (raw.substring(attachmentIdEndIndex, endIndex).equals(SUFFIX)) {
                    Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                    replacementMap.put(KEY_END_INDEX, endIndex);

                    if (attachmentMap.containsKey(attachmentId)) {
                        Attachment attachment = attachmentMap.get(attachmentId);
                        replacementMap.put(KEY_DATA, attachment.getContent());

                        bufferSize += attachment.getContent().length;
                    } else {
                        replacementMap.put(KEY_DATA, new byte[0]);
                    }

                    replacementObjects.put(index, replacementMap);
                }
            } else {
                endIndex = index + PREFIX.length();
            }

            index += endIndex - index;
        }
        // Release the object pointers of the attachment content so they aren't held in memory for the entire method
        dicomObject = null;
        attachmentMap = null;

        // Initialize the stream's buffer size. The buffer size will always be slightly large than needed,
        // because the template keys are never removed from the buffer size.
        // It is not worth doing any extra calculations for the amount of memory saved. 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize);

        int segmentStartIndex = 0;
        for (Map.Entry<Integer, Map<Integer, Object>> entry : replacementObjects.entrySet()) {
            int startReplacementIndex = entry.getKey();
            int endReplacementIndex = (Integer) entry.getValue().get(KEY_END_INDEX);
            byte[] data = (byte[]) entry.getValue().get(KEY_DATA);

            // Allows the memory used by the attachments to be released at the end of the loop
            entry.getValue().clear();

            byte[] templateSegment;
            // If the data is binary, the content should be in base64, so using US-ASCII as the charset encoding should be sufficient.
            if (binary) {
                templateSegment = StringUtils
                        .getBytesUsAscii(raw.substring(segmentStartIndex, startReplacementIndex));
            } else {
                templateSegment = StringUtil.getBytesUncheckedChunked(
                        raw.substring(segmentStartIndex, startReplacementIndex), Constants.ATTACHMENT_CHARSET);
            }

            baos.write(templateSegment);
            baos.write(data);

            segmentStartIndex = endReplacementIndex;
        }

        byte[] templateSegment;
        if (binary) {
            templateSegment = StringUtils.getBytesUsAscii(raw.substring(segmentStartIndex));
        } else {
            templateSegment = StringUtil.getBytesUncheckedChunked(raw.substring(segmentStartIndex),
                    Constants.ATTACHMENT_CHARSET);
        }

        byte[] combined;
        // If there are no attachments, don't bother writing to the output stream.
        if (segmentStartIndex == 0) {
            combined = templateSegment;
        } else {
            // Write the segment after the last replacement.
            baos.write(templateSegment);

            combined = baos.toByteArray();
            // Release the memory used by the byte array stream. ByteArrayOutputStreams do not need to be closed. 
            baos = null;
        }

        templateSegment = null;

        // If binary, the content should be in base64 so it is necessary to decode the data.
        if (binary) {
            combined = Base64Util.decodeBase64(combined);
        } else if (charsetEncoding != null
                && !charsetEncoding.toUpperCase().equals(Constants.ATTACHMENT_CHARSET.toUpperCase())) {
            // Convert the byte array to a string using the internal encoding.
            String combinedString = StringUtils.newString(combined, Constants.ATTACHMENT_CHARSET);
            // First release the reference to the old byte data so it can be reallocated if necessary.
            combined = null;
            // Convert the string to a byte array using the requested encoding
            combined = StringUtil.getBytesUncheckedChunked(combinedString, charsetEncoding);
        }

        return combined;
    } catch (Exception e) {
        logger.error("Error reattaching attachments", e);
        return null;
    }
}