Example usage for java.util TreeMap get

List of usage examples for java.util TreeMap get

Introduction

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

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:br.ufrgs.inf.dsmoura.repository.model.loadData.LoadLists.java

@SuppressWarnings("unused")
private static void loadOrganizationsAndProjects() {
    TreeMap<String, ArrayList<String>> organizations = new TreeMap<String, ArrayList<String>>();

    ArrayList<String> projects = new ArrayList<String>();
    projects.add("Project 1");
    projects.add("Project 2");
    projects.add("Project 3");
    organizations.put("Organization 1", projects);

    projects = new ArrayList<String>();
    projects.add("Project A");
    projects.add("Project B");
    projects.add("Project C");
    organizations.put("Organization A", projects);

    projects = new ArrayList<String>();
    projects.add("Project X");
    projects.add("Project Y");
    projects.add("Project Z");
    organizations.put("Organization K", projects);

    for (String key : organizations.keySet()) {
        OrganizationDTO org = new OrganizationDTO();
        org.setName(key);/*from ww  w  .j av a 2  s.co  m*/
        org = (OrganizationDTO) GenericDAO.getInstance().insert(org);
        logger.info("OrganizationDTO inserted: " + key);

        ArrayList<String> subdomains = organizations.get(key);
        for (String s : subdomains) {
            ProjectDTO proj = new ProjectDTO();
            proj.setName(s);
            proj.setOrganizationDTO(org);
            GenericDAO.getInstance().insert(proj);
            logger.info("ProjectDTO inserted: " + s);
        }
    }
}

From source file:com.google.gwt.benchmarks.viewer.server.ReportImageServer.java

