Example usage for java.util HashMap keySet

List of usage examples for java.util HashMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

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

Usage

From source file:edu.utexas.cs.tactex.ShiftingPredictorTest.java

@Test
public void testShiftingPredictorNoShifts() {
    HashMap<CustomerInfo, HashMap<TariffSpecification, ShiftedEnergyData>> cust2trf2energy = shiftingPredictorNoShifts
            .updateEstimatedEnergyWithShifting(customer2estimatedEnergy, predictedCustomerSubscriptions,
                    currentTimeslot);//from ww w. jav  a 2s .  c  om
    // verify keys are cust1 and cust2
    assertEquals("2 customers keys in result", 2, cust2trf2energy.keySet().size());
    assertNotNull("cust1 in keys", cust2trf2energy.get(cust1));
    assertNotNull("cust2 in keys", cust2trf2energy.get(cust2));

    // verify cust[i] is mapped to spec1=>energy[i] spec2=>energy[i] 
    //
    // cust1
    HashMap<TariffSpecification, ShiftedEnergyData> cust1_spec2energy = cust2trf2energy.get(cust1);
    ArrayRealVector predictedenergy11 = cust1_spec2energy.get(spec1).getShiftedEnergy();
    ArrayRealVector predictedenergy12 = cust1_spec2energy.get(spec2).getShiftedEnergy();
    assertNotNull("cust1: spec1=>energy1 exists", predictedenergy11);
    assertEquals("cust1: spec1=>energy1 as expected", energy1, predictedenergy11);
    assertNotNull("cust1: spec2=>energy1 exists", predictedenergy12);
    assertEquals("cust1: spec2=>energy1 as expected", energy1, predictedenergy12);
    //
    // cust2
    HashMap<TariffSpecification, ShiftedEnergyData> cust2_spec2energy = cust2trf2energy.get(cust2);
    ArrayRealVector predictedenergy21 = cust2_spec2energy.get(spec1).getShiftedEnergy();
    ArrayRealVector predictedenergy22 = cust2_spec2energy.get(spec2).getShiftedEnergy();
    assertNotNull("cust2: spec1=>energy2 exists", predictedenergy21);
    assertEquals("cust2: spec1=>energy2 as expected", energy2, predictedenergy21);
    assertNotNull("cust2: spec2=>energy2 exists", predictedenergy22);
    assertEquals("cust2: spec2=>energy2 as expected", energy2, predictedenergy22);

}

From source file:com.marketcloud.marketcloud.Json.java

/**
 * Parses a JSONObject, looking for the given structure. <br />
 * <br />/*w  w w.j av a2 s . c o  m*/
 * It differs from the other parseData because the user should provide a pre-prepared Hashmap that will be
 * filled by the method. The keys of the map will be used as the string array of the other parseData.
 * <br />
 * In order to avoid override of data that you need to keep, and to use the method without getting an
 * exception, you could pass an "ignore" list containing the keys that you want the method to ignore.
 * <br />
 * Note: if the structure is not correct, the method will throw an exception and fail. If the JSONObject
 * contains a JSONArray, only the first argument of the array (the first object) will be parsed.
 *
 * @param map pre-prepared Hashmap
 * @return an Hashmap with the parsed data
 */
@SuppressWarnings("unused")
public HashMap<String, Object> parseData(HashMap<String, Object> map, JSONObject jsonObject,
        List<String> ignore) throws JSONException {
    if (jsonObject.has("data"))
        jsonObject = getData(jsonObject)[0];

    for (String key : map.keySet()) {
        if (!ignore.contains(key))
            map.put(key, jsonObject.get(key));
    }

    return map;
}

From source file:ffx.potential.parameters.OutOfPlaneBendType.java

/**
 * Remap new atom classes to known internal ones.
 *
 * @param typeMap a lookup between new atom types and known atom types.
 * @return//from www .j  a va 2 s. c om
 */
public OutOfPlaneBendType patchClasses(HashMap<AtomType, AtomType> typeMap) {
    int count = 0;
    int len = atomClasses.length;
    /**
     * Look for new OutOfPlaneBends that contain 1 mapped atom classes.
     */
    for (AtomType newType : typeMap.keySet()) {
        for (int i = 0; i < len; i++) {
            if (atomClasses[i] == newType.atomClass) {
                count++;
            }
        }
    }
    /**
     * If found, create a new OutOfPlaneBend that bridges to known classes.
     */
    if (count == 1) {
        int newClasses[] = Arrays.copyOf(atomClasses, len);
        for (AtomType newType : typeMap.keySet()) {
            for (int i = 0; i < len; i++) {
                if (atomClasses[i] == newType.atomClass) {
                    AtomType knownType = typeMap.get(newType);
                    newClasses[i] = knownType.atomClass;
                }
            }
        }
        return new OutOfPlaneBendType(newClasses, forceConstant);
    }
    return null;
}

