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.streamsets.pipeline.stage.processor.kv.redis.RedisLookupProcessor.java

@SuppressWarnings("unchecked")
private void updateRecord(LookupValue value, String outputFieldPath, Record record) throws StageException {
    switch (value.getType()) {
    case STRING://from w  ww  .  ja  v  a2 s .com
        Optional<String> string = Optional.fromNullable((String) value.getValue());
        if (Optional.fromNullable(value.getValue()).isPresent()) {
            record.set(outputFieldPath, Field.create(string.get()));
        }
        break;
    case LIST:
        List<Field> field = new ArrayList<>();
        List<String> list = (List<String>) value.getValue();
        if (!list.isEmpty()) {
            for (String element : list) {
                field.add(Field.create(element));
            }
            record.set(outputFieldPath, Field.create(field));
        }
        break;
    case HASH:
        Map<String, Field> fieldMap = new HashMap<>();
        HashMap<String, String> map = (HashMap<String, String>) value.getValue();
        if (!map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                fieldMap.put(entry.getKey(), Field.create(entry.getValue()));
            }
            record.set(outputFieldPath, Field.create(fieldMap));
        }
        break;
    case SET:
        field = new ArrayList<>();
        Set<String> set = (Set<String>) value.getValue();
        if (!set.isEmpty()) {
            for (String element : set) {
                field.add(Field.create(element));
            }
            record.set(outputFieldPath, Field.create(field));
        }
        break;
    default:
        LOG.error(Errors.REDIS_LOOKUP_04.getMessage(), value.getType().getLabel(),
                record.getHeader().getSourceId());
        throw new StageException(Errors.REDIS_LOOKUP_04, value.getType().getLabel(),
                record.getHeader().getSourceId());
    }
}

From source file:org.mifos.reports.branchreport.persistence.BranchReportPersistenceIntegrationTest.java

@Test
public void testPopulateCustomersFormedByLoanOfficerReadsSummaries() throws Exception {
    HashSet<Short> personnelIds = new HashSet<Short>();
    personnelIds.add(LOAN_OFFICER_ID_SHORT);
    HashMap staffSummariesMock = createMock(HashMap.class);
    expect(staffSummariesMock.isEmpty()).andReturn(false);
    expect(staffSummariesMock.keySet()).andReturn(personnelIds);
    replay(staffSummariesMock);//from w w  w  .j  a  va  2 s . c o  m
    branchReportPersistence.populateTotalClientsEnrolledByPersonnel(staffSummariesMock);
    verify(staffSummariesMock);
}

From source file:org.mifos.reports.branchreport.persistence.BranchReportPersistenceIntegrationTest.java

@Test
public void testPopulateCustomersEnrolledByLoanOfficerThisMonthReadsSummaries() throws Exception {
    HashSet<Short> personnelIds = new HashSet<Short>();
    personnelIds.add(LOAN_OFFICER_ID_SHORT);
    HashMap staffSummariesMock = createMock(HashMap.class);
    expect(staffSummariesMock.isEmpty()).andReturn(false);
    expect(staffSummariesMock.keySet()).andReturn(personnelIds);
    replay(staffSummariesMock);//from ww w.  j  av  a2s  . c  o m
    branchReportPersistence.populateClientsEnrolledByPersonnelThisMonth(staffSummariesMock);
    verify(staffSummariesMock);
}

From source file:org.mifos.reports.branchreport.persistence.BranchReportPersistenceIntegrationTest.java

@Test
public void testPopulateLoanArrearsAmountReadsSummaries() throws Exception {
    HashSet<Short> personnelIds = new HashSet<Short>();
    personnelIds.add(LOAN_OFFICER_ID_SHORT);
    HashMap staffSummariesMock = createMock(HashMap.class);
    expect(staffSummariesMock.isEmpty()).andReturn(false);
    expect(staffSummariesMock.keySet()).andReturn(personnelIds);
    replay(staffSummariesMock);//from ww  w. ja va 2  s. com
    branchReportPersistence.populateLoanArrearsAmountForPersonnel(staffSummariesMock, DEFAULT_CURRENCY);
    verify(staffSummariesMock);
}

From source file:org.apache.hadoop.hive.ql.parse.MapReduceCompiler.java

private void breakTaskTree(Task<? extends Serializable> task) {

    if (task instanceof ExecDriver) {
        HashMap<String, Operator<? extends OperatorDesc>> opMap = ((MapredWork) task.getWork()).getMapWork()
                .getAliasToWork();/*from   www.j av a  2  s.c  o m*/
        if (!opMap.isEmpty()) {
            for (Operator<? extends OperatorDesc> op : opMap.values()) {
                breakOperatorTree(op);
            }
        }
    } else if (task instanceof ConditionalTask) {
        List<Task<? extends Serializable>> listTasks = ((ConditionalTask) task).getListTasks();
        for (Task<? extends Serializable> tsk : listTasks) {
            breakTaskTree(tsk);
        }
    }

    if (task.getChildTasks() == null) {
        return;
    }

    for (Task<? extends Serializable> childTask : task.getChildTasks()) {
        breakTaskTree(childTask);
    }
}