private JFreeChart createChart(String testName, Result result, String title, List<Result> comparativeResults) {

    // Find the maximum values across both axes for all of the results
    // (this chart's own results, plus all comparative results).
    ////from   w w  w. ja v a  2s. c om
    // This is a stop-gap solution that helps us compare different charts for
    // the same benchmark method (usually with different user agents) until we
    // get real comparative functionality in version two.

    double maxTime = 0;

    for (Result r : comparativeResults) {
        for (Trial t : r.getTrials()) {
            maxTime = Math.max(maxTime, t.getRunTimeMillis());
        }
    }

    // Determine the number of variables in this benchmark method
    List<Trial> trials = result.getTrials();
    Trial firstTrial = new Trial();
    int numVariables = 0;
    if (trials.size() > 0) {
        firstTrial = trials.get(0);
        numVariables = firstTrial.getVariables().size();
    }

    // Display the trial data.
    //
    // First, pick the domain and series variables for our graph.
    // Right now we only handle up to two "user" variables.
    // We set the domain variable to the be the one containing the most unique
    // values.
    // This might be easier if the results had meta information telling us
    // how many total variables there are, what types they are of, etc....

    String domainVariable = null;
    String seriesVariable = null;

    Map<String, Set<String>> variableValues = null;

    if (numVariables == 1) {
        domainVariable = firstTrial.getVariables().keySet().iterator().next();
    } else {
        // TODO(tobyr): Do something smarter, like allow the user to specify which
        // variables are domain and series, along with the variables which are
        // held constant.

        variableValues = new HashMap<String, Set<String>>();

        for (int i = 0; i < trials.size(); ++i) {
            Trial trial = trials.get(i);
            Map<String, String> variables = trial.getVariables();

            for (Map.Entry<String, String> entry : variables.entrySet()) {
                String variable = entry.getKey();
                Set<String> set = variableValues.get(variable);
                if (set == null) {
                    set = new TreeSet<String>();
                    variableValues.put(variable, set);
                }
                set.add(entry.getValue());
            }
        }

        TreeMap<Integer, List<String>> numValuesMap = new TreeMap<Integer, List<String>>();

        for (Map.Entry<String, Set<String>> entry : variableValues.entrySet()) {
            Integer numValues = new Integer(entry.getValue().size());
            List<String> variables = numValuesMap.get(numValues);
            if (variables == null) {
                variables = new ArrayList<String>();
                numValuesMap.put(numValues, variables);
            }
            variables.add(entry.getKey());
        }

        if (numValuesMap.values().size() > 0) {
            domainVariable = numValuesMap.get(numValuesMap.lastKey()).get(0);
            seriesVariable = numValuesMap.get(numValuesMap.firstKey()).get(0);
        }
    }

    String valueTitle = "time (ms)"; // This axis is time across all charts.

    if (numVariables == 0) {
        // Show a bar graph, with a single centered simple bar
        // 0 variables means there is only 1 trial
        DefaultCategoryDataset data = new DefaultCategoryDataset();
        data.addValue(firstTrial.getRunTimeMillis(), "result", "result");

        JFreeChart chart = ChartFactory.createBarChart(title, testName, valueTitle, data,
                PlotOrientation.VERTICAL, false, false, false);
        CategoryPlot p = chart.getCategoryPlot();
        ValueAxis axis = p.getRangeAxis();
        axis.setUpperBound(maxTime + maxTime * 0.1);
        return chart;
    } else if (numVariables == 1) {

        // Show a line graph with only 1 series
        // Or.... choose between a line graph and a bar graph depending upon
        // whether the type of the domain is numeric.

        XYSeriesCollection data = new XYSeriesCollection();

        XYSeries series = new XYSeries(domainVariable);

        for (Trial trial : trials) {
            double time = trial.getRunTimeMillis();
            String domainValue = trial.getVariables().get(domainVariable);
            series.add(Double.parseDouble(domainValue), time);
        }

        data.addSeries(series);

        JFreeChart chart = ChartFactory.createXYLineChart(title, domainVariable, valueTitle, data,
                PlotOrientation.VERTICAL, false, false, false);
        XYPlot plot = chart.getXYPlot();
        plot.getRangeAxis().setUpperBound(maxTime + maxTime * 0.1);
        double maxDomainValue = getMaxValue(comparativeResults, domainVariable);
        plot.getDomainAxis().setUpperBound(maxDomainValue + maxDomainValue * 0.1);
        return chart;
    } else if (numVariables == 2) {
        // Show a line graph with two series
        XYSeriesCollection data = new XYSeriesCollection();

        Set<String> seriesValues = variableValues.get(seriesVariable);

        for (String seriesValue : seriesValues) {
            XYSeries series = new XYSeries(seriesValue);

            for (Trial trial : trials) {
                Map<String, String> variables = trial.getVariables();
                if (variables.get(seriesVariable).equals(seriesValue)) {
                    double time = trial.getRunTimeMillis();
                    String domainValue = trial.getVariables().get(domainVariable);
                    series.add(Double.parseDouble(domainValue), time);
                }
            }
            data.addSeries(series);
        }
        // TODO(tobyr) - Handle graphs above 2 variables

        JFreeChart chart = ChartFactory.createXYLineChart(title, domainVariable, valueTitle, data,
                PlotOrientation.VERTICAL, true, true, false);
        XYPlot plot = chart.getXYPlot();
        plot.getRangeAxis().setUpperBound(maxTime + maxTime * 0.1);
        double maxDomainValue = getMaxValue(comparativeResults, domainVariable);
        plot.getDomainAxis().setUpperBound(maxDomainValue + maxDomainValue * 0.1);
        return chart;
    }

    throw new RuntimeException("The ReportImageServer is not yet able to "
            + "create charts for benchmarks with more than two variables.");

    // Sample JFreeChart code for creating certain charts:
    // Leaving this around until we can handle multivariate charts in dimensions
    // greater than two.

    // Code for creating a category data set - probably better with a bar chart
    // instead of line chart
    /*
     * DefaultCategoryDataset data = new DefaultCategoryDataset(); String series
     * = domainVariable;
     * 
     * for ( Iterator it = trials.iterator(); it.hasNext(); ) { Trial trial =
     * (Trial) it.next(); double time = trial.getRunTimeMillis(); String
     * domainValue = (String) trial.getVariables().get( domainVariable );
     * data.addValue( time, series, domainValue ); }
     * 
     * String title = ""; String categoryTitle = domainVariable; PlotOrientation
     * orientation = PlotOrientation.VERTICAL;
     * 
     * chart = ChartFactory.createLineChart( title, categoryTitle, valueTitle,
     * data, orientation, true, true, false );
     */

    /*
     * DefaultCategoryDataset data = new DefaultCategoryDataset(); String
     * series1 = "firefox"; String series2 = "ie";
     * 
     * data.addValue( 1.0, series1, "1024"); data.addValue( 2.0, series1,
     * "2048"); data.addValue( 4.0, series1, "4096"); data.addValue( 8.0,
     * series1, "8192");
     * 
     * data.addValue( 2.0, series2, "1024"); data.addValue( 4.0, series2,
     * "2048"); data.addValue( 8.0, series2, "4096"); data.addValue( 16.0,
     * series2,"8192");
     * 
     * String title = ""; String categoryTitle = "size"; PlotOrientation
     * orientation = PlotOrientation.VERTICAL;
     * 
     * chart = ChartFactory.createLineChart( title, categoryTitle, valueTitle,
     * data, orientation, true, true, false );
     */
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.RegressionReport_UK1.java

/**
 *
 * @param a_SAR_File//from  w w w .  j  a v  a 2  s  .  com
 * @param a_CAS_File
 * @return Object[] result where;
 * result[0] is a String[] of variable names
 * result[1] is a double[number of variables][no of data items]
 * of a_SAR_data
 * result[2] is a double[number of variables][no of data items]
 * of a_CAS_data
 * @throws IOException
 */
protected static Object[] loadDataISARHP_ISARCEP(File a_SAR_File, File a_CAS_File) throws IOException {
    Object[] result = new Object[3];

    TreeMap<String, double[]> a_SAROptimistaionConstraints_TreeMap = loadCASOptimistaionConstraints(a_SAR_File);
    TreeMap<String, double[]> a_CASOptimistaionConstraints_TreeMap = loadCASOptimistaionConstraints(a_CAS_File);

    Vector<String> variables = GeneticAlgorithm_ISARHP_ISARCEP.getVariableList();
    variables.add(0, "Zone_Code");
    String[] variableNames = new String[0];
    variableNames = variables.toArray(variableNames);
    result[0] = variableNames;

    // Format (Flip) data
    double[][] a_SAR_Data = new double[variables.size() - 1][a_SAROptimistaionConstraints_TreeMap.size()];
    double[][] a_CAS_Data = new double[variables.size() - 1][a_SAROptimistaionConstraints_TreeMap.size()];
    String oa;
    double[] a_SARExpectedRow;
    double[] a_CASObservedRow;
    int j = 0;
    Iterator<String> iterator_String = a_SAROptimistaionConstraints_TreeMap.keySet().iterator();
    while (iterator_String.hasNext()) {
        oa = iterator_String.next();
        a_SARExpectedRow = a_SAROptimistaionConstraints_TreeMap.get(oa);
        a_CASObservedRow = a_CASOptimistaionConstraints_TreeMap.get(oa);
        if (a_SARExpectedRow == null) {
            System.out.println(
                    "Warning a_SARExpectedRow == null in loadDataISARHP_ISARCEP(File,File) for OA " + oa);
        } else {
            if (a_CASObservedRow == null) {
                System.out.println(
                        "Warning a_CASObservedRow == null in loadDataISARHP_ISARCEP(File,File) for OA " + oa);
            } else {
                for (int i = 0; i < variables.size() - 1; i++) {
                    a_SAR_Data[i][j] = a_SARExpectedRow[i];
                    a_CAS_Data[i][j] = a_CASObservedRow[i];
                }
            }
        }
        j++;
    }
    result[1] = a_SAR_Data;
    result[2] = a_CAS_Data;
    return result;
}

From source file:com.pindroid.client.PinboardApi.java

/**
 * Performs an api call to Pinboard's http based api methods.
 * //from  w w  w  .  j  a  v a2  s  .com
 * @param url URL of the api method to call.
 * @param params Extra parameters included in the api call, as specified by different methods.
 * @param account The account being synced.
 * @param context The current application context.
 * @return A String containing the response from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 * @throws TooManyRequestsException 
 * @throws PinboardException 
 */
private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account,
        Context context)
        throws IOException, AuthenticationException, TooManyRequestsException, PinboardException {

    final AccountManager am = AccountManager.get(context);

    if (account == null)
        throw new AuthenticationException();

    final String username = account.name;
    String authtoken = "00000000000000000000"; // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401

    try {
        String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        if (tempAuthtoken != null)
            authtoken = tempAuthtoken;
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationException("Error getting auth token");
    }

    params.put("auth_token", username + ":" + authtoken);

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    String apiCallUrl = builder.build().toString();

    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);

    post.setHeader("User-Agent", "PinDroid");
    post.setHeader("Accept-Encoding", "gzip");

    final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    final HttpResponse resp = client.execute(post);

    final int statusCode = resp.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {

        final HttpEntity entity = resp.getEntity();

        InputStream instream = entity.getContent();

        final Header encoding = entity.getContentEncoding();

        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }

        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken);

        try {
            authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("Invalid auth token");
        }

        throw new AuthenticationException();
    } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) {
        throw new TooManyRequestsException(300);
    } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) {
        throw new PinboardException();
    } else {
        throw new IOException();
    }
}