From source file:Data.c_CardDB.java

public boolean isInLegal(c_Deck deck, Legals leg) {
    boolean isDeckInLegal = true;
    c_Card card;/*  ww  w.ja  v  a  2s  .co m*/
    if (m_expansionDB.doesLegalContainLegals(leg)) {
        HashMap<Integer, Keyword> list = m_expansionDB.getOtherLegals(leg);
        for (int mid : deck.getAllCards().keySet()) {
            card = getCard(mid);
            HashMap<c_Expansion, Integer> expList = getExpansionList(card.Name);
            ArrayList<Integer> legalExpansions = m_expansionDB.getLegalExpansions(leg);
            for (c_Expansion exp : expList.keySet()) {
                if (!legalExpansions.contains(m_expansionDB.getEID(exp))) {
                    isDeckInLegal = false;
                    expList = null;
                    legalExpansions = null;
                    break;
                }
            }

            int nameHash = card.Name.hashCode();
            if (list.containsKey(nameHash)) {
                if (list.get(nameHash) == Keyword.Banned
                        || deck.getAmountOfCard(mid, c_Deck.WhichHalf.BOTH) > 1) {
                    isDeckInLegal = false;
                    list = null;
                    break;
                }
            }
        }
    }
    card = null;
    return isDeckInLegal;
}

From source file:edu.utexas.cs.tactex.utils.ChargeEstimatorDefault.java

