Example usage for java.util HashMap containsKey

List of usage examples for java.util HashMap containsKey

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzResultDialog.java

private void updateValues(ArrayList<HttpFuzzRecord> members, HashMap<String, Integer> statesMap,
        HashMap<String, Integer> resultMap) {
    for (HttpFuzzRecord r : members) {
        if (r.isIncluded() && r instanceof HttpFuzzRequestRecord) {
            if (statesMap.containsKey(r.getReason())) {
                statesMap.put(r.getReason(), statesMap.get(r.getReason()) + 1);
            } else {
                statesMap.put(r.getReason(), 1);
            }/*from   www  . j a v a  2 s .  c o  m*/
            if (resultMap.containsKey(r.getResult().first)) {
                resultMap.put(r.getResult().first, resultMap.get(r.getResult().first) + 1);
            } else {
                resultMap.put(r.getResult().first, 1);
            }
            sizeSet.addValue(r.getSize(), "Row 1", r.getName());
            rttSet.addValue(r.getRTT(), "Row 1", r.getName());
        } else if (r.isIncluded() && r instanceof HttpFuzzRecordGroup) {
            updateValues(((HttpFuzzRecordGroup) r).getMembers(), statesMap, resultMap);
        }
    }

}

From source file:jobs.WarningMonitorJob.java

/**
 * All checks done on specific plants under the GardenDroid's care will be managed from here.
 * @param options/*  w  w  w.  j  a  v  a2s . co m*/
 * @throws EmailException 
 */
public boolean checkActivePlantings(Options options) {
    boolean alertDetected = false;
    if (options.enablePlantedWarnings) {
        StringBuilder sb = new StringBuilder();

        List<Plant> plantings = Plant.getActivePlantings();
        for (Plant plant : plantings) {
            //Check Temp Thresholds
            logger.warn("### Checking on plant: " + plant);
            int tempWarn = checkForTempThresholdsAlert(plant.plantData);
            if (tempWarn == 1) {
                sb.append("\n ").append(plant.name)
                        .append(": Tempratures have exceeded the Plants indicated tolerance range.");
            } else if (tempWarn == -1) {
                sb.append("\n ").append(plant.name)
                        .append(": Tempratures have dropped below the Plants indicated tolerance range.");
            }
            //check watering
            HashMap<SensorType, SensorData> latest = SensorData.retrieveLatestSensorData();
            boolean sensorState = false;
            boolean observationState = false;
            int waterDays = plant.plantData.waterFreqDays;
            if (latest.containsKey(SensorType.WATER_IRRIGATION)
                    && latest.get(SensorType.WATER_IRRIGATION) != null) {

                SensorData water = latest.get(SensorType.WATER_IRRIGATION);
                logger.warn("### latest water data== " + water);
                Calendar waterDate = Calendar.getInstance();
                waterDate.setTime(water.dateTime);

                Calendar nextWaterDate = Calendar.getInstance();
                nextWaterDate.add(Calendar.DATE, waterDays);

                if (waterDate.before(nextWaterDate)) {
                    sensorState = true;
                }
            }

            if (!sensorState) { //check observation entries.
                ObservationData mostRecent = ObservationData
                        .find("plant = ? AND dataType = ? order by dateCreated desc",
                                new Object[] { plant, UserDataType.DEFAULT_PLANT_IRRIGATION })
                        .first();
                if (mostRecent != null) {
                    Calendar obsWaterDate = Calendar.getInstance();
                    obsWaterDate.setTime(mostRecent.dateCreated);

                    Calendar nextWaterDate = Calendar.getInstance();
                    nextWaterDate.add(Calendar.DATE, waterDays);
                    if (obsWaterDate.before(nextWaterDate)) {
                        observationState = true;
                    }
                }
            }
            logger.warn(" sensorState=" + sensorState + "  ObsState=" + observationState);
            if (!sensorState & !observationState) {
                sb.append("\n ").append(plant.name).append(": is due for irrigation.");
            }

        }

        if (sb.length() > 0) {
            try {
                alertDetected = true;
                if (options.enableWarningNotification) {
                    sendNotification(options, "", sb.toString());
                }
                logger.info("Plant Alert Message Sent: " + sb.toString());
            } catch (EmailException e) {
                logger.error("Email Alert failed.", e);
                new LogData(new Date(), "Failed to send email address to email address: " + options.email)
                        .save();
            }
        }

    }
    return alertDetected;
}

