Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.epam.ta.reportportal.events.handler.ProjectActivityHandler.java

@EventListener
public void onApplicationEvent(ProjectUpdatedEvent event) {
    Project project = event.getBefore();
    HashMap<String, Activity.FieldValues> history = new HashMap<>();

    ProjectConfiguration configuration = event.getUpdateProjectRQ().getConfiguration();
    if (null != configuration) {
        processKeepLogs(history, project, configuration);
        processKeepScreenshots(history, project, configuration);
        processLaunchInactivityTimeout(history, project, configuration);
        processAutoAnalyze(history, project, configuration);
    }/*from   w  ww.  ja v  a  2s .c o  m*/

    if (!history.isEmpty()) {
        Activity activityLog = activityBuilder.get().addProjectRef(project.getName())
                .addObjectType(Project.PROJECT).addActionType(UPDATE_PROJECT).addUserRef(event.getUpdatedBy())
                .build();
        activityLog.setHistory(history);
        activityRepository.save(activityLog);
    }
}

From source file:gr.iit.demokritos.cru.cps.ai.ComputationalCreativityMetrics.java

public Map<String, Double> Novelty(ArrayList<String> stories)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
    String AllStories = "";
    Map<String, Double> novelties = new HashMap<String, Double>();
    //count average sem distance for every story
    Map<String, Double> stoped = new HashMap<String, Double>();
    for (int i = 0; i < stories.size(); i++) {
        HashMap<ArrayList<String>, Double> top = inf.TopTerms(stories.get(i).replace("---", " "), false);
        if (top.isEmpty()) {
            stoped.put(stories.get(i), -1.0);
        }//  w ww .  j  ava  2 s . com
        //cumpute the average semantic distance of the top terms in this story
        Set<String> terms = new HashSet<String>();
        for (ArrayList<String> stems : top.keySet()) {
            //if it is in compact form , there is only one term for each stem 
            for (int j = 0; j < stems.size(); j++) {
                terms.add(stems.get(j));
            }
        }
        // System.out.println("terms" + terms);
        double nov = AvgSemDist(terms);
        novelties.put(stories.get(i), nov);
        AllStories += "  " + stories.get(i);
    }
    //count avg semantic distance for all the stories together
    HashMap<ArrayList<String>, Double> bigtop = inf.TopTerms(AllStories, false);
    Set<String> termsAll = new HashSet<String>();
    for (ArrayList<String> stems : bigtop.keySet()) {
        for (int j = 0; j < stems.size(); j++) {
            termsAll.add(stems.get(j));
        }
    }
    //the novelty of all stories combined
    double novBig = AvgSemDist(termsAll);
    for (Map.Entry<String, Double> nov : novelties.entrySet()) {
        double newNov = 2 * abs(nov.getValue() - novBig);// / bigtop.size();
        novelties.put(nov.getKey(), newNov);
    }
    novelties.putAll(stoped);
    return novelties;
}

From source file:com.cssweb.android.base.BaseActivity.java

