Example usage for java.util HashMap entrySet

List of usage examples for java.util HashMap entrySet

Introduction

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

Prototype

Set entrySet

To view the source code for java.util HashMap entrySet.

Click Source Link

Document

Holds cached entrySet().

Usage

From source file:com.google.gwt.emultest.java.util.HashMapTest.java

/**
 * Check the state of a newly constructed, empty HashMap.
 *
 * @param hashMap/*from   w w  w .  j  av  a 2s  .  com*/
 */
private static void checkEmptyHashMapAssumptions(HashMap<?, ?> hashMap) {
    assertNotNull(hashMap);
    assertTrue(hashMap.isEmpty());

    assertNotNull(hashMap.values());
    assertTrue(hashMap.values().isEmpty());
    assertTrue(hashMap.values().size() == 0);

    assertNotNull(hashMap.keySet());
    assertTrue(hashMap.keySet().isEmpty());
    assertTrue(hashMap.keySet().size() == 0);

    assertNotNull(hashMap.entrySet());
    assertTrue(hashMap.entrySet().isEmpty());
    assertTrue(hashMap.entrySet().size() == 0);

    assertEmptyIterator(hashMap.entrySet().iterator());
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends a {@link MultipartEntity} post with text and image files.
 *
 * @param url        the url to which to POST to.
 * @param user       the user or <code>null</code>.
 * @param pwd        the password or <code>null</code>.
 * @param stringsMap the {@link HashMap} containing the key and string pairs to send.
 * @param filesMap   the {@link HashMap} containing the key and image file paths
 *                   (jpg, png supported) pairs to send.
 * @throws Exception if something goes wrong.
 *///from   w  w w  . ja v  a 2 s  .  com
public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap,
        HashMap<String, File> filesMap) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(url);

    if (user != null && pwd != null && user.trim().length() > 0 && pwd.trim().length() > 0) {
        String ret = getB64Auth(user, pwd);
        httppost.setHeader("Authorization", ret);
    }

    MultipartEntity mpEntity = new MultipartEntity();
    Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet();
    for (Entry<String, String> stringEntry : stringsEntrySet) {
        ContentBody cbProperties = new StringBody(stringEntry.getValue());
        mpEntity.addPart(stringEntry.getKey(), cbProperties);
    }

    Set<Entry<String, File>> filesEntrySet = filesMap.entrySet();
    for (Entry<String, File> filesEntry : filesEntrySet) {
        String propName = filesEntry.getKey();
        File file = filesEntry.getValue();
        if (file.exists()) {
            String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png";
            ContentBody cbFile = new FileBody(file, "image/" + ext);
            mpEntity.addPart(propName, cbFile);
        }
    }

    httppost.setEntity(mpEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
}

From source file:edu.ehu.galan.lite.model.Document.java

/**
 * Save the results of the document in a Json text file, if you want to use current directory
 * use "./" or the absolute path, the method will check whether the Dir exists or not and will
 * try to create according to that// w ww  .  j  av a 2s.  c o  m
 *
 * @param pFolder - where you want to save the results
 * @param pDoc
 */