From source file:com.chinamobile.bcbsp.comm.CombinerTool.java

/** combine the message queues.
 * @param outgoingQueue//  ww  w  . ja v  a  2s  .co m
 */
private ConcurrentLinkedQueue<IMessage> combine(ConcurrentLinkedQueue<IMessage> outgoingQueue) {
    // Map of outgoing queues indexed by destination vertex ID.
    TreeMap<String, ConcurrentLinkedQueue<IMessage>> outgoingQueues = new TreeMap<String, ConcurrentLinkedQueue<IMessage>>();
    ConcurrentLinkedQueue<IMessage> tempQueue = null;
    IMessage tempMessage = null;
    // Traverse the outgoing queue and put the messages with the same
    // dstVertexID into the same queue in the tree map.
    Iterator<IMessage> iter = outgoingQueue.iterator();
    String dstVertexID = null;
    /**The result queue for return.*/
    ConcurrentLinkedQueue<IMessage> resultQueue = new ConcurrentLinkedQueue<IMessage>();
    while (iter.hasNext()) {
        tempMessage = iter.next();
        dstVertexID = tempMessage.getDstVertexID();
        tempQueue = outgoingQueues.get(dstVertexID);
        if (tempQueue == null) {
            tempQueue = new ConcurrentLinkedQueue<IMessage>();
        }
        tempQueue.add(tempMessage);
        outgoingQueues.put(dstVertexID, tempQueue);
    }
    // Do combine operation for each of the outgoing queues.
    for (Entry<String, ConcurrentLinkedQueue<IMessage>> entry : outgoingQueues.entrySet()) {
        tempQueue = entry.getValue();
        tempMessage = (IMessage) this.combiner.combine(tempQueue.iterator());
        resultQueue.add(tempMessage);
    }
    outgoingQueue.clear();
    outgoingQueues.clear();
    return resultQueue;
}

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

