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:BitLottoVerify.java

public static Map<String, Long> getPaymentsBlockExplorer(String addr) throws Exception {
    URL u = new URL("http://blockexplorer.com/address/" + addr);
    Scanner scan = new Scanner(u.openStream());

    TreeMap<String, Long> map = new TreeMap<String, Long>();

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        StringTokenizer stok = new StringTokenizer(line, "\"#");
        while (stok.hasMoreTokens()) {
            String token = stok.nextToken();
            if (token.startsWith("/tx/")) {
                String tx = token.substring(4);
                line = scan.nextLine();//from  w w  w. ja  v  a2 s .c  o  m
                line = scan.nextLine();
                StringTokenizer stok2 = new StringTokenizer(line, "<>");
                stok2.nextToken();
                double amt = Double.parseDouble(stok2.nextToken());
                long amt_l = (long) Math.round(amt * 1e8);
                map.put(tx, amt_l);

            }
        }
    }
    return map;
}

From source file:dk.sdu.mmmi.hwr.group2.Utils.java

public static TreeMap<Calendar, Match> getAllMatches(boolean ignoreEmpty, boolean refresh) {
    if (!refresh && allCachedMaches != null) {
        return allCachedMaches;
    }// w ww  . ja  v a 2  s.com
    JSONObject json;
    try {
        json = new JSONObject(readURL("http://178.62.164.18:8080/foosball/api/match/getAll"));
    } catch (IOException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    TreeMap<Calendar, Match> matches = new TreeMap();

    JSONArray matchesJSON = json.getJSONArray("matches");
    for (int i = 0; i < matchesJSON.length(); i++) {
        JSONObject matchJSON = matchesJSON.getJSONObject(i);
        Match match = new Match(matchJSON.getInt("id"), matchJSON.getInt("startTime") * 1000l);
        JSONArray goalsJSON = matchJSON.getJSONArray("goals");

        for (int k = 0; k < goalsJSON.length(); k++) {
            JSONObject goal = goalsJSON.getJSONObject(k);
            int player = goal.getInt("player");
            int time = goal.getInt("time");
            match.addGoal(player, time * 1000l);
        }

        if (ignoreEmpty && match.getGoalsMap().isEmpty()) {
            continue;
        }
        matches.put(match.getOldestGoalTime(), match);
    }
    allCachedMaches = matches;
    return allCachedMaches;
}

From source file:org.opendatakit.persistence.table.GrantedAuthorityHierarchyTable.java

public static final TreeMap<String, TreeSet<String>> getEntireGrantedAuthorityHierarchy(Datastore ds, User user)
        throws ODKDatastoreException {

    GrantedAuthorityHierarchyTable relation;
    List<? extends CommonFieldsBase> groupsList;
    relation = GrantedAuthorityHierarchyTable.assertRelation(ds, user);
    Query query = ds.createQuery(relation, "GrantedAuthorityHierarchyTable.getEntireGrantedAuthorityHierarchy",
            user);/*from w w  w.ja  v a  2  s . c o m*/
    query.addSort(GrantedAuthorityHierarchyTable.DOMINATING_GRANTED_AUTHORITY, Direction.ASCENDING);
    groupsList = query.executeQuery();

    TreeMap<String, TreeSet<String>> inheritFrom = new TreeMap<String, TreeSet<String>>();
    for (CommonFieldsBase b : groupsList) {
        GrantedAuthorityHierarchyTable group = (GrantedAuthorityHierarchyTable) b;

        GrantedAuthority dom = group.getDominatingGrantedAuthority();
        GrantedAuthority sub = group.getSubordinateGrantedAuthority();

        if (!GrantedAuthorityName.permissionsCanBeAssigned(dom.toString()))
            continue;
        TreeSet<String> auths = inheritFrom.get(dom.getAuthority());
        if (auths == null) {
            auths = new TreeSet<String>();
            inheritFrom.put(dom.getAuthority(), auths);
        }
        auths.add(sub.getAuthority());
    }

    return inheritFrom;
}

From source file:com.adsapient.shared.service.FiltersService.java

public static void fillCountryMap(List<CountryAbbrEntity> countries) {
    if ((countries == null) || (countries.size() == 0)) {
        logger.warn("Country list is empty");
        mapCountries = new TreeMap<String, String>();
        countryIndexArray = new String[0];

        return;//from  w ww.  ja  v  a2s.  c  o m
    }

    ArrayList<String> list = new ArrayList<String>();

    try {
        TreeMap<String, String> map = new TreeMap<String, String>();
        int i = 0;

        for (CountryAbbrEntity country : countries) {
            String key = country.getCountryAbbr2();
            map.put(key, country.getCountryName());

            if (key.equals(AdsapientConstants.COUNTRY_ABBR_ADDRES_ANONIMOUS)
                    || key.equals(AdsapientConstants.COUNTRY_ABBR_ADDRES_RESERVED)
                    || key.equals(AdsapientConstants.COUNTRY_ABBR_ADDRES_NOT_FOUND)) {
                list.add(0, key);
            } else {
                list.add(key);
            }
        }

        mapCountries = map;

        countryIndexArray = new String[list.size()];
        countryIndexArray = list.toArray(countryIndexArray);
    } catch (Exception e) {
        logger.error("Error getting Countries", e);
    }
}

From source file:com.liveramp.hank.coordinator.Hosts.java

public static Map<String, FilesystemStatisticsAggregator> computeFilesystemStatistics(Host host)
        throws IOException {
    String filesystemsStatistics = host.getStatistic(FILESYSTEM_STATISTICS_KEY);

    if (filesystemsStatistics == null) {
        return Collections.emptyMap();
    } else {//from   ww  w  .j a  va  2  s . com
        TreeMap<String, FilesystemStatisticsAggregator> result = new TreeMap<String, FilesystemStatisticsAggregator>();
        String[] filesystemStatistics = filesystemsStatistics.split("\n");
        for (String statistics : filesystemStatistics) {
            if (statistics.length() == 0) {
                continue;
            }
            String[] tokens = statistics.split(" ");
            String filesystemRoot = tokens[0];
            long totalSpace = Long.parseLong(tokens[1]);
            long usableSpace = Long.parseLong(tokens[2]);
            result.put(filesystemRoot, new FilesystemStatisticsAggregator(totalSpace, usableSpace));
        }
        return result;
    }
}

From source file:agendavital.modelo.data.Noticia.java

/**
 * Funcion coloreadora del calendario//from   w w w  .ja v a2s . c o  m
 *
 * @return
 * @throws agendavital.modelo.excepciones.ConexionBDIncorrecta
 *
 */
public static TreeMap<LocalDate, String> getNoticiasFecha() throws ConexionBDIncorrecta {
    ResultSet rs = null;
    TreeMap<LocalDate, String> noticias = new TreeMap<>();
    try (Connection conexion = ConfigBD.conectar()) {
        String consulta = String.format("SELECT categoria, fecha from Noticias;");
        rs = conexion.createStatement().executeQuery(consulta);
        while (rs.next()) {
            String categoria = rs.getString("categoria");
            String fecha = rs.getString("fecha");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
            LocalDate date = LocalDate.parse(fecha, formatter);
            noticias.put(date, categoria);
        }
    } catch (SQLException e) {
        throw new ConexionBDIncorrecta();
    }
    return noticias;
}

From source file:com.sun.faces.generate.GeneratorUtil.java

/**
 * @return a SortedMap, where the keys are component-family String entries,
 *         and the values are {@link com.sun.faces.config.beans.ComponentBean}
 *         instances Only include components that do not have a base
 *         component type./*  w w  w . j av a 2 s.c  om*/
 */
public static Map<String, ComponentBean> getComponentFamilyComponentMap(FacesConfigBean configBean) {

    TreeMap<String, ComponentBean> result = new TreeMap<String, ComponentBean>();
    ComponentBean component;
    ComponentBean[] components = configBean.getComponents();
    for (int i = 0, len = components.length; i < len; i++) {
        component = components[i];
        if (component == null) {
            throw new IllegalStateException("No Components Found");
        }
        if (component.isIgnore()) {
            continue;
        }
        if (component.getBaseComponentType() != null) {
            continue;
        }
        String componentFamily = component.getComponentFamily();

        result.put(componentFamily, component);
    }

    return result;

}

From source file:com.sangupta.jerry.oauth.OAuthUtils.java

/**
 * Given a list of parameters (including the OAuth parameters) build the
 * unique parameter string that is used to generate the signable string.
 * //  w  w  w  . j av  a2  s  .c o  m
 * @param params
 *            the request parameters if any
 * 
 * @param oauthParams
 *            the OAuth params
 * 
 * @return the parameters string to be used to generate the signable string
 */
public static String buildParamString(TreeMap<String, String> params, WebForm oauthParams) {
    StringBuilder builder = new StringBuilder(1024);

    // add all to the list of params
    for (NameValuePair pair : oauthParams.build()) {
        if (pair.getName().startsWith("oauth_")) {
            params.put(pair.getName(), pair.getValue());
        }
    }

    // build the string
    boolean first = true;
    for (String key : params.keySet()) {
        if (!first) {
            builder.append('&');
        } else {
            first = false;
        }

        builder.append(key);
        builder.append('=');
        builder.append(UriUtils.encodeURIComponent(params.get(key)));
    }

    return builder.toString();
}

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

/**
 * Retrieves a specific list of bookmarks from Pinboard.
 * //from  www  . j a  v  a 2  s .c om
 * @param hashes A list of bookmark hashes to be retrieved.  
 *    The hashes are MD5 hashes of the URL of the bookmark.
 * 
 * @param account The account being synced.
 * @param context The current application context.
 * @return A list of bookmarks received from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 * @throws TooManyRequestsException 
 * @throws PinboardException 
 */
public static ArrayList<Bookmark> getBookmark(ArrayList<String> hashes, Account account, Context context)
        throws IOException, AuthenticationException, TooManyRequestsException, PinboardException {

    ArrayList<Bookmark> bookmarkList = new ArrayList<Bookmark>();
    TreeMap<String, String> params = new TreeMap<String, String>();
    String hashString = "";
    InputStream responseStream = null;
    String url = FETCH_BOOKMARK_URI;

    for (String h : hashes) {
        if (hashes.get(0) != h) {
            hashString += "+";
        }
        hashString += h;
    }
    params.put("meta", "yes");
    params.put("hashes", hashString);

    responseStream = PinboardApiCall(url, params, account, context);
    SaxBookmarkParser parser = new SaxBookmarkParser(responseStream);

    try {
        bookmarkList = parser.parse();
    } catch (ParseException e) {
        Log.e(TAG, "Server error in fetching bookmark list");
        throw new IOException();
    }

    responseStream.close();
    return bookmarkList;
}

From source file:com.eucalyptus.objectstorage.pipeline.handlers.ObjectStorageAuthenticationHandler.java

/**
 * Ensure that only one header for each name exists (i.e. not 2 Authorization headers)
 * Accomplish this by comma-delimited concatenating any duplicates found as per HTTP 1.1 RFC 2616 section 4.2
 * <p/>//from  w ww .  j  a v a2s .c  om
 * TODO: Also, should convert all headers to lower-case for consistent processing later. This is okay since headers are case-insensitive.
 * <p/>
 * in HTTP
 *
 * @param httpRequest
 */
private static void canonicalizeHeaders(MappingHttpRequest httpRequest) {
    //Iterate through headers and find duplicates, concatenate their values together and remove from
    // request as we find them.
    TreeMap<String, String> headerMap = new TreeMap<String, String>();
    String value = null;

    //Construct a map of the normalized headers, cannot modify in-place since
    // conconcurrent-modify exception may result
    for (String header : httpRequest.getHeaderNames()) {
        //TODO: zhill, put in the map in lower-case form.
        headerMap.put(header, Joiner.on(',').join(httpRequest.getHeaders(header)));
    }

    //Remove *all* headers
    httpRequest.clearHeaders();

    //Add the normalized headers back into the request
    for (String foundHeader : headerMap.keySet()) {
        httpRequest.addHeader(foundHeader, headerMap.get(foundHeader).toString());
    }
}