public static void saveJsonToDir(String pFolder, Document pDoc) {
    Doc msg = new Doc();
    msg.setName(pDoc.name);
    msg.setKnowledgeSource(pDoc.getSource().toString());
    List<MsgTop> list = new ArrayList<>();
    for (Topic string : pDoc.topicList) {
        MsgTop top = new MsgTop();
        top.setSourceTitle(string.getSourceTitle());
        top.setDefinition(string.getSourceDef());
        top.setId(string.getId());
        top.setTopic(string.getTopic());
        top.setLabels(string.getLabelList());
        top.setDomainRelatedness(string.getDomainRelatedness());

        List<Translation> transList = new ArrayList<>();
        HashMap<String, String> map = string.getTranslations();
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = it.next();
            Translation trans = new Translation();
            trans.setLang(pairs.getKey());
            trans.setText(pairs.getValue());
            transList.add(trans);
        }
        List<Link> linksIn = new ArrayList<>();
        HashMap<Integer, Double> map3 = string.getLinksIn();
        Iterator<Map.Entry<Integer, Double>> it2 = map3.entrySet().iterator();
        while (it2.hasNext()) {
            Map.Entry<Integer, Double> pairs = it2.next();
            Link link = new Link();
            link.setId(pairs.getKey());
            link.setRelatedness(pairs.getValue());
            linksIn.add(link);
        }
        List<Link> linksOut = new ArrayList<>();
        HashMap<Integer, Double> map4 = string.getLinksOut();
        Iterator<Map.Entry<Integer, Double>> it3 = map4.entrySet().iterator();
        while (it3.hasNext()) {
            Map.Entry<Integer, Double> pairs = it3.next();
            Link link = new Link();
            link.setId(pairs.getKey());
            link.setRelatedness(pairs.getValue());
            linksOut.add(link);
        }
        top.setLinksIn(linksIn);
        top.setLinksOut(linksOut);
        top.setTranslations(transList);
        List<Parent> parentList = new ArrayList<>();
        HashMap<Integer, String> map2 = string.getParentCategories();
        Iterator<Map.Entry<Integer, String>> itr = map2.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<Integer, String> pairs = itr.next();
            Parent trans = new Parent();
            trans.setId(pairs.getKey());
            trans.setSourceTitle(pairs.getValue());
            parentList.add(trans);
        }
        top.setParentCategories(parentList);
        list.add(top);
    }
    msg.setTopics(list);
    List<DomainRel> listRel = new ArrayList<>();
    for (Map.Entry<Integer, String> pair : pDoc.domainTopics.entrySet()) {
        DomainRel rel = new DomainRel();
        rel.setId(pair.getKey());
        rel.setTitle(pair.getValue());
        listRel.add(rel);
    }
    msg.setDomainTopics(listRel);
    if (pFolder.equals("")) {
        pFolder = System.getProperty("user.dir");

    }
    if (Files.isDirectory(Paths.get(pFolder), LinkOption.NOFOLLOW_LINKS)) {
        FileWriter outFile = null;
        try {
            FileUtils.deleteQuietly(new File(pFolder + "/" + pDoc.getName() + ".json"));
            outFile = new FileWriter(pFolder + "/" + pDoc.getName() + ".json");
            boolean first = true;
            try (PrintWriter out = new PrintWriter(outFile)) {
                Gson son = new GsonBuilder().setPrettyPrinting().create();
                out.print(son.toJson(msg));
            }
        } catch (IOException ex) {
            logger.warn("couldn't save the document results in json format", ex);
        } finally {
            try {
                if (outFile != null) {
                    outFile.close();
                }
            } catch (IOException ex) {
                logger.warn("Error while closing the file", ex);
            }
        }
        logger.info(pDoc.path + "  Saved... ");
    } else if (Files.exists(Paths.get(pFolder), LinkOption.NOFOLLOW_LINKS)) {
        logger.error("The folder exists but it isn't a directory...maybe a file?");
    } else {
        logger.warn("The directory doesn't exist... will be created");
        FileWriter outFile = null;
        try {
            FileUtils.forceMkdir(new File(pFolder));
            FileUtils.deleteQuietly(new File(pFolder + "/" + pDoc.getName() + ".json"));
            outFile = new FileWriter(pFolder + "/" + pDoc.getName() + ".json");
            boolean first = true;
            try (PrintWriter out = new PrintWriter(outFile)) {
                Gson son = new GsonBuilder().setPrettyPrinting().create();
                out.print(son.toJson(pDoc));
            }
        } catch (IOException ex) {
            logger.warn("couldn't save the document results in json format", ex);
        } finally {
            try {
                if (outFile != null) {
                    outFile.close();
                }
            } catch (IOException ex) {
                logger.warn("Error while closing the file", ex);
            }
        }
        logger.info(pDoc.path + "  Saved... ");

    }

}

From source file:de.document.umls.RetrieveCui.java

