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.jaredrummler.android.devices.Main.java

private static void createManufacturerJsonFiles(List<String[]> devices) throws IOException {
    File baseDir = new File(OUTPUT_DIR, "manufacturer");
    if (baseDir.exists()) {
        FileUtils.deleteDirectory(baseDir);
    }//from   w  ww  . ja  v a  2s  . com
    baseDir.mkdirs();

    // group all devices with the same codename together
    HashMap<String, List<DeviceInfo>> map = new HashMap<>();
    for (String[] arr : devices) {
        String key = arr[0];
        if (key == null || key.trim().length() == 0) {
            continue;
        }
        List<DeviceInfo> list = map.get(key);
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(new DeviceInfo(null, arr[1], arr[2], arr[3]));
        map.put(key, list);
    }

    for (Map.Entry<String, List<DeviceInfo>> entry : map.entrySet()) {
        String key = entry.getKey();
        File file = new File(baseDir, key + ".json");
        Manufacturer manufacturer = new Manufacturer(key, entry.getValue());
        FileUtils.write(file, PRETTY_GSON.toJson(manufacturer));
    }
}

From source file:com.gmail.frogocomics.schematic.BiomeWorldV2Object.java

public static BiomeWorldV2Object load(File file) throws IOException {

    BufferedReader settingsReader;

    if (!file.exists()) {
        throw new FileNotFoundException();
    }// www .j av  a 2 s. com
    settingsReader = new BufferedReader(new FileReader(file));
    int lineNumber = 0;
    String thisLine;
    ArrayList<BiomeWorldObjectBlock> bo2Blocks = new ArrayList<>();

    while ((thisLine = settingsReader.readLine()) != null) {
        lineNumber++;
        if (Pattern.compile("[0-9]").matcher(thisLine.substring(0, 1)).matches()
                || thisLine.substring(0, 1).equalsIgnoreCase("-")) {
            //Example: -1,-1,5:18.4
            // x,z,y:id.data
            String[] location = thisLine.split(":")[0].split(",");
            String[] block = thisLine.split(":")[1].split("\\.");
            bo2Blocks.add(new BiomeWorldObjectBlock(Integer.parseInt(location[0]),
                    Integer.parseInt(location[2]), Integer.parseInt(location[1]), Short.parseShort(block[0]),
                    Byte.parseByte(block[1])));
        }
    }

    ArrayList<Integer> maxXMap = new ArrayList<>();
    ArrayList<Integer> maxYMap = new ArrayList<>();
    ArrayList<Integer> maxZMap = new ArrayList<>();
    for (BiomeWorldObjectBlock bo2 : bo2Blocks) {
        maxXMap.add(bo2.getX());
        maxYMap.add(bo2.getY());
        maxZMap.add(bo2.getZ());
    }

    int maxX = Collections.max(maxXMap);
    int maxY = Collections.max(maxYMap);
    int maxZ = Collections.max(maxZMap);
    int minX = Collections.min(maxXMap);
    int minY = Collections.min(maxYMap);
    int minZ = Collections.min(maxZMap);
    int differenceX = maxX - minX + 1;
    int differenceY = maxY - minY + 1;
    int differenceZ = maxZ - minZ + 1;

    HashMap<Integer, Set<BiomeWorldObjectBlock>> blocks = new HashMap<>();
    for (int i = 0; i < differenceY + 1; i++) {
        blocks.put(i, new HashSet<>());
    }

    for (BiomeWorldObjectBlock bo2 : bo2Blocks) {
        Set<BiomeWorldObjectBlock> a = blocks.get(bo2.getY() - minY);
        a.add(bo2);
        blocks.replace(bo2.getY(), a);
    }

    //System.out.println(differenceX + " " + differenceZ);
    SliceStack schematic = new SliceStack(differenceY, differenceX, differenceZ);

    for (Map.Entry<Integer, Set<BiomeWorldObjectBlock>> next : blocks.entrySet()) {
        Slice slice = new Slice(differenceX, differenceZ);
        for (BiomeWorldObjectBlock block : next.getValue()) {
            //System.out.println("Added block at " + String.valueOf(block.getX() - minX) + "," + String.valueOf(block.getZ() - minZ));
            slice.setBlock(block.getBlock(), block.getX() - minX, block.getZ() - minZ);
        }
        schematic.addSlice(slice);
    }
    //System.out.println(schematic.toString());

    return new BiomeWorldV2Object(schematic, FilenameUtils.getBaseName(file.getAbsolutePath()));
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);/*from w ww  . j  av  a2s .  co m*/
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.OptimizationWrapper.java