From source file:com.krawler.spring.crm.common.ImportRecordAdvisor.java

private void AfterGetCustomComboID(MethodInvocation mi, Object result) throws DataInvalidateException {
    if (result != null) {
        List masterList = (List) result;
        if (masterList.size() == 0) {
            Object arguments[] = mi.getArguments();
            try {
                HashMap<String, Object> requestParams = (HashMap<String, Object>) arguments[0];
                if (requestParams.containsKey("doAction") && requestParams.containsKey("masterPreference")) {
                    //                    String module = (String) arguments[1];
                    //                    String companyid = requestParams.get("companyid").toString();
                    String doAction = requestParams.get("doAction").toString();
                    String pref = (String) requestParams.get("masterPreference"); //0:Skip Record, 1:Skip Column, 2:Add new
                    String addMissingMaster = (String) requestParams.get("addMissingMaster");
                    if (doAction.compareToIgnoreCase("import") == 0 && pref != null
                            && pref.compareToIgnoreCase("2") == 0) {
                        ArrayList<Object> filterValues = (ArrayList<Object>) arguments[3];
                        String fieldid = filterValues.get(1).toString();
                        String combovalue = (String) filterValues.get(0);

                        HashMap<String, Object> comborequestParams = new HashMap<String, Object>();
                        comborequestParams.put("Fieldid", fieldid);
                        comborequestParams.put("Value", combovalue);
                        KwlReturnObject kmsg = fieldManagerDAOobj.insertfieldcombodata(comborequestParams);
                        //                        JSONObject jobj = new JSONObject(fieldManager.addCustomComboData(fieldid, combovalue));
                        if (kmsg.getEntityList().size() > 0) {
                            Iterator ite = kmsg.getEntityList().iterator();
                            FieldComboData fieldData = (FieldComboData) ite.next();
                            masterList.add(fieldData.getId());
                        }//from  w  w  w  .  java2  s.c o  m
                    }
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:fr.paris.lutece.plugins.search.solr.web.SolrSearchApp.java

/**
 * Returns a model with points data from a geoloc search
 * @param listResultsGeoloc the result of a search
 * @return the model/*from   w  ww  . j a  va  2 s.c  om*/
 */
private static List<HashMap<String, Object>> getGeolocModel(List<SolrSearchResult> listResultsGeoloc) {
    List<HashMap<String, Object>> points = new ArrayList<HashMap<String, Object>>(listResultsGeoloc.size());
    HashMap<String, String> iconKeysCache = new HashMap<String, String>();

    for (SolrSearchResult result : listResultsGeoloc) {
        Map<String, Object> dynamicFields = result.getDynamicFields();

        for (String key : dynamicFields.keySet()) {
            if (key.endsWith(SolrItem.DYNAMIC_GEOJSON_FIELD_SUFFIX)) {
                HashMap<String, Object> h = new HashMap<String, Object>();
                String strJson = (String) dynamicFields.get(key);
                GeolocItem geolocItem = null;

                try {
                    geolocItem = GeolocItem.fromJSON(strJson);
                } catch (IOException e) {
                    AppLogService
                            .error("SolrSearchApp: error parsing geoloc JSON: " + strJson + ", exception " + e);
                }

                if (geolocItem != null) {
                    String strType = result.getId().substring(result.getId().lastIndexOf("_") + 1);
                    String strIcon;

                    if (iconKeysCache.containsKey(geolocItem.getIcon())) {
                        strIcon = iconKeysCache.get(geolocItem.getIcon());
                    } else {
                        strIcon = IconService.getIcon(strType, geolocItem.getIcon());
                        iconKeysCache.put(geolocItem.getIcon(), strIcon);
                    }

                    geolocItem.setIcon(strIcon);
                    h.put(MARK_POINTS_GEOJSON, geolocItem.toJSON());
                    h.put(MARK_POINTS_ID, result.getId().substring(result.getId().indexOf("_") + 1,
                            result.getId().lastIndexOf("_")));
                    h.put(MARK_POINTS_FIELDCODE, key.substring(0, key.lastIndexOf("_")));
                    h.put(MARK_POINTS_TYPE, strType);
                    points.add(h);
                }
            }
        }
    }
    return points;
}

From source file:com.wentam.defcol.connect_to_computer.HomeCommandHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext httpContext)
        throws HttpException, IOException {
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String req = request.getRequestLine().getUri();

            req = req.replaceAll("/\\?", "");

            String[] pairs = req.split("&");

            HashMap data = new HashMap();

            for (int i = 0; i < pairs.length; i++) {
                if (pairs[i].contains("=")) {
                    String[] pair = pairs[i].split("=");
                    data.put(pair[0], pair[1]);
                }//  w w w .ja  va2  s  .  c o m
            }

            String action = "none";
            if (data.containsKey("action")) {
                action = (String) data.get("action");
            }

            String resp = "404 on " + action;
            if (action.equals("none") || action.equals("home")) {
                response.setHeader("Content-Type", "text/html");

                resp = getHtml();

            } else if (action.equals("getPalettes")) {
                response.setHeader("Content-Type", "application/json");

                JSONArray json = new JSONArray();

                int tmp[] = { 0 };
                ArrayList<String> palettes = pFile.getRows(tmp);
                Iterator i = palettes.iterator();
                while (i.hasNext()) {
                    JSONObject item = new JSONObject();
                    try {
                        item.put("name", i.next());
                    } catch (JSONException e) {
                    }
                    json.put(item);
                }

                resp = json.toString();

            } else if (action.equals("getJquery")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = jquery;
            } else if (action.equals("getJs")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = getJs();
            } else if (action.equals("getPaletteColors")) {
                response.setHeader("Content-Type", "application/javascript");
                int id = Integer.parseInt((String) data.get("id"));

                int tmp[] = { 1 };
                String row = pFile.getRow(id, tmp);

                String colors[] = row.split("\\.");

                JSONArray json = new JSONArray();

                for (int i = 0; i < colors.length; i++) {
                    json.put(colors[i]);
                }

                resp = json.toString();
            }

            writer.write(resp);
            writer.flush();
        }
    });

    response.setEntity(entity);
}

From source file:com.ethercamp.harmony.service.BlockchainInfoService.java

@Scheduled(fixedRate = 2000)
private void doUpdateNetworkInfo() {
    final NetworkInfoDTO info = new NetworkInfoDTO(channelManager.getActivePeers().size(),
            NetworkInfoDTO.SyncStatusDTO.instanceOf(syncManager.getSyncStatus()), config.listenPort(), true);

    final HashMap<String, Integer> miners = new HashMap<>();
    lastBlocksForHashRate.stream().forEach(b -> {
        String minerAddress = Hex.toHexString(b.getCoinbase());
        int count = miners.containsKey(minerAddress) ? miners.get(minerAddress) : 0;
        miners.put(minerAddress, count + 1);
    });/* w w w .  j  a v a  2 s . co  m*/

    final List<MinerDTO> minersList = miners.entrySet().stream()
            .map(entry -> new MinerDTO(entry.getKey(), entry.getValue()))
            .sorted((a, b) -> Integer.compare(b.getCount(), a.getCount())).limit(3).collect(toList());
    info.getMiners().addAll(minersList);

    networkInfo.set(info);

    clientMessageService.sendToTopic("/topic/networkInfo", info);
}

From source file:net.certiv.authmgr.task.section.core.classifier.BayesPartitionClassifier.java

/**
 * @param category//from  www . j av a 2  s  .  c o  m
 * @param partition
 */
private void addTrainingCount(String category, String partition) {
    if (categoryCounter.containsKey(category)) {
        HashMap<String, Integer> partitionCounter = categoryCounter.get(category);
        if (partitionCounter.containsKey(partition)) {
            int cnt = partitionCounter.get(partition).intValue();
            partitionCounter.put(partition, new Integer(cnt + 1));
        } else {
            partitionCounter.put(partition, new Integer(1));
        }
    } else {
        HashMap<String, Integer> partitionCounter = new HashMap<String, Integer>();
        partitionCounter.put(partition, new Integer(1));
        categoryCounter.put(category, partitionCounter);
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {

    InitializationService.initialize();// w w  w.  j av a2s . com

    logger.info("Finding IdP...");
    String idpName = loadOption(cmd, "idpName", options);

    ApplicationType idp = null;

    for (ApplicationType app : tt.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }

    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }

    logger.info("Loading the base URL");
    String baseURL = loadOption(cmd, "urlBase", options);

    String url = baseURL + idp.getUrls().getUrl().get(0).getUri();

    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptor ed = edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);

    IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
    IDPSSODescriptor sd = idpssdb.buildObject();//ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    ed.getRoleDescriptors().add(sd);

    HashMap<String, List<String>> params = new HashMap<String, List<String>>();
    for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
        List<String> vals = params.get(pt.getName());
        if (vals == null) {
            vals = new ArrayList<String>();
            params.put(pt.getName(), vals);
        }
        vals.add(pt.getValue());
    }

    sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn")
            && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));

    KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();

    if (params.get("encKey") != null && !params.get("encKey").isEmpty()
            && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    if (params.get("sigKey") != null && !params.get("sigKey").isEmpty()
            && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    HashSet<String> nameids = new HashSet<String>();

    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        for (ParamType pt : trustType.getParam()) {
            if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
                if (!nameids.contains(val)) {
                    nameids.add(val);
                }
            }
        }
    }

    NameIDFormatBuilder nifb = new NameIDFormatBuilder();

    for (String nidf : nameids) {
        NameIDFormat nif = nifb.buildObject();
        nif.setFormat(nidf);
        sd.getNameIDFormats().add(nif);
    }

    SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
    SingleSignOnService sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sso.setLocation(url + "/httpPost");
    sd.getSingleSignOnServices().add(sso);

    sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sso.setLocation(url + "/httpRedirect");
    sd.getSingleSignOnServices().add(sso);

    String signingKey = loadOptional(cmd, "signMetadataWithKey", options);

    if (signingKey != null && ks.getCertificate(signingKey) != null) {
        BasicX509Credential signingCredential = new BasicX509Credential(
                (X509Certificate) ks.getCertificate(signingKey),
                (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));

        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);

        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

        ed.setSignature(signature);
        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }
        Signer.signObject(signature);
    }

    // Get the Subject marshaller
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();

    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);

    logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}

