Example usage for java.util TreeMap put

List of usage examples for java.util TreeMap put

Introduction

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

Prototype

public V put(K key, V value) 

Source Link

Document

Associates the specified value with the specified key in this map.

Usage

From source file:net.pms.dlna.protocolinfo.MimeType.java

/**
 * Creates a new {@link MimeType} instance using the given values.
 *
 * @param type the first part of the mime-type.
 * @param subtype the second part of the mime-type.
 * @param parameters a {@link Map} of additional parameters for this
 *            mime-type.//from  w  w w.jav  a 2s  .c  om
 */
public MimeType(String type, String subtype, Map<String, String> parameters) {
    this.type = type == null ? ANY : type;
    this.subtype = subtype == null ? ANY : subtype;
    if (parameters == null) {
        this.parameters = Collections.EMPTY_MAP;
    } else {
        TreeMap<String, String> map = new TreeMap<String, String>(new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }

        });
        for (Entry<String, String> entry : parameters.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        this.parameters = Collections.unmodifiableSortedMap(map);
    }
    this.stringValue = generateStringValue();
}

From source file:emily.command.administrative.GuildStatsCommand.java

@Override
public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author,
        Message inputMessage) {//w  w  w .  java 2 s .  c o m
    if (!bot.getContainer().allShardsReady()) {
        return "Not fully loaded yet!";
    }
    if (args.length == 0) {
        return "Statistics! \n" + getTotalTable(bot, false) + "\nYou are on shard # " + bot.getShardId();
    }
    SimpleRank userrank = bot.security.getSimpleRank(author, channel);
    switch (args[0].toLowerCase()) {
    case "mini":
        return "Statistics! \n" + getTotalTable(bot, true);
    case "music":
        return DebugUtil
                .sendToHastebin(getPlayingOn(bot.getContainer(), userrank.isAtLeast(SimpleRank.BOT_ADMIN)
                        || (args.length >= 2 && args[1].equalsIgnoreCase("guilds"))));
    case "activity":
        return lastShardActivity(bot.getContainer());
    case "users":
        if (!(channel instanceof TextChannel)) {
            return Templates.invalid_use.formatGuild(channel);
        }
        TreeMap<Date, Integer> map = new TreeMap<>();
        Guild guild = ((TextChannel) channel).getGuild();
        List<Member> joins = new ArrayList<>(guild.getMembers());
        for (Member join : joins) {
            Date time = DateUtils.round(new Date(join.getJoinDate().toInstant().toEpochMilli()),
                    Calendar.DAY_OF_MONTH);
            if (!map.containsKey(time)) {
                map.put(time, 0);
            }
            map.put(time, map.get(time) + 1);
        }
        List<Date> xData = new ArrayList<>();
        List<Integer> yData = new ArrayList<>();
        int total = 0;
        for (Map.Entry<Date, Integer> entry : map.entrySet()) {
            total += entry.getValue();
            xData.add(entry.getKey());
            yData.add(total);
        }
        XYChart chart = new XYChart(1024, 600);
        chart.setTitle("Users over time for " + guild.getName());
        chart.setXAxisTitle("Date");
        chart.setYAxisTitle("Users");
        chart.getStyler().setTheme(new GGPlot2Theme());
        XYSeries series = chart.addSeries("Users", xData, yData);
        series.setMarker(SeriesMarkers.CIRCLE);
        try {
            File f = new File("./Sample_Chart.png");
            BitmapEncoder.saveBitmap(chart, f.getAbsolutePath(), BitmapEncoder.BitmapFormat.PNG);
            bot.queue.add(channel.sendFile(f), message -> f.delete());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    return "Statistics! \n" + getTotalTable(bot, false);
}

From source file:checkdb.CheckDb.java

/**
 * Build a map of all channels that are derived from each base name for a single IFO:Subsystem
 * @param ifoSubsys String of the form IFO:Subsystem[-_] 
 *//*from ww w. j  a  va 2  s  .c  o  m*/
private void buildChanStats(String ifoSubsys) {
    try {
        chanstats.clear();

        chnTbl.streamByName(ifoSubsys + "%");
        ChanInfo ci;
        count = 0;
        while ((ci = chnTbl.streamNext()) != null) {
            count++;
            if (verbose > 2 && count > 0 && count % 100000 == 0) {
                System.out.format("\033[2K %,8d\r", count);
                System.out.flush();
            }
            String name = ci.getChanName();
            String basename = ci.getBaseName();
            String serv = ci.getServer();
            serv = serv.replace(".caltech.edu", "");
            String key = basename;
            TreeMap<String, ChanStat> chanstatLst = chanstats.get(key);
            ChanStat chanstat;
            if (chanstatLst == null) {
                chanstatLst = new TreeMap<>();
                chanstat = new ChanStat();
                chanstatLst.put(serv, chanstat);
                chanstats.put(key, chanstatLst);
            } else {
                chanstat = chanstatLst.get(serv);
                if (chanstat == null) {
                    chanstat = new ChanStat();
                    chanstatLst.put(serv, chanstat);
                }
            }
            chanstat.add(ci);

            chanstats.put(key, chanstatLst);
        }

    } catch (SQLException ex) {
        Logger.getLogger(CheckDb.class.getName()).log(Level.SEVERE, null, ex);
        try {
            chnTbl.streamClose();
        } catch (SQLException ex1) {
            Logger.getLogger(CheckDb.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } finally {
        try {
            chnTbl.streamClose();
        } catch (SQLException ex) {
            Logger.getLogger(CheckDb.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:io.apiman.tools.i18n.TemplateScanner.java

/**
 * Scan the given html template using jsoup and find all strings that require translation.  This is
 * done by finding all elements with a "apiman-i18n-key" attribute.
 * @param file//from w  w  w  .  j  av a2 s.co  m
 * @param strings
 * @throws IOException
 */
private static void scanFile(File file, TreeMap<String, String> strings) throws IOException {
    Document doc = Jsoup.parse(file, "UTF-8");

    // First, scan for elements with the 'apiman-i18n-key' attribute.  These require translating.
    Elements elements = doc.select("*[apiman-i18n-key]");
    for (Element element : elements) {
        String i18nKey = element.attr("apiman-i18n-key");
        boolean isNecessary = false;

        // Process the element text (if the element has no children)
        if (strings.containsKey(i18nKey)) {
            if (hasNoChildren(element)) {
                isNecessary = true;
                String elementVal = element.text();
                if (elementVal.trim().length() > 0 && !elementVal.contains("{{")) {
                    String currentValue = strings.get(i18nKey);
                    if (!currentValue.equals(elementVal)) {
                        throw new IOException("Duplicate i18n key found with different default values.  Key="
                                + i18nKey + "  Value1=" + elementVal + "  Value2=" + currentValue);
                    }
                }
            }
        } else {
            if (hasNoChildren(element)) {
                String elementVal = element.text();
                if (elementVal.trim().length() > 0 && !elementVal.contains("{{")) {
                    isNecessary = true;
                    strings.put(i18nKey, elementVal);
                }
            }
        }

        // Process the translatable attributes
        for (String tattr : TRANSLATABLE_ATTRIBUTES) {
            if (element.hasAttr(tattr)) {
                String attrValue = element.attr(tattr);
                if (attrValue.contains("{{")) {
                    continue;
                }
                String attrI18nKey = i18nKey + '.' + tattr;
                String currentAttrValue = strings.get(attrI18nKey);
                if (currentAttrValue == null) {
                    isNecessary = true;
                    strings.put(attrI18nKey, attrValue);
                } else if (!currentAttrValue.equals(attrValue)) {
                    throw new IOException(
                            "Duplicate i18n key found with different default values (for attribute '" + tattr
                                    + "').  Key=" + attrI18nKey + "  Value1=" + attrValue + "  Value2="
                                    + currentAttrValue);
                } else {
                    isNecessary = true;
                }
            }
        }

        if (!isNecessary) {
            throw new IOException("Detected an unnecessary apiman-i18n-key attribute in file '" + file.getName()
                    + "' on element: " + element);
        }
    }

    // Next, scan all elements to see if the element *should* be marked for translation
    elements = doc.select("*");
    for (Element element : elements) {
        if (element.hasAttr("apiman-i18n-key") || element.hasAttr("apiman-i18n-skip")) {
            continue;
        }
        if (hasNoChildren(element)) {
            String value = element.text();
            if (value != null && value.trim().length() > 0) {
                if (!value.contains("{{")) {
                    throw new IOException("Found an element in '" + file.getName()
                            + "' that should be translated:  " + element);
                }
            }
        }
    }

    // Next scan elements with a translatable attribute and fail if any of those elements
    // are missing the apiman-i18n-key attribute.
    for (String tattr : TRANSLATABLE_ATTRIBUTES) {
        elements = doc.select("*[" + tattr + "]");
        for (Element element : elements) {
            if (element.hasAttr("apiman-i18n-key") || element.hasAttr("apiman-i18n-skip")
                    || element.attr(tattr).contains("{{")) {
                continue;
            } else {
                throw new IOException("In template '" + file.getName() + "', found an element with a '" + tattr
                        + "' attribute but missing 'apiman-i18n-key': " + element);
            }
        }
    }

}

From source file:net.sf.maltcms.chromaui.charts.overlay.Peak1DOverlay.java

/**
 *
 * @param ce//from   www . j a v a  2  s.  c o m
 */
@Override
public void selectionStateChanged(SelectionChangeEvent ce) {
    if (isVisible() && ce.getSource() != this && ce.getSelection() != null) {
        if (ce.getSelection().getType().equals(ISelection.Type.CLEAR)) {
            Logger.getLogger(getClass().getName()).fine("Received clear selection type");
            clear();
            return;
        }
        if (dataset != null) {
            IScan target = dataset.getTarget(ce.getSelection().getSeriesIndex(),
                    ce.getSelection().getItemIndex());
            TreeMap<Double, IPeakAnnotationDescriptor> distanceMap = new TreeMap<>();
            for (IPeakAnnotationDescriptor ipad : peakAnnotations.getMembers()) {
                double absDiff = Math.abs(ipad.getApexTime() - target.getScanAcquisitionTime());
                if (absDiff < 10.0d) {
                    distanceMap.put(absDiff, ipad);
                }
            }
            if (!distanceMap.isEmpty()) {
                IPeakAnnotationDescriptor ipad = distanceMap.firstEntry().getValue();
                if (!activeSelection.contains(ipad)) {
                    switch (ce.getSelection().getType()) {
                    case CLICK:
                        Logger.getLogger(getClass().getName()).fine("Click selection received");
                        renderer.generatePeakShape(peakAnnotations.getChromatogram(), ipad, dataset,
                                renderer.getSeriesIndex(dataset, peakAnnotations.getChromatogram()),
                                selectedPeaks);
                        activeSelection.add(ipad);
                        break;
                    case HOVER:
                        //                        System.out.println("Hover selection received");
                        //                        //                     content.add(ipad);
                        //                        activeSelection.add(ipad);
                    default:
                        break;
                    }
                    fireOverlayChanged();
                }
            }
        }
    }
}

From source file:org.apache.ambari.server.controller.metrics.timeline.cache.TimelineMetricCacheTest.java

@Test
public void testTimelineMetricCachePrecisionUpdates() throws Exception {

    Configuration configuration = createNiceMock(Configuration.class);
    expect(configuration.getMetricCacheTTLSeconds()).andReturn(3600);
    expect(configuration.getMetricCacheIdleSeconds()).andReturn(100);
    expect(configuration.getMetricsCacheManagerHeapPercent()).andReturn("10%").anyTimes();
    expect(configuration.getMetricRequestBufferTimeCatchupInterval()).andReturn(1000l).anyTimes();
    replay(configuration);/* w w w .  ja  va2 s. c  o  m*/

    final long now = System.currentTimeMillis();
    long second = 1000;
    long min = 60 * second;
    long hour = 60 * min;
    long day = 24 * hour;
    long year = 365 * day;

    //Original Values
    Map<String, TimelineMetric> valueMap = new HashMap<String, TimelineMetric>();
    TimelineMetric timelineMetric = new TimelineMetric();
    timelineMetric.setMetricName("cpu_user");
    timelineMetric.setAppId("app1");

    TreeMap<Long, Double> metricValues = new TreeMap<Long, Double>();
    for (long i = 1 * year - 1 * day; i >= 0; i -= 1 * day) {
        metricValues.put(now - i, 1.0);
    }

    timelineMetric.setMetricValues(metricValues);
    valueMap.put("cpu_user", timelineMetric);

    List<TimelineMetric> timelineMetricList = new ArrayList<>();
    timelineMetricList.add(timelineMetric);
    TimelineMetrics metrics = new TimelineMetrics();
    metrics.setMetrics(timelineMetricList);

    TimelineAppMetricCacheKey key = new TimelineAppMetricCacheKey(Collections.singleton("cpu_user"), "app1",
            new TemporalInfoImpl(now - 1 * year, now, 1));
    key.setSpec("");

    //Updated values
    Map<String, TimelineMetric> newValueMap = new HashMap<String, TimelineMetric>();
    TimelineMetric newTimelineMetric = new TimelineMetric();
    newTimelineMetric.setMetricName("cpu_user");
    newTimelineMetric.setAppId("app1");

    TreeMap<Long, Double> newMetricValues = new TreeMap<Long, Double>();
    for (long i = 1 * hour; i <= 2 * day; i += hour) {
        newMetricValues.put(now - 1 * day + i, 2.0);
    }

    newTimelineMetric.setMetricValues(newMetricValues);
    newValueMap.put("cpu_user", newTimelineMetric);

    List<TimelineMetric> newTimelineMetricList = new ArrayList<>();
    newTimelineMetricList.add(newTimelineMetric);
    TimelineMetrics newMetrics = new TimelineMetrics();
    newMetrics.setMetrics(newTimelineMetricList);

    TimelineAppMetricCacheKey newKey = new TimelineAppMetricCacheKey(Collections.singleton("cpu_user"), "app1",
            new TemporalInfoImpl(now - 1 * day, now + 2 * day, 1));
    newKey.setSpec("");

    MetricsRequestHelper metricsRequestHelperForGets = createMock(MetricsRequestHelper.class);
    expect(metricsRequestHelperForGets.fetchTimelineMetrics(EasyMock.isA(URIBuilder.class), anyLong(),
            anyLong())).andReturn(metrics).andReturn(newMetrics);
    replay(metricsRequestHelperForGets);

    TimelineMetricCacheEntryFactory cacheEntryFactory = createMockBuilder(TimelineMetricCacheEntryFactory.class)
            .withConstructor(Configuration.class).withArgs(configuration).createMock();

    Field requestHelperField = TimelineMetricCacheEntryFactory.class.getDeclaredField("requestHelperForGets");
    requestHelperField.setAccessible(true);
    requestHelperField.set(cacheEntryFactory, metricsRequestHelperForGets);

    requestHelperField = TimelineMetricCacheEntryFactory.class.getDeclaredField("requestHelperForUpdates");
    requestHelperField.setAccessible(true);
    requestHelperField.set(cacheEntryFactory, metricsRequestHelperForGets);

    replay(cacheEntryFactory);

    TimelineMetricCacheProvider cacheProvider = createMockBuilder(TimelineMetricCacheProvider.class)
            .addMockedMethod("createCacheConfiguration").withConstructor(configuration, cacheEntryFactory)
            .createNiceMock();

    expect(cacheProvider.createCacheConfiguration()).andReturn(createTestCacheConfiguration(configuration))
            .anyTimes();
    replay(cacheProvider);

    TimelineMetricCache cache = cacheProvider.getTimelineMetricsCache();

    // call to get
    metrics = cache.getAppTimelineMetricsFromCache(key);
    List<TimelineMetric> metricsList = metrics.getMetrics();
    Assert.assertEquals(1, metricsList.size());
    TimelineMetric metric = metricsList.iterator().next();
    Assert.assertEquals("cpu_user", metric.getMetricName());
    Assert.assertEquals("app1", metric.getAppId());
    Assert.assertEquals(metricValues, metric.getMetricValues());

    // call to update with new key
    metrics = cache.getAppTimelineMetricsFromCache(newKey);
    metricsList = metrics.getMetrics();
    Assert.assertEquals(1, metricsList.size());
    Assert.assertEquals("cpu_user", metric.getMetricName());
    Assert.assertEquals("app1", metric.getAppId());
    Assert.assertEquals(newMetricValues, metric.getMetricValues());

}

From source file:com.npower.wurfl.ListManager.java

/**
 * Return HashMap of HashMaps brand-&gt;modelname-&gt;WurflDevice
 * /*w  w  w.  j a va 2s.  c om*/
 */
public TreeMap<String, TreeMap<String, WurflDevice>> getDeviceGroupedByBrand() {

    if (actualDevicesByBrand.isEmpty()) {
        TreeMap<String, WurflDevice> act_devices = getActualDeviceElementsList();
        Iterator<String> keys = act_devices.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            WurflDevice wd = act_devices.get(key);
            String bn = wd.getBrandName();
            if (actualDevicesByBrand.get(bn) == null) {
                // new brand
                TreeMap<String, WurflDevice> hm = new TreeMap<String, WurflDevice>();
                hm.put(wd.getModelName(), wd);
                actualDevicesByBrand.put(bn, hm);
            } else {
                // add to existing brand
                TreeMap<String, WurflDevice> hm = actualDevicesByBrand.get(bn);
                hm.put(wd.getModelName(), wd);
            }
        }
    }
    return actualDevicesByBrand;
}

From source file:br.bireme.ngrams.NGrams.java

public static void export(NGIndex index, final NGSchema schema, final String outFile,
        final String outFileEncoding) throws IOException {
    if (index == null) {
        throw new NullPointerException("index");
    }//  w  ww  .  ja  v  a  2 s .  c o  m
    if (schema == null) {
        throw new NullPointerException("schema");
    }
    if (outFile == null) {
        throw new NullPointerException("outFile");
    }
    if (outFileEncoding == null) {
        throw new NullPointerException("outFileEncoding");
    }
    final Parameters parameters = schema.getParameters();
    final TreeMap<Integer, String> fields = new TreeMap<>();
    final IndexReader reader = index.getIndexSearcher().getIndexReader();
    final int maxdoc = reader.maxDoc();
    //final Bits liveDocs = MultiFields.getLiveDocs(reader);
    final Bits liveDocs = MultiBits.getLiveDocs(reader);
    final BufferedWriter writer = Files.newBufferedWriter(Paths.get(outFile), Charset.forName(outFileEncoding),
            StandardOpenOption.CREATE, StandardOpenOption.WRITE);

    boolean first = true;

    for (Map.Entry<Integer, br.bireme.ngrams.Field> entry : parameters.sfields.entrySet()) {
        fields.put(entry.getKey(), entry.getValue().name + NOT_NORMALIZED_FLD);
    }

    for (int docID = 0; docID < maxdoc; docID++) {
        if ((liveDocs != null) && (!liveDocs.get(docID)))
            continue;
        final Document doc = reader.document(docID);

        if (first) {
            first = false;
        } else {
            writer.newLine();
        }
        writer.append(doc2pipe(doc, fields));
    }
    writer.close();
    reader.close();
}

From source file:org.openmrs.module.rwandaprimarycare.ExtendPatientNameSearchController.java

@RequestMapping("/module/rwandaprimarycare/extendNameSearch")
public String setupForm(@RequestParam("givenName") String givenName,
        @RequestParam("familyName") String familyName, @RequestParam("gender") String gender,
        @RequestParam("age") Integer age,
        @RequestParam(required = false, value = "birthdateDay") Integer birthdateDay,
        @RequestParam(required = false, value = "birthdateMonth") Integer birthdateMonth,
        @RequestParam(required = false, value = "birthdateYear") Integer birthdateYear,
        @RequestParam("country") String country, @RequestParam("province") String province,
        @RequestParam("district") String district, @RequestParam("sector") String sector,
        @RequestParam("cell") String cell, @RequestParam("address1") String address1, HttpSession session,
        ModelMap model) throws PrimaryCareException {
    // LK: Need to ensure that all primary care methods only throw a
    // PrimaryCareException
    // So that errors will be directed to a touch screen error page
    GetPatientUtil getPatientUtil = new GetPatientUtil();
    try {//from  w w w .j  a  v a2 s .c  o m
        if (givenName != null) {
            log.info("FANAME >> " + givenName);
            log.info("RWNAME >> " + familyName);
            model.addAttribute("givenName", givenName);
            TreeMap<String, String> params = new TreeMap<String, String>();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR, -age);
            c.add(Calendar.DATE, -183);

            Date d = c.getTime();
            int year = d.getYear();
            String df = sdf.format(d);
            log.info(df + "<<  >>" + year);

            params.put("dob", df);

            if (givenName != null && givenName != "") {
                params.put("given_name", givenName);
            }
            if (familyName != null && familyName != "") {
                params.put("family_name", familyName);
            }
            if (gender != null && gender != "") {
                params.put("gender", gender);
            }
            if (province != null && province != "") {
                params.put("addr_province", province);
            }
            if (district != null && district != "") {
                params.put("addr_district", district);
            }
            if (sector != null && sector != "") {
                params.put("addr_sector", sector);
            }
            if (cell != null && cell != "") {
                params.put("addr_cell", cell);
            }
            if (address1 != null && address1 != "") {
                params.put("addr_village", address1);
            }

            model.addAttribute("givenName", givenName);
            model.addAttribute("familyName", familyName);
            model.addAttribute("gender", gender);
            model.addAttribute("age", age);
            model.addAttribute("searchUMUDUGUDU", address1);
            model.addAttribute("searchCELL", cell);
            model.addAttribute("searchDISTRICT", district);
            model.addAttribute("searchCOUNTRY", country);
            model.addAttribute("searchPROVINCE", province);
            model.addAttribute("searchSECTOR", sector);
            //model.addAttribute("CR", "Client Reg");

            //List<AttributeList> result = new ArrayList<AttributeList>();
            //            List<Patient> extendedResults = getPatientUtil
            //                  .getPatientFromClientReg(params);

            List<AttributeList> results = getPatientUtil.getPatientWithAttributeListFromClientReg(params);

            if (results.size() > 0) {
                for (AttributeList al : results) {
                    String nid = "";
                    if (al.getPatient().getPatientIdentifier("NID") != null) {
                        nid = al.getPatient().getPatientIdentifier("NID").getIdentifier();
                        al.setNid(nid);
                        log.info("Moms name == " + al.getMothersName());
                    } else {
                        nid = "Unavailable";
                        al.setNid(nid);
                    }
                }
            }
            //            if(extendedResults.size()>0){
            //                  for(Patient p:extendedResults){
            //                     String mothersName="";
            //                     String fathersName="";
            //                     String nid = "";
            //                     if(p.getPatientIdentifier("NID")!=null){
            //                        nid = p.getPatientIdentifier("NID").getIdentifier();
            //                     }
            //                     else{
            //                        nid = "Unavailable";
            //                     }
            //                     PersonAttributeType mName = Context.getPersonService().getPersonAttributeTypeByName(
            //                          PrimaryCareConstants.MOTHER_NAME_ATTRIBUTE_TYPE) ;
            //                     PersonAttributeType fName = Context.getPersonService().getPersonAttributeTypeByName(
            //                          PrimaryCareConstants.FATHER_NAME_ATTRIBUTE_TYPE) ;
            //                     
            //                     if (p.getAttribute(mName) != null) {
            //                         mothersName = p.getAttribute(mName).getValue();
            //                         
            //                      }
            //                      
            //                     if (p.getAttribute(fName) != null) {
            //                      fathersName = p.getAttribute(fName).getValue();
            //                      
            //                   }
            //                     
            //                     AttributeList al = new AttributeList(p, mothersName, fathersName, nid);
            //                     results.add(al);
            //                     
            //                  }
            //               }
            //            

            model.addAttribute("results", results);

            model.addAttribute("identifierTypes", PrimaryCareBusinessLogic.getPatientIdentifierTypesToUse());

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new PrimaryCareException(e);
    }
    return "/module/rwandaprimarycare/extendedResults";
}

From source file:com.sfs.DataFilter.java

/**
 * Parses the text data.//from  w  w  w  .  j  av  a 2s  .  c  om
 *
 * @param text the text
 *
 * @return the tree map< integer, tree map< integer, string>>
 */
public static TreeMap<Integer, TreeMap<Integer, String>> parseTextData(final String text) {

    TreeMap<Integer, TreeMap<Integer, String>> parsedData = new TreeMap<Integer, TreeMap<Integer, String>>();

    // This counter holds the maximum number of columns provided
    int maxNumberOfTokens = 0;

    if (text != null) {
        StringTokenizer tokenizer = new StringTokenizer(text, "\n");

        int lineCounter = 1;

        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken();
            TreeMap<Integer, String> parsedLine = new TreeMap<Integer, String>();

            final StringTokenizer tabTokenizer = new StringTokenizer(line, "\t");
            if (tabTokenizer.countTokens() > 1) {
                parsedLine = tokenizerToMap(tabTokenizer);
            } else {
                final StringTokenizer commaTokenizer = new StringTokenizer(line, ",");
                parsedLine = tokenizerToMap(commaTokenizer);
            }
            if (parsedLine.size() > maxNumberOfTokens) {
                maxNumberOfTokens = parsedLine.size();
            }

            parsedData.put(lineCounter, parsedLine);
            lineCounter++;
        }
    }

    // Now cycle through all the parsed data
    // Ensure that each row has the same (max) number of tokens
    for (int rowIndex : parsedData.keySet()) {
        TreeMap<Integer, String> parsedLine = parsedData.get(rowIndex);

        // This map holds the final values
        TreeMap<Integer, String> columnTokens = new TreeMap<Integer, String>();

        for (int i = 0; i < maxNumberOfTokens; i++) {
            int columnIndex = i + 1;
            if (parsedLine.containsKey(columnIndex)) {
                String value = parsedLine.get(columnIndex);
                columnTokens.put(columnIndex, value);
            } else {
                columnTokens.put(columnIndex, "");
            }
        }
        parsedData.put(rowIndex, columnTokens);
    }

    return parsedData;
}