/**
 * Called once per DML script (during program compile time) 
 * in order to optimize all top-level parfor program blocks.
 * /*from   ww w  .j  a v  a 2 s . c o m*/
 * NOTE: currently note used at all.
 * 
 * @param prog
 * @param rtprog
 * @throws DMLRuntimeException 
 * @throws LanguageException 
 * @throws DMLUnsupportedOperationException 
 */
public static void optimize(DMLProgram prog, Program rtprog, boolean monitor)
        throws DMLRuntimeException, LanguageException, DMLUnsupportedOperationException {
    LOG.debug("ParFOR Opt: Running optimize all on DML program " + DMLScript.getUUID());

    //init internal structures 
    HashMap<Long, ParForStatementBlock> sbs = new HashMap<Long, ParForStatementBlock>();
    HashMap<Long, ParForProgramBlock> pbs = new HashMap<Long, ParForProgramBlock>();

    //find all top-level paror pbs
    findParForProgramBlocks(prog, rtprog, sbs, pbs);

    // Create an empty symbol table
    ExecutionContext ec = ExecutionContextFactory.createContext();

    //optimize each top-level parfor pb independently
    for (Entry<Long, ParForProgramBlock> entry : pbs.entrySet()) {
        long key = entry.getKey();
        ParForStatementBlock sb = sbs.get(key);
        ParForProgramBlock pb = entry.getValue();

        //optimize (and implicit exchange)
        POptMode type = pb.getOptimizationMode(); //known to be >0
        optimize(type, sb, pb, ec, monitor);
    }

    LOG.debug("ParFOR Opt: Finished optimization for DML program " + DMLScript.getUUID());
}

From source file:applab.search.client.ImageManager.java

public static void updateLocalImages() {
    // Get remote list
    InputStream xmlStream = getImageXml();

    // Get local list
    HashMap<String, File> localImageList = getLocalImageList();

    // Init Sax Parser & XML Handler
    SAXParser xmlParser;/*from   ww  w . j a  va  2s. c o m*/
    ImageXmlParseHandler xmlHandler = new ImageXmlParseHandler();
    xmlHandler.setLocalImageList(localImageList);

    if (xmlStream == null) {
        return;
    }
    try {
        if (xmlStream != null) {
            xmlParser = SAXParserFactory.newInstance().newSAXParser();

            // This line was causing problems on android 2.2 (IDEOS)
            // xmlParser.reset();

            xmlParser.parse(xmlStream, xmlHandler);

            // Delete local files not on remote list
            for (Entry<String, File> localImage : localImageList.entrySet()) {
                File file = localImage.getValue();
                String sha1Hash = localImage.getKey();
                // Confirm this is the file we intend to delete (a new file with the same name may have been downloaded)
                if (ImageFilesUtility.getSHA1Hash(file).equalsIgnoreCase(sha1Hash)) {
                    ImageFilesUtility.deleteFile(file);
                }
            }
        }
    } catch (SAXException e) {
        Log.e("ImageManager", "Error while parsing XML: " + e);
    } catch (IOException e) {
        Log.e("ImageManager", "Error while parsing XML: " + e);
    } catch (ParserConfigurationException e) {
        Log.e("ImageManager", "Error while parsing XML: " + e);
    }
}