/**
 * Return HashMap of HashMaps brand-&gt;modelname-&gt;WurflDevice
 * //from w  w  w .java  2 s .  c o m
 */
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:com.opengamma.analytics.financial.interestrate.CashFlowEquivalentCalculator.java

@Override
public AnnuityPaymentFixed visitBondFixedSecurity(final BondFixedSecurity bond, final YieldCurveBundle curves) {
    Validate.notNull(curves);//  w  ww.  j  a v  a 2  s . c  o  m
    Validate.notNull(bond);
    Currency ccy = bond.getCurrency();
    TreeMap<Double, Double> flow = new TreeMap<Double, Double>();
    AnnuityPaymentFixed cfeNom = visit(bond.getNominal(), curves);
    AnnuityPaymentFixed cfeCpn = visit(bond.getCoupon(), curves);
    for (final PaymentFixed p : cfeNom.getPayments()) {
        flow.put(p.getPaymentTime(), p.getAmount());
    }
    for (final PaymentFixed p : cfeCpn.getPayments()) {
        addcf(flow, p.getPaymentTime(), p.getAmount());
    }
    PaymentFixed[] agregatedCfe = new PaymentFixed[flow.size()];
    int loopcf = 0;
    for (double time : flow.keySet()) {
        agregatedCfe[loopcf++] = new PaymentFixed(ccy, time, flow.get(time), cfeCpn.getDiscountCurve());
    }
    return new AnnuityPaymentFixed(agregatedCfe);

}

From source file:com.opengamma.analytics.financial.interestrate.CashFlowEquivalentCalculator.java

@Override
public AnnuityPaymentFixed visitSwap(final Swap<?, ?> swap, final YieldCurveBundle curves) {
    Validate.notNull(curves);/*from  w w w  . ja  v  a2  s.c om*/
    Validate.notNull(swap);
    Currency ccy = swap.getFirstLeg().getCurrency();
    Validate.isTrue(ccy.equals(swap.getSecondLeg().getCurrency()),
            "Cash flow equivalent available only for single currency swaps.");
    TreeMap<Double, Double> flow = new TreeMap<Double, Double>();
    AnnuityPaymentFixed cfeLeg1 = visit(swap.getFirstLeg(), curves);
    AnnuityPaymentFixed cfeLeg2 = visit(swap.getSecondLeg(), curves);
    for (final PaymentFixed p : cfeLeg1.getPayments()) {
        flow.put(p.getPaymentTime(), p.getAmount());
    }
    for (final PaymentFixed p : cfeLeg2.getPayments()) {
        addcf(flow, p.getPaymentTime(), p.getAmount());
    }
    PaymentFixed[] agregatedCfe = new PaymentFixed[flow.size()];
    int loopcf = 0;
    for (double time : flow.keySet()) {
        agregatedCfe[loopcf++] = new PaymentFixed(ccy, time, flow.get(time), cfeLeg1.getDiscountCurve());
    }
    return new AnnuityPaymentFixed(agregatedCfe);
}

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