public Umls RetCui(String id) {

    //if you omit the -Dversion parameter, use 'current' as the default.
    version = System.getProperty("version") == null ? "current" : System.getProperty("version");
    String path = "/rest/content/" + version + "/CUI/" + id;
    RestAssured.baseURI = "https://uts-ws.nlm.nih.gov";
    Response response = given()//.log().all()
            .request().with().param("ticket", ticketClient.getST(tgt)).expect().statusCode(200).when()
            .get(path);/*w  w  w  . j  ava  2s  . c om*/
    //response.then().log().all();;     
    String output = response.getBody().asString();

    Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build();
    ConceptLite conceptLite = JsonPath.using(config).parse(output).read("$.result", ConceptLite.class);

    System.out.println(conceptLite.getUi() + ": " + conceptLite.getName());
    //System.out.println("Semantic Type(s): "+ join(conceptLite.getSemanticTypes(),","));
    System.out.println("Number of Atoms: " + conceptLite.getAtomCount());
    System.out.println("Atoms: " + conceptLite.getAtoms());
    System.out.println("Relations: " + conceptLite.getRelations());
    //System.out.println("Highest Ranking Atom: "+conceptLite.getDefaultPreferredAtom());
    System.out.println("Definitions: " + conceptLite.getDefinitions());
    //System.out.println(ticketClient.getST(tgt));
    //ST-115269-Mvb5oLFpIgQElKaKWVsN-cas
    String s = conceptLite.getDefinitions();
    if (s.charAt(0) != 'N' && s.charAt(1) != 'O' && s.charAt(2) != 'N' && s.charAt(3) != 'E') {

        String path2 = "/rest/content/" + version + "/CUI/" + id + "/definitions?ticket="
                + ticketClient.getST(tgt);
        RestAssured.baseURI = "https://uts-ws.nlm.nih.gov";
        Response response2 = given().log().all().request().with().param("ticket", ticketClient.getST(tgt))
                .expect().statusCode(200).when().get(path2);
        //response.then().log().all();;     
        String output2 = response2.getBody().asString();

        // System.out.println(output2);
        //extract the definition 
        System.out.println(output2.substring(output2.indexOf("value") + 8, output2.indexOf(".\"}")));
        String def = output2.substring(output2.indexOf("value") + 8, output2.indexOf("\"}"));

        HashMap hm = conceptLite.getSemanticTypes().get(0);
        Set set = hm.entrySet();
        // Get an iterator
        Iterator i = set.iterator();
        // Display elements

        Map.Entry me = (Map.Entry) i.next();
        System.out.print(me.getKey() + ": ");
        System.out.println(me.getValue());

        // def =def + "\r\n"+"Semantic Type"+me.getKey() + ": "+me.getValue()+"\r\n"+"Number of Atoms: " + conceptLite.getAtomCount();

        Umls u = new Umls();
        //u.setNumberOfAtom(conceptLite.getAtomCount());
        u.setUi(id);
        u.setDefinition(def);
        u.setNumberOfAtom(conceptLite.getAtomCount());

        u.setSemanticType(me.getValue().toString());

        return u;
    } else {
        Umls u = new Umls();
        //u.setNumberOfAtom(conceptLite.getAtomCount());
        u.setUi("");
        u.setName("");
        u.setDefinition("There is no available definition");
        return u;

    }
}

From source file:hudson.plugins.memegen.MemegeneratorResponseException.java

protected URL buildURL(String action, HashMap<String, String> map) throws MalformedURLException, IOException {

    String getVars = "";
    Set s = map.entrySet();
    Iterator i = s.iterator();/*from ww w.  j  a va2  s.  c om*/
    while (i.hasNext()) {
        Map.Entry var = (Map.Entry) i.next();
        getVars += URLEncoder.encode((String) var.getKey(), "UTF-8") + "="
                + URLEncoder.encode((String) var.getValue(), "UTF-8") + "&";
    }
    URL url = new URL(APIURL + "/" + action + "?" + getVars);
    return url;
}

From source file:org.clothocad.phagebook.controllers.ProjectController.java

static Map<String, Object> editProjectHelper(Project project, HashMap params, Clotho clothoObject) {

    // params is the hashmap of new values
    System.out.println("In Edit Project function");

    Iterator entries = params.entrySet().iterator();
    // result hashmap would let the user know whether there have
    // been unedited values.
    Map result = new HashMap();

    while (entries.hasNext()) {
        // reset the value if it is diff from the one in the project object
        Map.Entry entry = (Map.Entry) entries.next();
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        System.out.println("Key = " + key + ", Value = " + value);

        String[] keyValue = new String[4];
        keyValue[0] = key; // type of new value (like "description")
        keyValue[1] = value; // the actual new value (like "This is a new desciption")

        if (key.equals("editorId")) {
            Person editor = ClothoAdapter.getPerson(value, clothoObject);
            System.out.println();
        }/*from  w  w  w .  jav  a  2s. co  m*/
        if (key.equals("description")) {
            keyValue[2] = "description";
            keyValue[3] = project.getDescription();
            //helperMsg(project.getDescription(), value);
            if (value != "") {
                project.setDescription(value);
                result.put("desc", 1);
            } else {
                result.put("desc", 0);
            }

        }
        if (key.equals("name")) {
            keyValue[2] = "name";
            keyValue[3] = project.getName();
            //helperMsg(project.getName(), value);
            if (value != "") {
                project.setName(value);
                result.put("name", 1);
            } else {
                result.put("name", 0);
            }

        }
        if (key.equals("leadId")) {
            //helperMsg(project.getLeadId(), value);
            System.out.println("Can't edit lead yet, sorry!");
            // TODO: add lead editing capabilities
        }
        if (key.equals("budget")) {
            keyValue[2] = "budget";
            keyValue[3] = project.getBudget().toString();
            //helperMsg(Double.toString(project.getBudget()), value);
            if (value != "") {
                project.setBudget(Double.parseDouble(value));
                result.put("budget", 1);
            } else {
                result.put("budget", 0);
            }
        }
        if (key.equals("projectGrant")) {
            if (value != "") {
                String oldGrantId = project.getGrantId();
                Grant newGrant = new Grant(value);
                String newGrantId = ClothoAdapter.createGrant(newGrant, clothoObject);
                keyValue[2] = "projectGrant";
                keyValue[3] = oldGrantId;

                project.setGrantId(newGrantId);
                result.put("grant", 1);
            } else {
                result.put("grant", 0);
            }
        }
    }
    String projectID = project.getId();
    System.out.println("in Edit Project Function Project ID is");
    System.out.println(projectID);
    System.out.println(clothoObject);
    String foo = ClothoAdapter.setProject(project, clothoObject);
    System.out.println(foo);

    // FOR TESTING -- prints the result hashmap    
    //      Iterator iterator = result.keySet().iterator();
    //      while (iterator.hasNext()) {
    //         String key = iterator.next().toString();
    //         Integer value = (Integer)result.get(key);
    //
    //         System.out.println(key + " " + value);
    //      }
    //
    if (projectID.length() > 0) {
        result.put("success", 1);
        return result;
    } else {
        result.put("success", 0);
        return result;
    }
    //sendEmails(request);
}