@Override
protected void onResume() {
    super.onResume();
    alarmManager.cancel(pendingIntent);/*from w w  w  . j av a 2 s .  co  m*/
    if (ActivityUtil.ALARM_RECORED >= Config.lockTime) {
        finish();
        this.mLock = false;
        ActivityUtil.restart(this, 0);
    }
    ActivityUtil.ALARM_RECORED = -1;
    HashMap<String, Integer> hashMap = StockInfo.hashMap;
    if (hashMap.isEmpty()) {
        String jsonObject = CssIniFile.loadStockData(BaseActivity.this,
                CssIniFile.GetFileName(CssIniFile.UserStockFile));
        JSONObject quoteData;
        try {
            if (jsonObject != null) {
                quoteData = new JSONObject(jsonObject);
                StockInfo.initAllStock(quoteData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    ServiceControl.resumeHomeReceiver();
}

From source file:org.simiancage.bukkit.DwarfForge.Forge.java

/**
 * Move the item stack to the input/output chest as provided.
 * @param item/*w w w  .  jav a  2 s. c om*/
 * @param chest - block to move the item into. Can be null.
 * @param dropRemains whether to drop anything that can't be moved
 * @return anything that did not get moved
 */
ItemStack addTo(ItemStack item, Block chest, boolean dropRemains) {
    Validate.notNull(item);

    if (chest == null) {
        // No destination chest.
        if (dropRemains) {
            loc.getWorld().dropItemNaturally(loc, item);
            return null;
        } else {
            return item;
        }
    } else {
        BlockState ch = chest.getState();
        Inventory chestInv;
        if (ch instanceof InventoryHolder) {
            chestInv = ((InventoryHolder) ch).getInventory();
        } else {
            // Destination is not a chest.
            if (dropRemains) {
                loc.getWorld().dropItemNaturally(loc, item);
                return null;
            } else {
                return item;
            }
        }
        HashMap<Integer, ItemStack> remains = chestInv.addItem(item);
        if (remains.isEmpty()) {
            // Everything fit!
            return null;
        } else {
            // Destination chest full.
            if (dropRemains) {
                loc.getWorld().dropItemNaturally(loc, remains.get(0));
                return null;
            } else {
                return remains.get(0);
            }
        }
    }
}

From source file:com.googlecode.erca.framework.algo.ClfGenerator.java

/**
 * Build the CLF for the given RCF./*from www. j a  v a2 s.c o  m*/
 * @throws IOException IOException.
 */
public void generateClf() throws IOException {
    logger.info("Starting concept lattice family construction.");
    logger.info("Initializing lattices.");

    stepNumber = 0;

    this.clf = ClfFactory.eINSTANCE.createConceptLatticeFamily();

    for (FormalContext context : this.rcf.getFormalContexts())
        initializeLattice(context);

    HashMap<ConceptLattice, EList<Concept>> nextStepConcepts = initNextStepConcepts();
    HashMap<ConceptLattice, EList<Concept>> currentStepConcepts = new HashMap<ConceptLattice, EList<Concept>>();
    EList<Concept> newConcepts;

    logger.info("Starting relational construction process.");

    boolean stopProcess = (nextStepConcepts.isEmpty() || (maxStepNumber > 0 && stepNumber >= maxStepNumber));

    while (!stopProcess) {

        if (saveDebugLattices) {
            logger.debug("Saving debug informations.");
            String clfPath = debugDir.getAbsolutePath() + "/clf_" + stepNumber + ".clf";
            ErcaIO.saveErcaObject(clf, clfPath);
        }

        stepNumber++;

        logger.debug("Step number " + Integer.toString(stepNumber));

        int addedConcepts = 0;
        currentStepConcepts = nextStepConcepts;
        nextStepConcepts = new HashMap<ConceptLattice, EList<Concept>>();
        for (FormalContext context : this.rcf.getFormalContexts()) {
            ConceptLattice lattice = this.clf.getConceptLattice(context.getName());
            for (RelationalContext relation : this.rcf.getRelationalContexts(context)) {
                ConceptLattice targetLattice = this.clf
                        .getConceptLattice(relation.getTargetContext().getName());
                newConcepts = null;
                newConcepts = scale(lattice, relation, currentStepConcepts.get(targetLattice));
                if (newConcepts != null) {
                    addedConcepts += newConcepts.size();
                    // Sets the creation step attribute
                    for (Concept concept : newConcepts)
                        concept.setCreationStep(stepNumber);
                }
                if (newConcepts == null || newConcepts.isEmpty())
                    continue;
                else if (nextStepConcepts.get(lattice) == null)
                    nextStepConcepts.put(lattice, newConcepts);
                else
                    nextStepConcepts.get(lattice).addAll(newConcepts);
            }
        }

        logger.debug("Added concepts: " + Integer.toString(addedConcepts));

        stopProcess = (nextStepConcepts.isEmpty() || (maxStepNumber > 0 && stepNumber >= maxStepNumber));
    }

    clf.setStepNumber(stepNumber);

    applyFilters();
}

From source file:org.simiancage.bukkit.DwarfForge.Forge.java

boolean updateFuel() {
    // TODO assert DFConfig.requireFuel()

    Furnace state = (Furnace) getBlock().getState();
    Inventory blockInv = state.getInventory();

    // Can reload only if fuel slot is empty.
    ItemStack fuel = blockInv.getItem(FUEL_SLOT);
    if (fuel == null || fuel.getType() == Material.AIR) {

        // Can reload only if an input chest is available.
        Block input = getInputChest();/*from   w ww .j  a v a 2s.  c o  m*/
        if (input != null) {
            BlockState inpstate = input.getState();
            if (inpstate instanceof InventoryHolder) {
                Inventory inpInv = ((InventoryHolder) inpstate).getInventory();

                for (ItemStack item : inpInv.getContents()) {
                    if (Utils.canBurn(item.getType())) {
                        int takeAmount = 1;
                        // Only take 1/4 of stack, to allow multiple feeding
                        if ((item.getAmount() / 4) > 1) {
                            takeAmount = item.getAmount() / 4;
                        }
                        ItemStack toTake = item.clone();
                        toTake.setAmount(takeAmount);
                        HashMap<Integer, ItemStack> ghost = inpInv.removeItem(toTake);
                        if (!ghost.isEmpty()) {
                            toTake.setAmount(toTake.getAmount() - ghost.get(0).getAmount());
                        }
                        blockInv.setItem(FUEL_SLOT, toTake);
                        return true;
                    }
                }
                return false;
            }
        }
    }

    return true;
}

From source file:com.datatorrent.lib.math.QuotientMap.java

/**
 * Generates tuples for each key and emits them. Only keys that are in the
 * denominator are iterated on If the key is only in the numerator, it gets
 * ignored (cannot do divide by 0) Clears internal data
 *//*from   w ww  . j a v a  2  s.c o m*/
@Override
public void endWindow() {
    HashMap<K, Double> tuples = new HashMap<K, Double>();
    for (Map.Entry<K, MutableDouble> e : denominators.entrySet()) {
        MutableDouble nval = numerators.get(e.getKey());
        if (nval == null) {
            tuples.put(e.getKey(), new Double(0.0));
        } else {
            tuples.put(e.getKey(), new Double((nval.doubleValue() / e.getValue().doubleValue()) * mult_by));
        }
    }
    if (!tuples.isEmpty()) {
        quotient.emit(tuples);
    }
    numerators.clear();
    denominators.clear();
}

From source file:org.wso2.carbon.policy.mgt.core.mgt.impl.MonitoringManagerImpl.java

@Override
public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException {

    //int tenantId = PolicyManagerUtil.getTenantId();
    Map<Integer, Device> deviceIds = new HashMap<>();
    List<NonComplianceData> complianceDatas = new ArrayList<>();
    HashMap<Integer, Integer> devicePolicyIdMap = new HashMap<>();

    try {/*from   www  .  ja v a  2  s .c o  m*/
        PolicyManagementDAOFactory.openConnection();
        //TODO: Return a map from getCompliance to reduce O(n^2) -> O(n)
        List<NonComplianceData> cd = monitoringDAO.getCompliance();

        for (Device device : devices) {
            deviceIds.put(device.getId(), device);

            for (NonComplianceData data : cd) {
                if (device.getId() == data.getDeviceId()
                        && device.getEnrolmentInfo().getId() == data.getEnrolmentId()) {
                    complianceDatas.add(data);
                }
            }
        }
        List<Integer> deviceIDs = new ArrayList<>(deviceIds.keySet());

        HashMap<Integer, Integer> temp = policyDAO.getAppliedPolicyIds();
        for (Integer id : deviceIDs) {
            if (temp != null && !temp.isEmpty() && temp.containsKey(id)) {
                devicePolicyIdMap.put(id, temp.get(id));
            }
        }

    } catch (SQLException e) {
        throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e);
    } catch (MonitoringDAOException e) {
        throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e);
    } catch (PolicyManagerDAOException e) {
        throw new PolicyComplianceException("SQL error occurred while getting policy details.", e);
    } finally {
        PolicyManagementDAOFactory.closeConnection();
    }

    Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>();
    Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();

    List<PolicyDeviceWrapper> firstTimeDevices = new ArrayList<>();

    Map<Integer, NonComplianceData> tempMap = new HashMap<>();

    try {
        if (complianceDatas != null || !complianceDatas.isEmpty()) {
            for (NonComplianceData complianceData : complianceDatas) {

                tempMap.put(complianceData.getDeviceId(), complianceData);

                if (complianceData.getAttempts() == 0) {
                    deviceIdsToAddOperation.put(complianceData.getDeviceId(),
                            deviceIds.get(complianceData.getDeviceId()));
                } else {
                    deviceIdsWithExistingOperation.put(complianceData.getDeviceId(),
                            deviceIds.get(complianceData.getDeviceId()));
                }
            }
        }

        for (Device device : devices) {
            if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) {
                deviceIdsToAddOperation.put(device.getId(), device);

                PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper();
                policyDeviceWrapper.setDeviceId(device.getId());
                policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId());
                policyDeviceWrapper.setPolicyId(devicePolicyIdMap.get(device.getId()));

                firstTimeDevices.add(policyDeviceWrapper);

                // firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId()));
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("These devices are in the system for the first time");
            for (PolicyDeviceWrapper wrapper : firstTimeDevices) {
                log.debug("First time device primary key : " + wrapper.getDeviceId() + " & policy id "
                        + wrapper.getPolicyId());
            }
        }

        PolicyManagementDAOFactory.beginTransaction();

        if (!deviceIdsToAddOperation.isEmpty()) {
            //                monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds);
            monitoringDAO.addComplianceDetails(firstTimeDevices);
            monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsToAddOperation.keySet()), false);
        }

        if (!deviceIdsWithExistingOperation.isEmpty()) {
            monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsWithExistingOperation.keySet()), false);
        }
        PolicyManagementDAOFactory.commitTransaction();

    } catch (MonitoringDAOException e) {
        PolicyManagementDAOFactory.rollbackTransaction();
        throw new PolicyComplianceException("Error occurred from monitoring dao.", e);
    } catch (PolicyManagerDAOException e) {
        PolicyManagementDAOFactory.rollbackTransaction();
        throw new PolicyComplianceException("Error occurred reading the applied policies to devices.", e);
    } finally {
        PolicyManagementDAOFactory.closeConnection();
    }

    if (!deviceIdsToAddOperation.isEmpty()) {
        try {
            this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values()));
        } catch (InvalidDeviceException e) {
            throw new PolicyComplianceException("Invalid Device Identifiers found.", e);
        } catch (OperationManagementException e) {
            throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices",
                    e);
        }
    }
}