From source file:com.savy3.nonequijoin.MapOutputSampler.java

/**
 * Write a partition file for the given job, using the Sampler provided.
 * Queries the sampler for a sample keyset, sorts by the output key
 * comparator, selects the keys for each rank, and writes to the destination
 * returned from {@link TotalOrderPartitioner#getPartitionFile}.
 *///ww  w.  j a v  a  2s  .com

@SuppressWarnings("unchecked")
// getInputFormat, getOutputKeyComparator
public static <K, V> void writePartitionFile(Job job, Sampler<K, V> sampler)
        throws IOException, ClassNotFoundException, InterruptedException {
    Configuration conf = job.getConfiguration();
    final InputFormat inf = ReflectionUtils.newInstance(job.getInputFormatClass(), conf);
    int numPartitions = job.getNumReduceTasks();
    HashMap<K, V> samples = (HashMap<K, V>) sampler.getSample(inf, job);
    LOG.info("Using " + samples.size() + " samples");

    // write the input samples in to file <partitionfile>/mapIn
    Path dstOut = new Path(TotalOrderPartitioner.getPartitionFile(conf));

    Path dst = new Path(dstOut, "mapIn");
    FileSystem fs = dst.getFileSystem(conf);
    SequenceFile.Writer sampleWriter = null;
    for (Map.Entry<K, V> sample : samples.entrySet()) {
        sampleWriter = SequenceFile.createWriter(fs, conf, dst, sample.getKey().getClass(),
                sample.getValue().getClass());
        break;
    }
    for (Map.Entry<K, V> sample : samples.entrySet()) {
        sampleWriter.append(sample.getKey(), sample.getValue());
    }
    sampleWriter.close();
    LOG.info("Sample Input File location " + dst.toString());
    // run map reduce on the samples input
    runMap(job, dst);
}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Get RSA PublicKey by PublicKey HashMap input. Create a dialog popup with a combobox to choose the correct JWK to use.
 * /*from  w  w w  . j a va2  s  . c  o  m*/
 * @param publicKeys
 *            HashMap containing a PublicKey and related describing string
 * @throws AttackPreparationFailedException
 * @return Selected {@link PublicKey}
 */