From source file:EJBs.Operations.java

public String cartCheckout(String username, HashMap<Products, Integer> cart, double total) {
    try {/* w w w .j a  v  a2 s.co m*/
        for (Map.Entry<Products, Integer> entry : cart.entrySet()) {
            System.out.println(entry.getKey() + "/" + entry.getValue());
            Products product = em.find(Products.class, entry.getKey().getName());
            product.setStock(product.getStock() - cart.get(product));
            em.persist(product);
        }
        byte[] cartData = SerializationUtils.serialize(cart);
        Orders newOrd = new Orders(username, cartData, total);
        em.persist(newOrd);
        String oid = "" + em.createQuery("SELECT max(o.id) FROM Orders o where o.username=:username")
                .setParameter("username", username).getSingleResult();
        return oid;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return "";
    }
}

From source file:ANNFileDetect.GraphingClass.java

public JFreeChart chartOutcome(HashMap hm) {
    JFreeChart jf = null;//from  ww  w  .  j a  v  a  2  s. co  m
    DefaultCategoryDataset dc = new DefaultCategoryDataset();
    String xax = "File Type";
    Iterator it = hm.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        dc.addValue((Double) pair.getValue(), xax, pair.getKey().toString());
    }
    jf = ChartFactory.createBarChart3D("File detection results", "File type", "Score", (CategoryDataset) dc,
            PlotOrientation.VERTICAL, true, true, true);
    return jf;
}

From source file:org.archone.ad.schema.DisplayAttributeHelper.java

public HashMap<String, Object> apiToLdapAttrNames(HashMap<String, Object> attrMap) {
    HashMap<String, Object> ldapAttrMap = new HashMap<String, Object>();
    for (Entry<String, Object> entry : attrMap.entrySet()) {
        if (this.apiNameIndex.get(entry.getKey()) != null) {
            ldapAttrMap.put((String) this.apiNameIndex.get(entry.getKey()).getLdapName(), entry.getValue());
        }// w  w  w .j a  va2  s  .  c o m
    }

    return ldapAttrMap;
}

From source file:com.baidu.qa.service.test.verify.VerifyResponseImpl.java

public void verifyResponseWithExpectString(File expectfile, String actual) {

    FileCharsetDetector det = new FileCharsetDetector();
    String expectedStr = FileUtil.readFileByLines(expectfile);
    try {/*ww w . ja va 2 s . c  o  m*/
        String oldcharset = det.guestFileEncoding(expectfile);
        if (oldcharset.equalsIgnoreCase("UTF-8") == false)
            FileUtil.transferFile(expectfile, oldcharset, "UTF-8");
    } catch (Exception ex) {
        log.error("[change expect file charset error]:" + ex);
    }

    //???json??actual.contain(expect)
    if (!BJSON.BooleanJudgeStringJson(actual) || !BJSON.BooleanJudgeStringJson(expectedStr)) {

        List<String> datalist = FileUtil.getListFromFileWithBOMFilter(expectfile);
        for (String data : datalist) {
            log.info("[expected string]:" + data);
            Assert.assertTrue("[response different with expect][expect]:" + data.trim() + "[actual]:" + actual,
                    actual.contains(data.trim()));
        }
    }
    //json????
    else {

        BJSON service = new BJSON();
        HashMap<String, String> diffHash = service.findDiffSingleInJson(actual, expectedStr);
        if (diffHash.size() != 0) {
            for (Entry<String, String> it : diffHash.entrySet()) {
                log.error(it.getKey() + "----" + it.getValue());
            }
            Assert.assertEquals(0, diffHash.size());
        }
    }
}