From source file:edu.tum.cs.conqat.quamoco.qiesl.QIESLEngine.java

/**
 * @param variables//from ww  w.j  a  v a  2 s.  c  o  m
 * @throws QIESLException
 */
private Map<String, String> createNameMapping(Map<String, Object> variables) throws QIESLException {
    HashMap<String, String> mapping = new HashMap<String, String>();
    for (String modelName : variables.keySet()) {
        String technicalName = toTechnicalName(modelName);
        if (mapping.containsKey(technicalName)) {
            throw new QIESLException("Model names " + modelName + " and " + mapping.get(technicalName)
                    + " map to same to technial name: " + technicalName);
        }
        mapping.put(technicalName, modelName);
    }
    return mapping;

}

From source file:de.joinout.criztovyl.tools.files.MultiFileGrep.java

/**
 * Greps from all files and returns a {@link Map} with the matched file as a key and the matching lines as value. 
 * @return a {@link HashMap} with a {@link Path} as key and a {@link String} {@link List} as value.
 *//* ww w . ja  v a2 s  .  c o m*/
public HashMap<Path, ArrayList<String>> grep() {

    //Create map
    HashMap<Path, ArrayList<String>> map = new HashMap<>();

    //Iterate over paths
    for (final Path file : paths) {

        try { //Try reading all lines from file

            //Iterate over lines
            for (final String line : FileUtils.readLines(file.getFile())) {

                //Check if line matches
                if (line.matches(regex))

                    //Add file to map if not present
                    if (!map.containsKey(file))
                        map.put(file, new ArrayList<String>());

                //Add line
                map.get(file).add(line);
            }

        } catch (final FileNotFoundException e) { // Catch if file not found
            logger.warn("File {} not found!", file);
            logger.debug(e);
        } catch (final IOException e) { // Catch general IOException
            logger.error("IOException!", e);
        }

    }

    //Return
    return map;
}