From source file:de.tor.tribes.util.parser.SOSParser.java

@Override
public List<SOSRequest> parse(String pData) {
    print("Start parsing SOS request");
    List<SOSRequest> requests = new LinkedList<>();
    try {//from w  w w .  j a v a2s.  co  m
        HashMap<Tribe, SOSRequest> parsedData = parseRequests(pData);
        if (parsedData.isEmpty()) {
            print("Check short version");
            parsedData = parseRequestsShort(pData);
        } else {
            print("Got results for long version");
        }
        CollectionUtils.addAll(requests, parsedData.values());
    } catch (Exception ignored) {
    }
    return requests;
}

From source file:com.manning.androidhacks.hack017.CreateAccountActivity.java

@Override
public void processForm(Account account) {

    HashMap<String, String> errors = account.getErrors();
    String email = account.getEmail();

    if (null == email) {
        errors.put(CreateAccountAdapter.EMAIL_KEY, "E-mail is empty");
    } else if (email.toLowerCase().equals("me@my.com")) {
        errors.put(CreateAccountAdapter.EMAIL_KEY, "E-mail is already taken");
    }/*from   w ww .j av  a  2  s  . c  om*/

    if (errors.isEmpty()) {
        Toast.makeText(this, "Form ok!", Toast.LENGTH_SHORT).show();
        finish();
    } else {
        mAdapter.showErrors(account);
        mGallery.setSelection(0);
        mGalleryPosition = 0;
    }
}

From source file:org.apache.sysml.hops.codegen.SpoofCompiler.java

/**
 * Main interface of sum-product optimizer, statement block dag.
 * /*  ww w .ja  v a2  s. c  o  m*/
 * @param roots dag root nodes
 * @param recompile true if invoked during dynamic recompilation
 * @return dag root nodes of modified dag 
 */
public static ArrayList<Hop> optimize(ArrayList<Hop> roots, boolean recompile) {
    if (roots == null || roots.isEmpty())
        return roots;

    long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;
    ArrayList<Hop> ret = roots;

    try {
        //context-sensitive literal replacement (only integers during recompile)
        boolean compileLiterals = (PLAN_CACHE_POLICY == PlanCachePolicy.CONSTANT) || !recompile;

        //candidate exploration of valid partial fusion plans
        CPlanMemoTable memo = new CPlanMemoTable();
        for (Hop hop : roots)
            rExploreCPlans(hop, memo, compileLiterals);

        //candidate selection of optimal fusion plan
        memo.pruneSuboptimal(roots);

        //construct actual cplan representations
        //note: we do not use the hop visit status due to jumps over fused operators which would
        //corrupt subsequent resets, leaving partial hops dags in visited status
        HashMap<Long, Pair<Hop[], CNodeTpl>> cplans = new LinkedHashMap<>();
        HashSet<Long> visited = new HashSet<>();
        for (Hop hop : roots)
            rConstructCPlans(hop, memo, cplans, compileLiterals, visited);

        //cleanup codegen plans (remove unnecessary inputs, fix hop-cnodedata mapping,
        //remove empty templates with single cnodedata input, remove spurious lookups,
        //perform common subexpression elimination)
        cplans = cleanupCPlans(memo, cplans);

        //explain before modification
        if (LOG.isTraceEnabled() && !cplans.isEmpty()) { //existing cplans
            LOG.trace("Codegen EXPLAIN (before optimize): \n" + Explain.explainHops(roots));
        }

        //source code generation for all cplans
        HashMap<Long, Pair<Hop[], Class<?>>> clas = new HashMap<>();
        for (Entry<Long, Pair<Hop[], CNodeTpl>> cplan : cplans.entrySet()) {
            Pair<Hop[], CNodeTpl> tmp = cplan.getValue();
            Class<?> cla = planCache.getPlan(tmp.getValue());

            if (cla == null) {
                //generate java source code
                String src = tmp.getValue().codegen(false);

                //explain debug output cplans or generated source code
                if (LOG.isTraceEnabled() || DMLScript.EXPLAIN.isHopsType(recompile)) {
                    LOG.info("Codegen EXPLAIN (generated cplan for HopID: " + cplan.getKey() + ", line "
                            + tmp.getValue().getBeginLine() + ", hash=" + tmp.getValue().hashCode() + "):");
                    LOG.info(tmp.getValue().getClassname() + Explain.explainCPlan(cplan.getValue().getValue()));
                }
                if (LOG.isTraceEnabled() || DMLScript.EXPLAIN.isRuntimeType(recompile)) {
                    LOG.info("Codegen EXPLAIN (generated code for HopID: " + cplan.getKey() + ", line "
                            + tmp.getValue().getBeginLine() + ", hash=" + tmp.getValue().hashCode() + "):");
                    LOG.info(src);
                }

                //compile generated java source code
                cla = CodegenUtils.compileClass("codegen." + tmp.getValue().getClassname(), src);

                //maintain plan cache
                if (PLAN_CACHE_POLICY != PlanCachePolicy.NONE)
                    planCache.putPlan(tmp.getValue(), cla);
            } else if (DMLScript.STATISTICS) {
                Statistics.incrementCodegenOpCacheHits();
            }

            //make class available and maintain hits
            if (cla != null)
                clas.put(cplan.getKey(), new Pair<Hop[], Class<?>>(tmp.getKey(), cla));
            if (DMLScript.STATISTICS)
                Statistics.incrementCodegenOpCacheTotal();
        }

        //create modified hop dag (operator replacement and CSE)
        if (!cplans.isEmpty()) {
            //generate final hop dag
            ret = constructModifiedHopDag(roots, cplans, clas);

            //run common subexpression elimination and other rewrites
            ret = rewriteCSE.rewriteHopDAG(ret, new ProgramRewriteStatus());

            //explain after modification
            if (LOG.isTraceEnabled()) {
                LOG.trace("Codegen EXPLAIN (after optimize): \n" + Explain.explainHops(roots));
            }
        }
    } catch (Exception ex) {
        LOG.error("Codegen failed to optimize the following HOP DAG: \n" + Explain.explainHops(roots));
        throw new DMLRuntimeException(ex);
    }

    if (DMLScript.STATISTICS) {
        Statistics.incrementCodegenDAGCompile();
        Statistics.incrementCodegenCompileTime(System.nanoTime() - t0);
    }

    Hop.resetVisitStatus(roots);

    return ret;
}

