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.clustercontrol.infra.composite.InfraModuleComposite.java

private HashMap<String, String> getStatusString(String managerName, String managementId) {
    HashMap<String, String> ret = new HashMap<>();
    List<InfraCheckResult> resultList = null;
    try {/*from w  w  w . j  a  va 2s  .  com*/
        InfraEndpointWrapper wrapper = InfraEndpointWrapper.getWrapper(managerName);
        resultList = wrapper.getCheckResultList(managementId);
    } catch (HinemosUnknown_Exception | InvalidRole_Exception | InvalidUserPass_Exception e) {
        m_log.error("getStatusString() getCheckResultList, " + e.getMessage());
    }
    if (resultList == null) {
        return ret;
    }

    HashMap<String, List<InfraCheckResult>> checkResultMap = new HashMap<>();
    for (InfraCheckResult result : resultList) {
        String moduleId = result.getModuleId();
        List<InfraCheckResult> list = checkResultMap.get(moduleId);
        if (list == null) {
            list = new ArrayList<InfraCheckResult>();
            checkResultMap.put(moduleId, list);
        }
        m_log.debug("moduleId=" + moduleId + ", facilityId=" + result.getNodeId() + ", " + result.getResult());
        list.add(result);
    }
    for (Entry<String, List<InfraCheckResult>> resultEntry : checkResultMap.entrySet()) {
        List<InfraCheckResult> list = resultEntry.getValue();
        List<String> okList = new ArrayList<>();
        List<String> ngList = new ArrayList<>();
        for (InfraCheckResult result : list) {
            if (result.getResult() == OkNgConstant.TYPE_OK) {
                okList.add(result.getNodeId());
            } else if (result.getResult() == OkNgConstant.TYPE_NG) {
                ngList.add(result.getNodeId());
            } else {
                m_log.warn("getStatusString : " + result.getNodeId() + ", " + result.getResult()); // ??????????
            }
        }
        Collections.sort(okList);
        Collections.sort(ngList);
        StringBuilder message = new StringBuilder();
        StringBuilder str = new StringBuilder();
        for (String ng : ngList) {
            if (str.length() > 0) {
                str.append(", ");
            }
            str.append(ng);
        }
        message.append("NG(" + str + "), \n");
        str = new StringBuilder();
        for (String ok : okList) {
            if (str.length() > 0) {
                str.append(", ");
            }
            str.append(ok);
        }
        message.append("OK(" + str + ")");

        int maxMessage = 1024;
        if (message.length() > maxMessage) {
            message.substring(1, maxMessage);
            message.append("...");
        }
        ret.put(resultEntry.getKey(), message.toString());
    }

    return ret;
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.lookupproperty.ELTLookupMapWizard.java

private List<String> getListOfNonMappedFields(HashMap<String, List<String>> inputFieldMap) {
    Iterator iterator = inputFieldMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry portFieldPair = (Map.Entry) iterator.next();
        for (LookupMapProperty lookupMapProperty : joinOutputList) {
            String port = "";
            if (lookupMapProperty.getSource_Field().length() >= 3) {
                port = lookupMapProperty.getSource_Field().substring(0, 3);
            }/*from w  ww.  j  a  va  2s  .co m*/
            String source_field = lookupMapProperty.getSource_Field()
                    .substring(lookupMapProperty.getSource_Field().lastIndexOf(".") + 1);
            if (portFieldPair.getKey().equals(port)) {
                List<String> value = (ArrayList<String>) portFieldPair.getValue();
                if (!value.isEmpty() && !checkIfSourceFieldExists(value, source_field)) {
                    sourceFieldList.add(port + "." + source_field);
                }
            } else {
                sourceFieldList.add(source_field);
            }
            if (port.equalsIgnoreCase("")) {
                sourceFieldList.add(source_field);
            }
        }
    }
    return sourceFieldList;
}

