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:com.krawler.spring.crm.common.ImportRecordAdvisor.java

private void AfterGetRefModuleData(MethodInvocation mi, Object result) throws DataInvalidateException {
    if (result != null) {
        List masterList = (List) result;
        if (masterList.size() == 0) {
            Object arguments[] = mi.getArguments();
            String module = (String) arguments[1];
            if (ImportHandler.isMasterTable(module)) { //Check for referencing to master
                try {
                    HashMap<String, Object> requestParams = (HashMap<String, Object>) arguments[0];
                    if (requestParams.containsKey("companyid") && requestParams.containsKey("doAction")
                            && requestParams.containsKey("masterPreference")) {
                        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) {
                            String comboConfigid = (String) arguments[3];
                            ArrayList<Object> filterValues = (ArrayList<Object>) arguments[5];

                            if (module.equalsIgnoreCase("DefaultMasterItem")
                                    || module.equalsIgnoreCase("com.krawler.common.admin.DefaultMasterItem")) {
                                String configid = (String) arguments[3];
                                String masterName = filterValues.get(0) != null ? filterValues.get(0).toString()
                                        : "";
                                masterName = masterName.length() > 50 ? masterName.substring(0, 50)
                                        : masterName; //Maxlength for value is 50 so truncate extra string
                                HashMap<String, Object> addParams = new HashMap<String, Object>();
                                addParams.put("companyid", companyid);
                                addParams.put("name", masterName);
                                addParams.put("configid", comboConfigid);

                                KwlReturnObject kmsg = crmManagerDAOObj.addMasterData(addParams);

                                JSONObject jResultObj = new JSONObject(kmsg.getEntityList().get(0).toString());
                                if (jResultObj.has("data")) {
                                    if (jResultObj.getJSONObject("data").has("id"))
                                        masterList.add(jResultObj.getJSONObject("data").getString("id"));
                                }/*  ww w.jav  a 2s  .  c om*/
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.linuxbox.enkive.imap.mongo.MongoImapAccountCreator.java

private DBObject getMessagesFolder(String username, Date date) {
    Calendar mailboxTime = Calendar.getInstance();
    mailboxTime.setTime(date);/*from  w  w w .  j  a va  2 s .  c  o m*/
    DBObject mailboxObject = new BasicDBObject();
    String mailboxPath = MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME + "/"
            + mailboxTime.get(Calendar.YEAR) + "/" + String.format("%02d", mailboxTime.get(Calendar.MONTH) + 1);

    // Get table of user mailboxes
    BasicDBObject userMailboxesSearchObject = new BasicDBObject();
    userMailboxesSearchObject.put(MongoEnkiveImapConstants.USER, username);
    DBObject userMailboxesObject = imapCollection.findOne(userMailboxesSearchObject);
    // Check for mailbox we're looking for
    @SuppressWarnings("unchecked")
    HashMap<String, String> mailboxTable = (HashMap<String, String>) userMailboxesObject
            .get(MongoEnkiveImapConstants.MAILBOXES);
    // If it exists, return the associated object
    // If it doesn't exist, create it, and any necessary upper level folders
    if (mailboxTable.containsKey(mailboxPath)) {
        DBObject mailboxSearchObject = new BasicDBObject();
        mailboxSearchObject.put("_id", ObjectId.massageToObjectId(mailboxTable.get(mailboxPath)));
        mailboxObject = imapCollection.findOne(mailboxSearchObject);
        return mailboxObject;
    } else {
        mailboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, new HashMap<String, String>());
        imapCollection.insert(mailboxObject);
        ObjectId id = (ObjectId) mailboxObject.get("_id");
        mailboxTable.put(mailboxPath, id.toString());
    }

    if (!mailboxTable.containsKey(
            MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME + "/" + mailboxTime.get(Calendar.YEAR))) {
        BasicDBObject yearMailboxObject = new BasicDBObject();
        yearMailboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, new HashMap<String, String>());
        imapCollection.insert(yearMailboxObject);
        ObjectId id = (ObjectId) yearMailboxObject.get("_id");
        mailboxTable.put(
                MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME + "/" + mailboxTime.get(Calendar.YEAR),
                id.toString());
    }
    userMailboxesObject.put(MongoEnkiveImapConstants.MAILBOXES, mailboxTable);
    imapCollection.findAndModify(userMailboxesSearchObject, userMailboxesObject);

    return mailboxObject;
}

From source file:com.liteoc.domain.rule.RuleSetRuleBean.java

@Transient
public HashMap<String, ArrayList<RuleActionBean>> getAllActionsWithEvaluatesToAsKey(String actionEvaluatesTo) {
    HashMap<String, ArrayList<RuleActionBean>> h = new HashMap<String, ArrayList<RuleActionBean>>();
    for (RuleActionBean action : actions) {
        String key = action.getExpressionEvaluatesTo().toString();
        if (actionEvaluatesTo == null || actionEvaluatesTo.equals(key)) {
            if (h.containsKey(key)) {
                h.get(key).add(action);/*from w w  w  . j  a  v a  2s. c o  m*/
            } else {
                ArrayList<RuleActionBean> a = new ArrayList<RuleActionBean>();
                a.add(action);
                h.put(key, a);
            }
        }
    }
    return h;
}

From source file:br.fapesp.myutils.MyUtils.java

/**
 * Get the most frequently occurring number in a sequence
 * @param values the sequence of numbers
 * @return the number that appears the most times in the sequence
 *//*from w  w  w . j  av  a 2  s .  com*/
public static double getMostFrequenceOccurrence(double[] values) {
    HashMap<Double, Integer> mapCount = new HashMap<Double, Integer>();
    int mostFreq = -1;
    double mostFreqVal = -1;

    for (int i = 0; i < values.length; i++) {
        if (!mapCount.containsKey(values[i]))
            mapCount.put(values[i], 0);
        else
            mapCount.put(values[i], mapCount.get(values[i]) + 1);
    }
    for (Double key : mapCount.keySet()) {
        if (mapCount.get(key) > mostFreq) {
            mostFreq = mapCount.get(key);
            mostFreqVal = key;
        }
    }
    return mostFreqVal;
}

From source file:info.plugmania.mazemania.Util.java

/**
 * Compress an ItemStack[] into a HashMap of the item string and the total amount of that item
 * Uses {@BlockUtil} to get the item string
 * @param inventory ItemStack[] to compress
 * @return HashMap<String,Integer>
 *//*from ww w. j a v  a2s  .c  om*/
public HashMap<String, Integer> compressInventory(ItemStack[] inventory) {
    HashMap<String, Integer> items = new HashMap<String, Integer>();
    if (inventory == null) {
        return null;
    }
    for (ItemStack item : inventory) {
        if (item == null)
            continue;
        String iString = item.getType().toString();
        if (items.containsKey(iString))
            items.put(iString, items.get(iString) + item.getAmount());
        else
            items.put(iString, item.getAmount());
    }
    return items;
}

From source file:com.adobe.acs.commons.exporters.impl.users.UsersExportServlet.java

/**
 * Generates a CSV file representing the User Data.
 *
 * @param request  the Sling HTTP Request object
 * @param response the Sling HTTP Response object
 * @throws IOException//from   ww  w  .  ja va 2s .c  om
 * @throws ServletException
 */
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/csv");
    response.setCharacterEncoding("UTF-8");

    final Parameters parameters = new Parameters(request);

    log.debug("Users to CSV Export Parameters: {}", parameters.toString());

    final Csv csv = new Csv();
    final Writer writer = response.getWriter();
    csv.writeInit(writer);

    final Iterator<Resource> resources = request.getResourceResolver().findResources(QUERY, Query.JCR_SQL2);

    // Using a HashMap to satisfy issue with duplicate results in AEM 6.1 GA
    HashMap<String, CsvUser> csvUsers = new LinkedHashMap<String, CsvUser>();

    while (resources.hasNext()) {
        try {
            Resource resource = resources.next();
            CsvUser csvUser = new CsvUser(resource);

            if (!csvUsers.containsKey(csvUser.getPath())
                    && checkGroups(parameters.getGroups(), parameters.getGroupFilter(), csvUser)) {
                csvUsers.put(csvUser.getPath(), csvUser);
            }

        } catch (RepositoryException e) {
            log.error("Unable to extract a user from resource.", e);
        }
    }

    List<String> columns = new ArrayList<String>();
    columns.add("Path");
    columns.add("User ID");
    columns.add("First Name");
    columns.add("Last Name");
    columns.add("E-mail Address");
    columns.add("Created Date");
    columns.add("Last Modified Date");

    for (String customProperty : parameters.getCustomProperties()) {
        columns.add(customProperty);
    }

    columns.add("All Groups");
    columns.add("Direct Groups");
    columns.add("Indirect Groups");

    csv.writeRow(columns.toArray(new String[columns.size()]));

    for (final CsvUser csvUser : csvUsers.values()) {
        List<String> values = new ArrayList<String>();
        try {
            values.add(csvUser.getPath());
            values.add(csvUser.getID());
            values.add(csvUser.getFirstName());
            values.add(csvUser.getLastName());
            values.add(csvUser.getEmail());
            values.add(csvUser.getCreatedDate());
            values.add(csvUser.getLastModifiedDate());

            for (String customProperty : parameters.getCustomProperties()) {
                values.add(csvUser.getCustomProperty(customProperty));
            }

            values.add(StringUtils.join(csvUser.getAllGroups(), GROUP_DELIMITER));
            values.add(StringUtils.join(csvUser.getDeclaredGroups(), GROUP_DELIMITER));
            values.add(StringUtils.join(csvUser.getTransitiveGroups(), GROUP_DELIMITER));

            csv.writeRow(values.toArray(new String[values.size()]));
        } catch (RepositoryException e) {
            log.error("Unable to export user to CSV report", e);
        }
    }

    csv.close();
}

From source file:GeneticAlgorithm.SystemToSolve.java

private boolean is_there_proteins(HashMap data) {
    boolean is_it_there = false;
    int count = 0;
    for (Enzyme enzyme : Enzymes) {
        String enzyme_ID = enzyme.getID();
        if (data.containsKey(enzyme_ID)) {
            count++;/*  w  w w  .j  a  v  a2s .co  m*/
        }
    }
    if (count > 0) {
        is_it_there = true;
    }
    return is_it_there;
}

From source file:com.facebook.tsdb.tsdash.server.model.Metric.java

public HashMap<String, HashSet<String>> getTagsSet() {
    HashMap<String, HashSet<String>> tagsSet = new HashMap<String, HashSet<String>>();
    for (TagsArray rowTags : timeSeries.keySet()) {
        for (Tag tag : rowTags.asArray()) {
            if (!tagsSet.containsKey(tag.key)) {
                tagsSet.put(tag.key, new HashSet<String>());
            }/*from w ww.  jav a  2  s .c om*/
            HashSet<String> values = tagsSet.get(tag.key);
            if (!tag.valueID.isNull() && !values.contains(tag.value)) {
                values.add(tag.value);
            }
        }
    }
    return tagsSet;
}

From source file:uk.ac.cam.cl.dtg.isaac.quiz.IsaacSymbolicValidator.java

@Override
public QuestionValidationResponse validateQuestionResponse(final Question question, final Choice answer)
        throws ValidatorUnavailableException {
    Validate.notNull(question);/*  w ww  .j a  va  2s .  c  om*/
    Validate.notNull(answer);

    if (!(question instanceof IsaacSymbolicQuestion)) {
        throw new IllegalArgumentException(
                String.format("This validator only works with Isaac Symbolic Questions... (%s is not symbolic)",
                        question.getId()));
    }

    if (!(answer instanceof Formula)) {
        throw new IllegalArgumentException(
                String.format("Expected Formula for IsaacSymbolicQuestion: %s. Received (%s) ",
                        question.getId(), answer.getClass()));
    }

    IsaacSymbolicQuestion symbolicQuestion = (IsaacSymbolicQuestion) question;
    Formula submittedFormula = (Formula) answer;

    // These variables store the important features of the response we'll send.
    Content feedback = null; // The feedback we send the user
    MatchType responseMatchType = MatchType.NONE; // The match type we found
    boolean responseCorrect = false; // Whether we're right or wrong

    // There are several specific responses the user can receive. Each of them will set feedback content, so
    // use that to decide whether to proceed to the next check in each case.

    // STEP 0: Do we even have any answers for this question? Always do this check, because we know we
    //         won't have feedback yet.

    if (null == symbolicQuestion.getChoices() || symbolicQuestion.getChoices().isEmpty()) {
        log.error("Question does not have any answers. " + question.getId() + " src: "
                + question.getCanonicalSourceFile());

        feedback = new Content("This question does not have any correct answers");
    }

    // STEP 1: Did they provide an answer?

    if (null == feedback && (null == submittedFormula.getPythonExpression()
            || submittedFormula.getPythonExpression().isEmpty())) {
        feedback = new Content("You did not provide an answer");
    }

    // STEP 2: Otherwise, Does their answer match a choice exactly?

    if (null == feedback) {

        // For all the choices on this question...
        for (Choice c : symbolicQuestion.getChoices()) {

            // ... that are of the Formula type, ...
            if (!(c instanceof Formula)) {
                log.error("Isaac Symbolic Validator for questionId: " + symbolicQuestion.getId()
                        + " expected there to be a Formula. Instead it found a Choice.");
                continue;
            }

            Formula formulaChoice = (Formula) c;

            // ... and that have a python expression ...
            if (null == formulaChoice.getPythonExpression() || formulaChoice.getPythonExpression().isEmpty()) {
                log.error("Expected python expression, but none found in choice for question id: "
                        + symbolicQuestion.getId());
                continue;
            }

            // ... look for an exact string match to the submitted answer.
            if (formulaChoice.getPythonExpression().equals(submittedFormula.getPythonExpression())) {
                feedback = (Content) formulaChoice.getExplanation();
                responseMatchType = MatchType.EXACT;
                responseCorrect = formulaChoice.isCorrect();
            }
        }
    }

    // STEP 3: Otherwise, use the symbolic checker to analyse their answer

    if (null == feedback) {

        // Go through all choices, keeping track of the best match we've seen so far. A symbolic match terminates
        // this loop immediately. A numeric match may later be replaced with a symbolic match, but otherwise will suffice.

        Formula closestMatch = null;
        MatchType closestMatchType = MatchType.NONE;

        // Sort the choices so that we match incorrect choices last, taking precedence over correct ones.
        List<Choice> orderedChoices = Lists.newArrayList(symbolicQuestion.getChoices());

        Collections.sort(orderedChoices, new Comparator<Choice>() {
            @Override
            public int compare(Choice o1, Choice o2) {
                int o1Val = o1.isCorrect() ? 0 : 1;
                int o2Val = o2.isCorrect() ? 0 : 1;
                return o1Val - o2Val;
            }
        });

        // For all the choices on this question...
        for (Choice c : orderedChoices) {

            // ... that are of the Formula type, ...
            if (!(c instanceof Formula)) {
                // Don't need to log this - it will have been logged above.
                continue;
            }

            Formula formulaChoice = (Formula) c;

            // ... and that have a python expression ...
            if (null == formulaChoice.getPythonExpression() || formulaChoice.getPythonExpression().isEmpty()) {
                // Don't need to log this - it will have been logged above.
                continue;
            }

            // ... test their answer against this choice with the symbolic checker.

            // We don't do any sanitisation of user input here, we'll leave that to the python.

            MatchType matchType = MatchType.NONE;

            try {
                // This is ridiculous. All I want to do is pass some JSON to a REST endpoint and get some JSON back.

                ObjectMapper mapper = new ObjectMapper();

                HashMap<String, String> req = Maps.newHashMap();
                req.put("target", formulaChoice.getPythonExpression());
                req.put("test", submittedFormula.getPythonExpression());
                req.put("description", symbolicQuestion.getId());

                StringWriter sw = new StringWriter();
                JsonGenerator g = new JsonFactory().createGenerator(sw);
                mapper.writeValue(g, req);
                g.close();
                String requestString = sw.toString();

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + "/check");

                httpPost.setEntity(new StringEntity(requestString, "UTF-8"));
                httpPost.addHeader("Content-Type", "application/json");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity responseEntity = httpResponse.getEntity();
                String responseString = EntityUtils.toString(responseEntity);
                HashMap<String, Object> response = mapper.readValue(responseString, HashMap.class);

                if (response.containsKey("error")) {
                    if (response.containsKey("code")) {
                        log.error("Failed to check formula \"" + submittedFormula.getPythonExpression()
                                + "\" against \"" + formulaChoice.getPythonExpression() + "\": "
                                + response.get("error"));
                    } else {
                        // If it doesn't contain a code, it wasn't a fatal error in the checker; probably only a
                        // problem with the submitted answer.
                        log.warn("Problem checking formula \"" + submittedFormula.getPythonExpression()
                                + "\" for (" + symbolicQuestion.getId() + ") with symbolic checker: "
                                + response.get("error"));
                    }
                } else {
                    if (response.get("equal").equals("true")) {
                        matchType = MatchType.valueOf(((String) response.get("equality_type")).toUpperCase());
                    }
                }

            } catch (IOException e) {
                log.error(
                        "Failed to check formula with symbolic checker. Is the server running? Not trying again.");
                throw new ValidatorUnavailableException(
                        "We are having problems marking Symbolic Questions." + " Please try again later!");
            }

            if (matchType == MatchType.EXACT) {
                closestMatch = formulaChoice;
                closestMatchType = MatchType.EXACT;
                break;
            } else if (matchType.compareTo(closestMatchType) > 0) {
                if (formulaChoice.getRequiresExactMatch() && formulaChoice.isCorrect()) {
                    closestMatch = formulaChoice;
                    closestMatchType = matchType;
                } else {
                    if (closestMatch == null || !closestMatch.getRequiresExactMatch()) {
                        closestMatch = formulaChoice;
                        closestMatchType = matchType;
                    } else {
                        // This is not as good a match as the one we already have.
                    }
                }
            }
        }

        if (null != closestMatch) {
            // We found a decent match. Of course, it still might be wrong.

            if (closestMatchType != MatchType.EXACT && closestMatch.getRequiresExactMatch()) {
                if (closestMatch.isCorrect()) {
                    feedback = new Content(
                            "Your answer is not in the form we expected. Can you rearrange or simplify it?");
                    responseCorrect = false;
                    responseMatchType = closestMatchType;

                    log.info("User submitted an answer that was close to an exact match, but not exact "
                            + "for question " + symbolicQuestion.getId() + ". Choice: "
                            + closestMatch.getPythonExpression() + ", submitted: "
                            + submittedFormula.getPythonExpression());
                } else {
                    // This is weak match to a wrong answer; we can't use the feedback for the choice.
                }
            } else {
                feedback = (Content) closestMatch.getExplanation();
                responseCorrect = closestMatch.isCorrect();
                responseMatchType = closestMatchType;
            }

            if (closestMatchType == MatchType.NUMERIC) {
                log.info("User submitted an answer that was only numerically equivalent to one of our choices "
                        + "for question " + symbolicQuestion.getId() + ". Choice: "
                        + closestMatch.getPythonExpression() + ", submitted: "
                        + submittedFormula.getPythonExpression());

                // TODO: Decide whether we want to add something to the explanation along the lines of "you got it
                //       right, but only numerically.
            }

        }
    }

    // If we got this far and feedback is still null, they were wrong. There's no useful feedback we can give at this point.

    return new FormulaValidationResponse(symbolicQuestion.getId(), answer, feedback, responseCorrect,
            responseMatchType.toString(), new Date());
}

From source file:com.boxupp.utilities.PuppetUtilities.java

public StatusBean refreshNodeTemplate(List<PuppetModuleMapping> puppetModuleData, String ProjectID) {

    HashMap<String, ArrayList<String>> nodeConfigMap = new HashMap<String, ArrayList<String>>();
    for (PuppetModuleMapping puppetModule : puppetModuleData) {
        if (puppetModule.getMachineConfig().getIsDisabled() == false
                && puppetModule.getPuppetModule().getIsDisabled() == false) {
            if (nodeConfigMap.containsKey(puppetModule.getMachineConfig().getHostName())) {
                nodeConfigMap.get(puppetModule.getMachineConfig().getHostName())
                        .add(puppetModule.getPuppetModule().getModuleName());
            } else {
                ArrayList<String> moduleNameList = new ArrayList<String>();
                moduleNameList.add(puppetModule.getPuppetModule().getModuleName());
                nodeConfigMap.put(puppetModule.getMachineConfig().getHostName(), moduleNameList);
            }/*from   w w w  .j  a v  a  2 s. co  m*/
        }
    }

    boolean configFileData = ConfigurationGenerator.generateNodeConfig(nodeConfigMap);
    StatusBean statusBean = new StatusBean();
    if (configFileData) {
        logger.info("Started saving Nodes.pp file");
        FileManager fileManager = new FileManager();
        String renderedTemplate = ConfigurationGenerator.getVelocityFinalTemplate();
        statusBean = fileManager.writeNodeFileToDisk(renderedTemplate, ProjectID);
        logger.info("Nodes.pp file save completed");
    } else {
        logger.info("Failed to save Nodes.pp file !!");
    }

    return statusBean;

}