From source file:org.simiancage.bukkit.DwarfForge.Forge.java

/**
 * Update the raw material slot of the forge.
 * @return true if forge can continue working
 *//*from   w  w w.j ava 2s  . c  o  m*/
boolean updateRawMaterial() {
    Furnace state = (Furnace) getBlock().getState();
    Inventory blockInv = state.getInventory();

    // Can only reload if the raw material slot is empty.
    ItemStack raw = blockInv.getItem(RAW_SLOT);
    if (raw != null && raw.getType() != Material.AIR) {
        // Something already in the raw slot; is it smeltable?
        return Utils.canCook(raw.getType());
    } else {
        // Can only reload if an input chest is available.
        Block input = getInputChest();
        if (input != null) {
            BlockState inpstate = input.getState();
            if (inpstate instanceof InventoryHolder) {
                Inventory inpInv = ((InventoryHolder) inpstate).getInventory();

                // Check for the same item first
                Material want = Utils.getRawProduct(blockInv.getItem(PRODUCT_SLOT).getType());
                if (inpInv.contains(want)) {
                    ItemStack inp = inpInv.getItem(inpInv.first(want));
                    inpInv.removeItem(inp);
                    blockInv.setItem(RAW_SLOT, inp);
                    return true;
                }
                // Can't find the same item, look for anything
                for (ItemStack item : inpInv.getContents()) {
                    if (Utils.canCook(item.getType())) {
                        int takeAmount = 1;
                        // Take all, because it's generally more efficent
                        if ((item.getAmount()) > 1) {
                            takeAmount = item.getAmount();
                        }
                        ItemStack toTake = item.clone();
                        toTake.setAmount(takeAmount);
                        HashMap<Integer, ItemStack> ghost = inpInv.removeItem(toTake);
                        if (!ghost.isEmpty()) {
                            toTake.setAmount(toTake.getAmount() - ghost.get(0).getAmount());
                        }
                        blockInv.setItem(FUEL_SLOT, toTake);
                        return true;
                    }
                }
                return false;
            }
        }
    }

    return false;
}