From source file:Forms.SalesChart.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    DefaultPieDataset pieDataset = new DefaultPieDataset();

    String conString = "jdbc:mysql://localhost:3306/nafis";
    String username = "root";
    String passward = "";

    String sql = "SELECT * FROM sold";

    try {/* w  w w  .  ja  v a 2 s.c  om*/
        Connection con = (Connection) DriverManager.getConnection(conString, username, passward);

        Statement s = (Statement) con.prepareStatement(sql);

        ResultSet rs = s.executeQuery(sql);

        HashMap<String, Integer> map = new HashMap<String, Integer>();

        while (rs.next()) {

            String name = rs.getString(2);

            String stock = rs.getString(3);
            String type = rs.getString(8);

            Integer oldVal = map.get(type);

            //System.out.println(oldVal);

            if (oldVal == null) {
                map.put(type, Integer.parseInt(stock));
            } else {
                map.put(type, oldVal + Integer.parseInt(stock));
            }

        }

        for (HashMap.Entry m : map.entrySet()) {
            //System.out.println(m.getKey()+" "+m.getValue());  
            pieDataset.setValue(m.getKey() + "", Integer.parseInt(m.getValue() + ""));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    JFreeChart chart = ChartFactory.createPieChart3D("pie chart", pieDataset, true, true, false);
    PiePlot3D p = (PiePlot3D) chart.getPlot();
    p.setStartAngle(0);
    p.setDirection(Rotation.CLOCKWISE);
    p.setForegroundAlpha(0.5f);
    p.getBackgroundPaint();

    ChartFrame frame = new ChartFrame("Pie Chart", chart);
    frame.setLocationByPlatform(true);

    frame.setVisible(true);
    frame.setSize(750, 600);
}

From source file:net.sf.taverna.t2.activities.soaplab.SoaplabActivity.java

@Override
public void executeAsynch(final Map<String, T2Reference> data, final AsynchronousActivityCallback callback) {
    callback.requestRun(new Runnable() {

        @SuppressWarnings("unchecked")
        public void run() {
            ReferenceService referenceService = callback.getContext().getReferenceService();

            Map<String, T2Reference> outputData = new HashMap<String, T2Reference>();

            try {
                // Copy the contents of the data set in the input map
                // to a new Map object which just contains the raw data
                // objects
                Map<String, Object> soaplabInputMap = new HashMap<String, Object>();
                for (Map.Entry<String, T2Reference> entry : data.entrySet()) {
                    Class<?> inputType = getInputType(entry.getKey());
                    logger.info("Resolving " + entry.getKey() + " to " + inputType);
                    soaplabInputMap.put(entry.getKey(), referenceService.renderIdentifier(entry.getValue(),
                            inputType, callback.getContext()));
                    logger.info("  Value = " + soaplabInputMap.get(entry.getKey()));
                }/*from  ww  w  .  j av a2s . c o m*/

                // Invoke the web service...
                Call call = (Call) new Service().createCall();
                call.setTimeout(new Integer(INVOCATION_TIMEOUT));
                // TODO is there endpoint stored in the configuration as a
                // String or a URL?
                // URL soaplabWSDLURL = new
                // URL(configurationBean.getEndpoint());
                call.setTargetEndpointAddress(json.get("endpoint").textValue());

                // Invoke the job and wait for it to complete
                call.setOperationName(new QName("createAndRun"));
                String jobID = (String) call.invoke(new Object[] { soaplabInputMap });
                // Get the array of desired outputs to avoid pulling
                // everything back
                // TODO Decide how to get the bound ports for the processor
                // OutputPort[] boundOutputs =
                // this.proc.getBoundOutputPorts();
                OutputPort[] boundOutputs = getOutputPorts().toArray(new OutputPort[0]);
                String[] outputPortNames = new String[boundOutputs.length];
                for (int i = 0; i < outputPortNames.length; i++) {
                    outputPortNames[i] = boundOutputs[i].getName();
                    logger.debug("Adding output : " + outputPortNames[i]);
                }

                if (!isPollingDefined()) {
                    // If we're not polling then use this behaviour
                    call.setOperationName(new QName("waitFor"));
                    call.invoke(new Object[] { jobID });
                } else {
                    // Wait for the polling interval then request a status
                    // and do this until the status is terminal.
                    boolean polling = true;
                    // Number of milliseconds to wait before the first
                    // status request.
                    int pollingInterval = json.get("pollingInterval").intValue();
                    while (polling) {
                        try {
                            Thread.sleep(pollingInterval);
                        } catch (InterruptedException ie) {
                            // do nothing
                        }
                        call.setOperationName(new QName("getStatus"));
                        String statusString = (String) call.invoke(new Object[] { jobID });
                        logger.info("Polling, status is : " + statusString);
                        if (statusString.equals("RUNNING") || statusString.equals("CREATED")) {
                            pollingInterval = (int) ((double) pollingInterval
                                    * json.get("pollingBackoff").doubleValue());
                            if (pollingInterval > json.get("pollingIntervalMax").intValue()) {
                                pollingInterval = json.get("pollingIntervalMax").intValue();
                            }
                        } else {
                            // Either completed with an error or success
                            polling = false;
                        }
                    }
                }

                // Get the status code
                call.setOperationName(new QName("getStatus"));
                String statusString = (String) call.invoke(new Object[] { jobID });
                if (statusString.equals("TERMINATED_BY_ERROR")) {
                    // Get the report
                    call.setOperationName(new QName("getSomeResults"));
                    HashMap<String, String> temp = new HashMap<String, String>(
                            (Map) call.invoke(new Object[] { jobID, new String[] { "report" } }));
                    String reportText = temp.get("report");
                    callback.fail("Soaplab call returned an error : " + reportText);
                    return;
                }

                // Get the results required by downstream processors
                call.setOperationName(new QName("getSomeResults"));
                HashMap<String, Object> outputMap = new HashMap<String, Object>(
                        (Map) call.invoke(new Object[] { jobID, outputPortNames }));

                // Tell soaplab that we don't need this session any more
                call.setOperationName(new QName("destroy"));
                call.invoke(new Object[] { jobID });

                // Build the map of DataThing objects
                for (Map.Entry<String, Object> entry : outputMap.entrySet()) {
                    String parameterName = entry.getKey();
                    Object outputObject = entry.getValue();
                    if (logger.isDebugEnabled())
                        logger.debug("Soaplab : parameter '" + parameterName + "' has type '"
                                + outputObject.getClass().getName() + "'");

                    if (outputObject instanceof String[]) {
                        // outputThing = DataThingFactory
                        // .bake((String[]) outputObject);
                        outputData.put(parameterName, referenceService.register(Arrays.asList(outputObject), 1,
                                true, callback.getContext()));
                    } else if (outputObject instanceof byte[][]) {
                        // Create a List of byte arrays, this will
                        // map to l('application/octet-stream') in
                        // the output document.
                        // outputThing = DataThingFactory
                        // .bake((byte[][]) outputObject);
                        List<byte[]> list = new ArrayList<byte[]>();
                        for (byte[] byteArray : (byte[][]) outputObject) {
                            list.add(byteArray);
                        }
                        outputData.put(parameterName,
                                referenceService.register(list, 1, true, callback.getContext()));
                        // outputData.put(parameterName, dataFacade
                        // .register(Arrays.asList(outputObject)));
                    } else if (outputObject instanceof List) {
                        List<?> convertedList = convertList((List<?>) outputObject);
                        outputData.put(parameterName,
                                referenceService.register(convertedList, 1, true, callback.getContext()));
                    } else {
                        // Fallthrough case, this mostly applies to
                        // output of type byte[] or string, both of which
                        // are handled perfectly sensibly by default.
                        outputData.put(parameterName,
                                referenceService.register(outputObject, 0, true, callback.getContext()));
                    }
                }

                // success
                callback.receiveResult(outputData, new int[0]);
            } catch (ReferenceServiceException e) {
                callback.fail("Error accessing soaplab input/output data", e);
            } catch (IOException e) {
                callback.fail("Failure calling soaplab", e);
            } catch (ServiceException e) {
                callback.fail("Failure calling soaplab", e);
            }
        }

    });

}

From source file:ca.uhn.fhir.jpa.term.TerminologyLoaderSvc.java

UploadStatistics processSnomedCtFiles(List<byte[]> theZipBytes, RequestDetails theRequestDetails) {
    final TermCodeSystemVersion codeSystemVersion = new TermCodeSystemVersion();
    final Map<String, TermConcept> id2concept = new HashMap<String, TermConcept>();
    final Map<String, TermConcept> code2concept = new HashMap<String, TermConcept>();
    final Set<String> validConceptIds = new HashSet<String>();

    IRecordHandler handler = new SctHandlerConcept(validConceptIds);
    iterateOverZipFile(theZipBytes, SCT_FILE_CONCEPT, handler, '\t', null);

    ourLog.info("Have {} valid concept IDs", validConceptIds.size());

    handler = new SctHandlerDescription(validConceptIds, code2concept, id2concept, codeSystemVersion);
    iterateOverZipFile(theZipBytes, SCT_FILE_DESCRIPTION, handler, '\t', null);

    ourLog.info("Got {} concepts, cloning map", code2concept.size());
    final HashMap<String, TermConcept> rootConcepts = new HashMap<String, TermConcept>(code2concept);

    handler = new SctHandlerRelationship(codeSystemVersion, rootConcepts, code2concept);
    iterateOverZipFile(theZipBytes, SCT_FILE_RELATIONSHIP, handler, '\t', null);

    theZipBytes.clear();//from  ww w. j a v a 2  s .c  o  m

    ourLog.info("Looking for root codes");
    for (Iterator<Entry<String, TermConcept>> iter = rootConcepts.entrySet().iterator(); iter.hasNext();) {
        if (iter.next().getValue().getParents().isEmpty() == false) {
            iter.remove();
        }
    }

    ourLog.info("Done loading SNOMED CT files - {} root codes, {} total codes", rootConcepts.size(),
            code2concept.size());

    Counter circularCounter = new Counter();
    for (TermConcept next : rootConcepts.values()) {
        long count = circularCounter.getThenAdd();
        float pct = ((float) count / rootConcepts.size()) * 100.0f;
        ourLog.info(" * Scanning for circular refs - have scanned {} / {} codes ({}%)", count,
                rootConcepts.size(), pct);
        dropCircularRefs(next, new ArrayList<String>(), code2concept, circularCounter);
    }

    codeSystemVersion.getConcepts().addAll(rootConcepts.values());
    String url = SCT_URL;
    storeCodeSystem(theRequestDetails, codeSystemVersion, url);

    return new UploadStatistics(code2concept.size());
}

From source file:org.sickbeard.SickBeard.java

public ArrayList<Show> shows() throws Exception {
    HashMap<String, ShowJson> result = this.commandData("shows",
            new TypeToken<JsonResponse<HashMap<String, ShowJson>>>() {
            }.getType());//from w  w  w  .j a v a  2s . com
    for (Map.Entry<String, ShowJson> entry : result.entrySet()) {
        entry.getValue().id = entry.getKey();
    }
    ArrayList<Show> ret = new ArrayList<Show>();
    for (ShowJson j : result.values()) {
        ret.add(new Show(j));
    }
    Collections.sort(ret, new Comparator<Show>() {
        public int compare(Show a, Show b) {
            return a.showName.compareTo(a.showName);
        }
    });
    return ret;
}

From source file:net.daw.control.upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w.j av a  2  s  .c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String name = "";
        String strMessage = "";
        HashMap<String, String> hash = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(".//..//webapps//images//" + name));
                    } else {
                        hash.put(item.getFieldName(), item.getString());
                    }
                }
                Gson oGson = new Gson();
                Map<String, String> data = new HashMap<>();
                Iterator it = hash.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry e = (Map.Entry) it.next();
                    data.put(e.getKey().toString(), e.getValue().toString());
                }
                data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/images/" + name);
                out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}");
            } catch (Exception ex) {
                strMessage += "File Upload Failed: " + ex;
                out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
            }
        } else {
            strMessage += "Only serve file upload requests";
            out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
        }
    }
}