From source file:com.qwazr.utils.server.InFileSessionPersistenceManager.java

private PersistentSession readSession(File sessionFile) {
    try {/* ww  w .  j  a  v  a 2  s.  co m*/
        final FileInputStream fileInputStream = new FileInputStream(sessionFile);
        try {
            final ObjectInputStream in = new ObjectInputStream(fileInputStream);
            try {
                final Date expDate = new Date(in.readLong());
                final HashMap<String, Object> sessionData = new HashMap<>();
                try {
                    for (;;)
                        readSessionAttribute(in, sessionData);
                } catch (EOFException e) {
                    ;// Ok we reached the end of the file
                }
                return sessionData.isEmpty() ? null : new PersistentSession(expDate, sessionData);
            } finally {
                IOUtils.close(in);
            }
        } finally {
            IOUtils.close(fileInputStream);
        }
    } catch (IOException e) {
        if (logger.isWarnEnabled())
            logger.warn("Cannot load sessions from " + sessionFile + " " + e.getMessage(), e);
        return null;
    }
}

From source file:com.wasteofplastic.beaconz.listeners.BeaconCaptureListener.java

/**
 * Puts a beacon map in the player's main hand
 * @param player//from  w  w  w.j a  v  a 2s  .  c  o  m
 * @param beacon
 */
@SuppressWarnings("deprecation")
private void giveBeaconMap(Player player, BeaconObj beacon) {
    // Make a map!
    player.sendMessage(ChatColor.GREEN + Lang.beaconYouHaveAMap);
    MapView map = Bukkit.createMap(getBeaconzWorld());
    //map.setWorld(getBeaconzWorld());
    map.setCenterX(beacon.getX());
    map.setCenterZ(beacon.getZ());
    map.getRenderers().clear();
    map.addRenderer(new TerritoryMapRenderer(getBeaconzPlugin()));
    map.addRenderer(new BeaconMap(getBeaconzPlugin()));
    ItemStack newMap = new ItemStack(Material.MAP);
    newMap.setDurability(map.getId());
    ItemMeta meta = newMap.getItemMeta();
    meta.setDisplayName("Beacon map for " + beacon.getName());
    newMap.setItemMeta(meta);
    // Each map is unique and the durability defines the map ID, register it
    getRegister().addBeaconMap(map.getId(), beacon);
    //getLogger().info("DEBUG: beacon id = " + beacon.getId());
    // Put map into hand
    //ItemStack inHand = player.getInventory().getItemInMainHand();
    ItemStack offHand = player.getInventory().getItemInOffHand();
    player.getInventory().setItemInOffHand(newMap);
    //player.getInventory().setItemInOffHand(inHand);
    if (offHand != null && !offHand.getType().equals(Material.AIR)) {
        HashMap<Integer, ItemStack> leftOvers = player.getInventory().addItem(offHand);
        if (!leftOvers.isEmpty()) {
            player.sendMessage(ChatColor.RED + Lang.errorInventoryFull);
            for (ItemStack item : leftOvers.values()) {
                player.getWorld().dropItem(player.getLocation(), item);
                player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1F, 0.5F);
            }
        }
    }
}