@Override
public HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> estimateRelevantTariffCharges(
        List<TariffSpecification> tariffSpecs,
        HashMap<CustomerInfo, HashMap<TariffSpecification, BrokerUtils.ShiftedEnergyData>> customer2ShiftedEnergy) {

    // Assumption: ignoring regulation charges in tariff evaluation helper
    HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> estimatedCharges = new HashMap<CustomerInfo, HashMap<TariffSpecification, Double>>();
    for (CustomerInfo customerInfo : customer2ShiftedEnergy.keySet()) {
        // create entry for customer
        HashMap<TariffSpecification, Double> tariffEvaluations = new HashMap<TariffSpecification, Double>();
        // scan tariffs and evaluate them 
        for (TariffSpecification spec : tariffSpecs) {
            if (customerInfo.getPowerType().canUse(spec.getPowerType())) {
                double charge = estimateCharge(
                        customer2ShiftedEnergy.get(customerInfo).get(spec).getShiftedEnergy(), spec);
                Double inconvenienceFactor = customer2ShiftedEnergy.get(customerInfo).get(spec)
                        .getInconvenienceFactor();
                double evaluation = charge + inconvenienceFactor;
                log.debug("inconv charge=" + charge + " inconvenienceFactor=" + inconvenienceFactor
                        + " evaluation=" + evaluation /*+ " ratio=" + evaluation/charge*/);
                tariffEvaluations.put(spec, evaluation);
            }//from  w  ww. jav a 2  s . c  om
        }

        if (tariffEvaluations.size() > 0) {
            estimatedCharges.put(customerInfo, tariffEvaluations);
        }
    }
    return estimatedCharges;
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();/*from w  w  w . j a va  2  s . c  o  m*/

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:ffx.potential.parameters.StretchBendType.java

/**
 * Remap new atom classes to known internal ones.
 *
 * @param typeMap a lookup between new atom types and known atom types.
 * @return/*  w w  w .  ja v a2 s  .c  o m*/
 */
public StretchBendType patchClasses(HashMap<AtomType, AtomType> typeMap) {
    int count = 0;
    int len = atomClasses.length;
    /**
     * Check if this StetchBendType contain 1 or 2 mapped atom classes.
     */
    for (AtomType newType : typeMap.keySet()) {
        for (int i = 0; i < len; i++) {
            if (atomClasses[i] == newType.atomClass) {
                count++;
            }
        }
    }
    /**
     * If found, create a new StetchBendType that bridges to known classes.
     */
    if (count == 1 || count == 2) {
        int newClasses[] = Arrays.copyOf(atomClasses, len);
        for (AtomType newType : typeMap.keySet()) {
            for (int i = 0; i < len; i++) {
                if (atomClasses[i] == newType.atomClass) {
                    AtomType knownType = typeMap.get(newType);
                    newClasses[i] = knownType.atomClass;
                }
            }
        }
        return new StretchBendType(newClasses, forceConstants);
    }
    return null;
}

From source file:com.redhat.victims.database.VictimsSqlDB.java

/**
 * Update all records in the given {@link RecordStream}. This will remove
 * the record if it already exits and then add it. Otherwise, it just adds
 * it.//from   ww  w  . ja  va2 s.  c o  m
 *
 * @param recordStream
 * @throws SQLException
 * @throws IOException
 */
protected int update(Connection connection, RecordStream recordStream) throws SQLException, IOException {
    int count = 0;
    PreparedStatement insertFileHash = statement(connection, Query.INSERT_FILEHASH);
    PreparedStatement insertMeta = statement(connection, Query.INSERT_META);
    PreparedStatement insertCVE = statement(connection, Query.INSERT_CVES);
    while (recordStream.hasNext()) {
        VictimsRecord vr = recordStream.getNext();
        String hash = vr.hash.trim();

        // remove if already present
        deleteRecord(connection, hash);

        // add the new/updated hash
        int id = insertRecord(connection, hash);

        // insert file hahes
        for (String filehash : vr.getHashes(Algorithms.SHA512).keySet()) {
            setObjects(insertFileHash, id, filehash.trim());
            insertFileHash.addBatch();
        }

        // insert metadata key-value pairs
        HashMap<String, String> md = vr.getFlattenedMetaData();
        for (String key : md.keySet()) {
            setObjects(insertMeta, id, key, md.get(key));
            insertMeta.addBatch();
        }

        // insert cves
        for (String cve : vr.cves) {
            setObjects(insertCVE, id, cve.trim());
            insertCVE.addBatch();
        }

        count++;
    }
    executeBatchAndClose(insertFileHash, insertMeta, insertCVE);
    return count;
}

From source file:com.compomics.pride_asa_pipeline.core.logic.modification.PTMMapper.java

/**
 * Processes all mods before they are set to the modification profile
 * modification profile. Unknown PTMs are added to the unknown PTMs
 * arraylist./*from  w w  w.  jav  a  2 s. co m*/
 *
 * @param modificationMap hashmap containing modification names and their
 * fixed/variable status
 * @param unknownPtms the list of unknown PTMS, updated during this method
 * @return the filled up modification profile
 */
public PtmSettings buildTotalModProfile(HashMap<String, Boolean> modificationMap,
        ArrayList<String> unknownPtms) {
    PtmSettings modProfile = new PtmSettings();
    for (String aModificationName : modificationMap.keySet()) {
        if (!addPTMToProfile(modProfile, modificationMap, aModificationName)) {
            factory.convertPridePtm(aModificationName, modProfile, unknownPtms,
                    modificationMap.get(aModificationName));
        }
        //check if the unknowns have an alternative and retry them...
        for (String anUnknownPTM : unknownPtms) {
            String temp = lookupRealModName(anUnknownPTM);
            if (addPTMToProfile(modProfile, modificationMap, temp)) {
                unknownPtms.remove(anUnknownPTM);
            }
            ;
        }
    }
    return modProfile;
}

From source file:org.openmeetings.app.remote.red5.ClientListManager.java

/**
 * Get current clients and extends the room client with its potential 
 * audio/video client and settings//w  w  w . java  2  s. c  o m
 * 
 * @param room_id
 * @return
 */
public HashMap<String, RoomClient> getRoomClients(Long room_id) {
    try {

        HashMap<String, RoomClient> roomClientList = new HashMap<String, RoomClient>();
        HashMap<String, RoomClient> clientListRoom = this.getClientListByRoom(room_id);
        for (Iterator<String> iter = clientListRoom.keySet().iterator(); iter.hasNext();) {
            String key = iter.next();
            RoomClient rcl = this.getClientByStreamId(key);

            if (rcl.getIsAVClient()) {
                continue;
            }

            // Add user to List
            roomClientList.put(key, rcl);
        }

        return roomClientList;
    } catch (Exception err) {
        log.error("[getRoomClients]", err);
    }
    return null;
}