From source file:SwiftSeleniumWeb.WebHelper.java

@SuppressWarnings("null")
public static String getCellData(String reqValue, HSSFSheet reqSheet, int rowIndex,
        HashMap<String, Object> inputHashTable) throws IOException {
    HSSFCell reqCell = null;/*from  w  ww  .  j  a  va  2 s  .co  m*/
    Object actualvalue = null;
    String req = "";
    DataFormatter fmt = new DataFormatter();
    if (inputHashTable.isEmpty() == true) {
        inputHashTable = getValueFromHashMap(reqSheet);
    }
    HSSFRow rowActual = reqSheet.getRow(rowIndex);
    if (inputHashTable.get(reqValue) == null) {
        SwiftSeleniumWeb.WebDriver.report
                .setStrMessage("Column " + reqValue + " not Found. Please Check input Sheet");
        MainController.pauseFun("Column " + reqValue + " not Found. Please Check input Sheet");
    } else {
        actualvalue = inputHashTable.get(reqValue);//rowHeader.getCell(colIndex).toString();         
        if (actualvalue != null) {
            int colIndex = Integer.parseInt(actualvalue.toString());
            reqCell = rowActual.getCell(colIndex);
            if (reqCell == null) {
                System.out.println(reqValue + " is Null");
            } else {
                int type = reqCell.getCellType();
                switch (type) {
                case HSSFCell.CELL_TYPE_BLANK:
                    req = "";
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    req = fmt.formatCellValue(reqCell);
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    req = reqCell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    req = Boolean.toString(reqCell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    req = "error";
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    req = reqCell.getCellFormula();
                    break;
                }
            }
        }

        else {
            req = reqCell.getStringCellValue();
            System.out.println("null");
        }
    }
    return req;
}