@SuppressWarnings("unchecked")
public static PublicKey getRsaPublicKeyByJwkSelectionPanel(HashMap<String, PublicKey> publicKeys)
        throws AttackPreparationFailedException {
    // TODO: Move to other class?
    JPanel selectionPanel = new JPanel();
    selectionPanel.setLayout(new java.awt.GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;

    constraints.gridy = 0;
    selectionPanel.add(new JLabel("Multiple JWKs found. Please choose one:"), constraints);

    JComboBox jwkSetKeySelection = new JComboBox<>();
    DefaultComboBoxModel<String> jwkSetKeySelectionModel = new DefaultComboBoxModel<>();

    for (Map.Entry<String, PublicKey> publicKey : publicKeys.entrySet()) {
        jwkSetKeySelectionModel.addElement(publicKey.getKey());
    }

    jwkSetKeySelection.setModel(jwkSetKeySelectionModel);

    constraints.gridy = 1;
    selectionPanel.add(jwkSetKeySelection, constraints);

    int resultButton = JOptionPane.showConfirmDialog(null, selectionPanel, "Select JWK",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

    if (resultButton == JOptionPane.CANCEL_OPTION) {
        throw new AttackPreparationFailedException("No JWK from JWK Set selected!");
    }

    loggerInstance.log(Converter.class, "Key selected: " + jwkSetKeySelection.getSelectedIndex(),
            Logger.LogLevel.DEBUG);
    return publicKeys.get(jwkSetKeySelection.getSelectedItem());
}

From source file:gov.llnl.lc.smt.command.route.SmtRoute.java

public static String getRouteTableDump(OpenSmMonitorService oms, RT_Table table) {
    StringBuffer buff = new StringBuffer();

    if ((oms != null) && (table != null)) {
        // iterate through the switches, and dump their port routes
        HashMap<String, RT_Node> NodeRouteMap = table.getSwitchGuidMap();

        if (NodeRouteMap != null) {
            for (Map.Entry<String, RT_Node> entry : NodeRouteMap.entrySet()) {
                RT_Node rn = entry.getValue();
                buff.append(SmtPort.getPortRoutes(table, oms, rn.getGuid(), (short) 0));
            }/*from   ww  w  .j  a v  a  2s .c  om*/
        }
    } else
        System.err.println("Unable to show routing table for null objects");

    return buff.toString();
}

From source file:com.viettel.util.StringUtils.java

public static void buidQuery(String name, HashMap<String, Object> searchParams, StringBuilder strQuery,
         Map<String, Object> params, String... prefix) {
     ArrayList<String> arrQuery = new ArrayList<String>();
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
     HashMap<String, Object> searchParamsCopy = new HashMap<>(searchParams);
     for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
         String key = entry.getKey();
         Object value = entry.getValue();
         if (value == null || value.toString().equals("")) {
             searchParamsCopy.remove(key);
         }// w  w w .  j  av  a  2s.c  o m
     }
     String pref = prefix != null && prefix.length > 0 ? prefix[0] + "." : "";
     for (Map.Entry<String, Object> entry : searchParamsCopy.entrySet()) {
         String key = entry.getKey();

         Object value = entry.getValue();
         /*
          * if (value == null || value.toString().equals("") || (value
          * instanceof Long && 0 >= (int) value)) { continue; }
          */
         if (arrQuery.size() > 0) {
             arrQuery.add(" AND  ");
         }
         if (value instanceof Date || DateUtil.isValidDateWithFormat(value.toString(), "yyyy-MM-dd")) {
             try {
                 if (key.startsWith("from")) {
                     String cl = key.replace("from", "");
                     if (searchParamsCopy.containsKey("to" + cl)) {
                         arrQuery.add(String.format("%1$s BETWEEN :%2$s", pref + cl, key));
                         params.put(key, formatter.parse(value.toString()));

                         Object objTo = searchParamsCopy.get("to" + cl);
                         if (objTo != null) {
                             arrQuery.add(String.format(" AND :%s", "to" + cl));
                             params.put("to" + cl, formatter.parse(objTo.toString()));
                         }
                     } else {
                         arrQuery.add(String.format("%1$s >= :%2$s", pref + cl, key));
                         params.put(key, formatter.parse(value.toString()));
                     }
                 } else if (key.startsWith("to")) {
                     String cl = key.replace("to", "");
                     if (!searchParamsCopy.containsKey("from" + cl)) {
                         arrQuery.add(String.format("%1$s <= :%2$s", pref + cl, key));
                         params.put(key, formatter.parse(value.toString()));
                     } else {
                         if (arrQuery.size() > 0) {
                             arrQuery.remove(arrQuery.size() - 1);
                         }
                     }
                 } else {
                     arrQuery.add(String.format("DATE(%1$s) = DATE(:%2$s)", pref + key, key));
                     params.put(key, value + "%");
                 }
             } catch (ParseException ex) {

             }
         } else if (value instanceof Number) {
             if (key.startsWith("and_")) {
                 if (searchParamsCopy.containsKey(key.replace("and_", ""))) {
                     if (!CollectionUtils.isEmpty(arrQuery)) {
                         arrQuery.remove(arrQuery.size() - 1);
                     }
                 }
             } else if (searchParamsCopy.containsKey("and_" + key)) {
                 arrQuery.add(String.format("(%1$s = :%2$s", pref + key, key));
                 if (value instanceof Integer) {
                     params.put(key, Integer.parseInt(value.toString()));
                 } else if (value instanceof Long) {
                     params.put(key, Long.parseLong(value.toString()));
                 } else if (value instanceof Float) {
                     params.put(key, Float.parseFloat(value.toString()));
                 } else if (value instanceof Double) {
                     params.put(key, Double.parseDouble(value.toString()));
                 }

                 Object obj = searchParamsCopy.get("and_" + key);
                 if (obj != null) {
                     arrQuery.add(String.format(" OR %1$s = :%2$s)", pref + key, "and_" + key));
                     if (value instanceof Integer) {
                         params.put("and_" + key, Integer.parseInt(obj.toString()));
                     } else if (value instanceof Long) {
                         params.put("and_" + key, Long.parseLong(obj.toString()));
                     } else if (value instanceof Float) {
                         params.put("and_" + key, Float.parseFloat(obj.toString()));
                     } else if (value instanceof Double) {
                         params.put("and_" + key, Double.parseDouble(obj.toString()));
                     }
                 }
             } else {
                 arrQuery.add(String.format("%1$s = :%2$s", pref + key, key));
                 if (value instanceof Integer) {
                     params.put(key, Integer.parseInt(value.toString()));
                 } else if (value instanceof Long) {
                     params.put(key, Long.parseLong(value.toString()));
                 } else if (value instanceof Float) {
                     params.put(key, Float.parseFloat(value.toString()));
                 } else if (value instanceof Double) {
                     params.put(key, Double.parseDouble(value.toString()));
                 }
             }
         } else if (value instanceof String) {
             if (key.startsWith("and_")) {
                 if (searchParamsCopy.containsKey(key.replace("and_", ""))) {
                     if (arrQuery.size() > 0) {
                         arrQuery.remove(arrQuery.size() - 1);
                     }
                 }
             } else if (searchParamsCopy.containsKey("and_" + key)) {
                 arrQuery.add(String.format("(LOWER(%1$s) like LOWER(:%2$s)", pref + key, key));
                 params.put(key, "%" + value + "%");

                 Object obj = searchParamsCopy.get("and_" + key);
                 if (obj != null) {
                     arrQuery.add(String.format(" OR LOWER(%1$s) LIKE LOWER(:%2$s))", pref + key, "and_" + key));
                     params.put("and_" + key, "%" + obj + "%");
                 }
             } else if (key.startsWith("in_cond_")) {
                 String cl = key.replace("in_cond_", "");
                 arrQuery.add(String.format("%1$s IN (%2$s)", pref + cl, value.toString()));
                 params.remove(key);
             } else if (key.startsWith("not_in_cond_")) {
                 String cl = key.replace("not_in_cond_", "");
                 arrQuery.add(String.format("%1$s NOT IN (%2$s)", pref + cl, value.toString()));
                 params.remove(key);
             } else {
                 arrQuery.add(String.format("LOWER(%1$s) LIKE LOWER(:%2$s)", pref + key, key));
                 params.put(key, "%" + value + "%");
             }
         }
     }
     strQuery.append(String.join("", arrQuery));
 }

From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * ???/*w  ww  .  j a  va  2  s  .com*/
 */
public static ArrayList<String> getValidAgent() {
    try {
        _agentCacheLock.writeLock();

        HashMap<String, AgentInfo> agentMap = getAgentCache();
        Set<AgentInfo> removedSet = new HashSet<AgentInfo>();
        for (Entry<String, AgentInfo> entry : new HashSet<Entry<String, AgentInfo>>(agentMap.entrySet())) {
            if (!entry.getValue().isValid()) {
                removedSet.add(agentMap.remove(entry.getKey()));
                m_log.info("remove " + entry.getValue());
            }
        }
        if (removedSet.size() > 0) {
            storeAgentCache(agentMap);
        }
    } finally {
        _agentCacheLock.writeUnlock();
    }

    try {
        _agentCacheLock.readLock();

        Map<String, AgentInfo> agentMap = getAgentCache();

        ArrayList<String> list = new ArrayList<String>();
        for (String fid : agentMap.keySet()) {
            list.add(fid);
        }

        return list;
    } finally {
        _agentCacheLock.readUnlock();
    }
}