From source file:com.esri.geoportal.harvester.beans.TaskManagerBean.java

@Override
public Collection<Map.Entry<UUID, TaskDefinition>> list() throws CrudlException {
    HashMap<UUID, TaskDefinition> map = new HashMap<>();
    try (Connection connection = dataSource.getConnection();
            PreparedStatement st = connection.prepareStatement("SELECT * FROM TASKS");) {
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            try {
                UUID id = UUID.fromString(rs.getString("id"));
                TaskDefinition td = deserialize(rs.getString("taskDefinition"), TaskDefinition.class);
                td.setRef(id.toString());
                map.put(id, td);/* w  w  w.  j  av a2 s  .  c o  m*/
            } catch (IOException | SQLException ex) {
                LOG.warn("Error reading task definition", ex);
            }
        }
    } catch (SQLException ex) {
        throw new CrudlException("Error selecting task", ex);
    }
    return map.entrySet();
}

From source file:ch.icclab.cyclops.resource.impl.GenerateResource.java

private TSDBData createPOJOObject(String name, ArrayList<String> columns, HashMap entrySet) {
    ArrayList<Object> objArrNode;
    Iterator<Map.Entry<String, Object>> entries;
    Object key;/*from  w  w w . j a v  a 2  s.com*/
    ArrayList<ArrayList<Object>> objArr = new ArrayList<ArrayList<Object>>();
    TSDBData result = new TSDBData();

    //TODO: parametrization of method
    entries = entrySet.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, Object> entry = entries.next();
        key = entry.getKey();
        objArrNode = new ArrayList<Object>();
        objArrNode.add(key);
        objArrNode.add(entry.getValue());
        objArrNode.add("static");
        objArr.add(objArrNode);
    }

    result.setName(name);
    result.setColumns(columns);
    result.setPoints(objArr);

    return result;
}