/**
 * Return TreeMap of device IDs to WurflDevices representing actual devices
 * (i.e. this device element represents a real device and a bunch of
 * subdevices with similar software subversions.
 * //from   w  w  w. ja  v a 2  s .c om
 */

public synchronized TreeMap<String, WurflDevice> getActualDeviceElementsList() {

    if (actualDeviceElementsList.isEmpty()) {
        CapabilityMatrix cm = this.getObjectsManager().getCapabilityMatrixInstance();
        TreeMap<String, Element> actualXOMDevices = wu.getActualDeviceElementsList();
        Iterator<String> keys = actualXOMDevices.keySet().iterator();
        while (keys.hasNext()) {

            String key = keys.next();
            Element el = actualXOMDevices.get(key);
            WurflDevice wd = new WurflDevice(el);
            String bn = cm.getCapabilityForDevice(key, "brand_name");
            String mn = cm.getCapabilityForDevice(key, "model_name");
            // only devices with name and brand defined in the WURFL please
            if (!bn.equals("") && !mn.equals("")) {
                wd.setBrandName(bn);
                wd.setModelName(mn);
                actualDeviceElementsList.put(key, wd);
            }
            // else { //just for debugging purposes
            // log.debug("Discarding actual device: "+wd.getId());
            // }
        }
    }
    return actualDeviceElementsList;
}

From source file:com.sfs.whichdoctor.analysis.RevenueAnalysisDAOImpl.java

/**
 * Batch analysis.//from ww  w  . j a v  a  2 s.co  m
 *
 * @param search the search
 *
 * @return the revenue analysis bean
 *
 * @throws WhichDoctorAnalysisDaoException the which doctor analysis dao
 *             exception
 */
@SuppressWarnings("unchecked")
public final RevenueAnalysisBean batchAnalysis(final RevenueAnalysisBean search)
        throws WhichDoctorAnalysisDaoException {

    /* Zero out values in revenue analysis bean */
    search.setValue(0);
    search.setNetValue(0);
    /* Set ordering system of returned results */
    String sqlORDER = " ORDER BY receipt.BatchReference, receipt.ReceiptNo";
    StringBuffer sqlWHERE = new StringBuffer();

    Collection<Object> parameters = new ArrayList<Object>();
    if (search.getSQLWhereStatement() != null) {
        if (search.getSQLWhereStatement().compareTo("") != 0) {
            sqlWHERE.append(" AND ");
            sqlWHERE.append(search.getSQLWhereStatement());
        }
    }
    if (search.getSearchParameters() != null) {
        parameters = search.getSearchParameters();
    }

    /* BUILD SQL Statement */
    final StringBuffer searchSQL = new StringBuffer();
    searchSQL.append(this.getSQL().getValue("revenue"));
    searchSQL.append(sqlWHERE.toString());
    searchSQL.append(" GROUP BY payment.PaymentId, receipt.BatchReference ");
    searchSQL.append(sqlORDER);

    dataLogger.info("SQL Query: " + searchSQL.toString());

    Collection<RevenueBean> results = new ArrayList<RevenueBean>();
    try {
        results = this.getJdbcTemplateReader().query(searchSQL.toString(), parameters.toArray(),
                new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return loadBatchRevenue(rs);
                    }
                });

    } catch (IncorrectResultSizeDataAccessException ie) {
        // No results found for this search
        dataLogger.debug("No results found for this search: " + ie.getMessage());
    }

    final TreeMap<Object, ArrayList<RevenueBean>> batchMap = new TreeMap<Object, ArrayList<RevenueBean>>();

    for (RevenueBean revenue : results) {
        ArrayList<RevenueBean> revenueList = new ArrayList<RevenueBean>();
        if (batchMap.containsKey(revenue.getBatchReference())) {
            revenueList = batchMap.get(revenue.getBatchReference());
        }
        revenueList.add(revenue);
        batchMap.put(revenue.getBatchReference(), revenueList);
    }

    final RevenueAnalysisBean summary = consolidateSummary(batchMap);
    search.setValue(summary.getValue());
    search.setNetValue(summary.getNetValue());
    search.setGSTValues(summary.getGSTValues());
    search.setRevenue(summary.getRevenue());

    return search;
}