From source file:forestry.core.gui.GuiAlyzer.java

protected void drawAnalyticsPage4(IIndividual individual) {

    float factor = this.factor;
    this.setFactor(1.0f);

    startPage(COLUMN_0, COLUMN_1, COLUMN_2);
    drawLine(StringUtil.localize("gui.beealyzer.mutations") + ":", COLUMN_0);
    newLine();//from www  .  jav a2  s  . c o  m

    RenderHelper.enableGUIStandardItemLighting();

    HashMap<IMutation, IAllele> combinations = new HashMap<IMutation, IAllele>();

    for (IMutation mutation : speciesRoot.getCombinations(individual.getGenome().getPrimary()))
        combinations.put(mutation, individual.getGenome().getPrimary());

    for (IMutation mutation : speciesRoot.getCombinations(individual.getGenome().getSecondary()))
        combinations.put(mutation, individual.getGenome().getSecondary());

    int columnWidth = 50;
    int x = 0;

    for (Map.Entry<IMutation, IAllele> mutation : combinations.entrySet()) {

        if (breedingTracker.isDiscovered(mutation.getKey()))
            drawMutationInfo(mutation.getKey(), mutation.getValue(), COLUMN_0 + x);
        else {
            // Do not display secret undiscovered mutations.
            if (mutation.getKey().isSecret())
                continue;

            drawUnknownMutation(mutation.getKey(), mutation.getValue(), COLUMN_0 + x);
        }

        x += columnWidth;
        if (x >= columnWidth * 4) {
            x = 0;
            newLine();
            newLine();
        }
    }

    endPage();

    this.setFactor(factor);
}