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:org.apache.jcs.auxiliary.disk.block.BlockDiskKeyStore.java

/**
 * Loads the keys from the .key file. The keys are stored individually on disk. They are added
 * one by one to an LRUMap..//www .  java2s.c o m
 * <p>
 * @throws InterruptedException
 */
protected void loadKeys() throws InterruptedException {
    if (log.isInfoEnabled()) {
        log.info(logCacheName + "Loading keys for " + keyFile.toString());
    }

    try {
        // create a key map to use.
        initKeyMap();

        HashMap keys = new HashMap();

        FileInputStream fis = new FileInputStream(keyFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ObjectInputStream ois = new ObjectInputStream(bis);
        try {
            while (true) {
                BlockDiskElementDescriptor descriptor = (BlockDiskElementDescriptor) ois.readObject();
                if (descriptor != null) {
                    keys.put(descriptor.getKey(), descriptor.getBlocks());
                }
            }
        } catch (EOFException eof) {
            // nothing
        } finally {
            ois.close();
        }

        if (!keys.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug(logCacheName + "Found " + keys.size() + " in keys file.");
            }

            keyHash.putAll(keys);

            if (log.isInfoEnabled()) {
                log.info(logCacheName + "Loaded keys from [" + fileName + "], key count: " + keyHash.size()
                        + "; up to " + maxKeySize + " will be available.");
            }
        }
    } catch (Exception e) {
        log.error(logCacheName + "Problem loading keys for file " + fileName, e);
    }
}

From source file:org.apache.usergrid.java.client.model.UsergridEntity.java

public void putProperties(@NotNull final JsonNode jsonNode) {
    HashMap<String, JsonNode> propertiesToUpdate = new HashMap<>();
    Iterator<Map.Entry<String, JsonNode>> keys = jsonNode.fields();
    while (keys.hasNext()) {
        Map.Entry<String, JsonNode> entry = keys.next();
        String key = entry.getKey();
        UsergridEntityProperties entityProperty = UsergridEntityProperties.fromString(key);
        if (entityProperty == null || entityProperty.isMutableForEntity(this)) {
            propertiesToUpdate.put(key, entry.getValue());
        }/* w w  w  . ja  v a 2s .  c  o  m*/
    }
    if (!propertiesToUpdate.isEmpty()) {
        this.updatePropertiesWithMap(propertiesToUpdate);
    }
}

From source file:org.pentaho.platform.plugin.action.jasperreports.JasperReportsComponent.java

/**
 * Runs a report.//  ww w  .j a v a  2  s . c o m
 * 
 * @return true if action was successful
 */
public boolean executeAction() {
    JasperReportAction reportAction = (JasperReportAction) getActionDefinition();

    // perform runtime validation of the output type
    String reportOutputType = reportAction.getOutputType().getStringValue();
    if (debug) {
        debug(Messages.getString("JasperReport.DEBUG_OUTPUT_TYPE", reportOutputType)); //$NON-NLS-1$
    }

    String mimeType = getMimeType(reportOutputType);
    if (mimeType == null) {
        error(Messages.getErrorString("JasperReport.ERROR_0011_OUTPUT_TYPE_INVALID")); //$NON-NLS-1$
        return false;
    }

    String extension = "." + reportOutputType; //$NON-NLS-1$

    HashSet<String> compiledReportPaths = new HashSet<String>();
    JasperReport jrreport = null;
    // Store parameters for all reports
    HashMap allReportParameters = new HashMap();

    IActionResource reportDefinition = reportAction.getReportDefinition();
    if (reportDefinition != null) {
        IActionSequenceResource resource = getResource(reportDefinition.getName());
        HashMap returnImmediately = new HashMap();

        processCurrentReport(resource, compiledReportPaths, jrreport, allReportParameters, returnImmediately,
                reportOutputType);

        if (!returnImmediately.isEmpty() && returnImmediately.containsKey(RETURN_IMMEDIATELY)) {
            return true;
        }

    } else {
        // This else statement is here to support old action sequence functionality.
        org.pentaho.actionsequence.dom.IActionSequenceResource[] actionSequenceResources = reportAction
                .getDocument().getResources();
        for (org.pentaho.actionsequence.dom.IActionSequenceResource element : actionSequenceResources) {
            IActionSequenceResource resource = getResource(element.getName());
            HashMap returnImmediately = new HashMap();
            // Compile every report
            processCurrentReport(resource, compiledReportPaths, jrreport, allReportParameters,
                    returnImmediately, reportOutputType);

            if (!returnImmediately.isEmpty() && returnImmediately.containsKey(RETURN_IMMEDIATELY)) {
                return true;
            }
        }
    }

    // Try to get the output from the action-sequence document.
    // execute the report here...
    IContentItem contentItem = null;
    OutputStream outputStream = getOutputStream(mimeType, extension, contentItem);
    if (outputStream == null) {
        error(Messages.getErrorString("JasperReport.ERROR_0013_OUTPUT_STREAM_INVALID")); //$NON-NLS-1$
        return false;
    }

    return exportReport(compiledReportPaths, allReportParameters, reportOutputType, outputStream, contentItem);
}

From source file:io.bifroest.commons.boot.BootLoaderNG.java

/**
 * Calculates the systems boot order. This is an iterative process: At
 * first, from a list with all available systems, all systems with no
 * dependencies are removed. This is repeated until the list is empty. If
 * there are systems still remaining, there is a dependency misconfiguration
 * and a CircularDependencyException is raised.
 *
 * @return A list with systems ordered by boot priority. The first element
 * needs to start first, the second after and so on.
 * @throws CircularDependencyException If two or more systems are
 * misconfigured, a circular dependency can occur. This happens e.g. if
 * system A depends on system B and system B also requires system A. This
 * cannot be resolved and an exception is thrown.
 */// www  . j av  a 2  s.co  m
private List<Subsystem<E>> getBootOrder() throws CircularDependencyException {
    HashMap<String, Subsystem<E>> bootSystems = new HashMap<>();
    HashMap<String, List<String>> systemDependencies = new HashMap<>();
    List<Subsystem<E>> result = new ArrayList<>();

    // shuffle systems to boot, so no one can forget system dependencies
    Collections.shuffle(this.systemsToBoot);

    this.systemsToBoot.stream().forEach((system) -> {
        bootSystems.put(system.getSystemIdentifier(), system);
        systemDependencies.put(system.getSystemIdentifier(), system.getRequiredSystems().stream()
                .filter(dep -> !dep.equals(system.getSystemIdentifier())).collect(Collectors.toList()));
    });
    // while there are dependencies to solve
    while (!systemDependencies.isEmpty()) {
        // Get all nodes without any dependency            
        Set<String> keys = systemDependencies.keySet();
        List<String> resolved = new ArrayList<>();
        keys.stream().forEach((key) -> {
            log.trace("Trying to resolve {}", key);
            Collection<String> dependencies = systemDependencies.get(key);
            log.trace("Found dependencies: {}", dependencies);
            if (dependencies == null || dependencies.isEmpty()) {
                log.trace("Marking {} as resolved", key);
                resolved.add(key);
            }
        });
        // if resolved is empty, we have a loop in the graph            
        if (resolved.isEmpty()) {
            String msg = "Loop in graph! This should not happen. Check your dependencies! Remaining systems: "
                    + keys.toString();
            throw new CircularDependencyException(msg, systemDependencies);
        }

        // remove systemsToBoot found from dependency graph
        resolved.stream().forEach((systemIdentifier) -> {
            systemDependencies.remove(systemIdentifier);
            result.add(bootSystems.get(systemIdentifier));
        });

        // remove dependencies
        Set<String> systemDependenciesKeys = systemDependencies.keySet();
        systemDependenciesKeys.stream().map((key) -> systemDependencies.get(key)).forEach((values) -> {
            resolved.stream().forEach((resolvedValue) -> {
                values.removeIf(v -> v.equals(resolvedValue));
            });
        });
    }
    return result;
}

From source file:helma.servlet.AbstractServletClient.java

protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws IOException {
    // check if there are any parameters before we get started
    String queryString = request.getQueryString();
    String contentType = request.getContentType();
    boolean isFormPost = "post".equals(request.getMethod().toLowerCase()) && contentType != null
            && contentType.toLowerCase().startsWith("application/x-www-form-urlencoded");

    if (queryString == null && !isFormPost) {
        return;/*from   w w  w . j  a va2s  .  c o  m*/
    }

    HashMap parameters = new HashMap();

    // Parse any query string parameters from the request
    if (queryString != null) {
        parseParameters(parameters, queryString.getBytes(), encoding, false);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, false);
            parameters.clear();
        }
    }

    // Parse any posted parameters in the input stream
    if (isFormPost) {
        int max = request.getContentLength();
        if (max > totalUploadLimit * 1024) {
            throw new IOException("Exceeded Upload limit");
        }
        int len = 0;
        byte[] buf = new byte[max];
        ServletInputStream is = request.getInputStream();

        while (len < max) {
            int next = is.read(buf, len, max - len);

            if (next < 0) {
                break;
            }

            len += next;
        }

        // is.close();
        parseParameters(parameters, buf, encoding, true);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, true);
            parameters.clear();
        }
    }
}

From source file:de.gfz_potsdam.datasync.Datasync.java

private void addContainerMembers(String parentdir, Container parent, ArrayList<VersionableResource> children)
        throws Exception {
    if (parent == null || children == null)
        return;/*from   w w w . j a va 2  s. c o m*/

    HashMap<String, VersionableResource> ids = new HashMap<String, VersionableResource>();

    for (VersionableResource child : children) {
        ids.put(child.getObjid(), child);
    }
    //do not add twice
    if (parent.getStructMap() != null) {
        for (MemberRef m : parent.getStructMap()) {
            if (ids.containsKey(m.getObjid()))
                ids.remove(m.getObjid());
        }
    }

    if (ids.isEmpty())
        return;

    DateTime r = srv.containerAddMembers(parent, ids.values());

    File dir = new File(directory + File.separator + parentdir);

    App.db.storeMapping(parentdir, parent.getObjid(), dir.lastModified(), r, SyncDB.DIRECTORY);
    log.log(Level.INFO, "added members : {0}", new Object[] { dir.getAbsoluteFile() });

}

From source file:com.wasteofplastic.beaconz.BeaconListeners.java

/**
 * Handles the event of hitting a beacon with paper or a map
 * @param event/*  w ww . j  a va  2  s  .  com*/
 */
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPaperMapUse(final PlayerInteractEvent event) {
    //getLogger().info("DEBUG: paper map " + event.getEventName());
    if (Settings.pairLinking) {
        // Not used if pair linking is used
        return;
    }
    if (!event.hasItem()) {
        return;
    }
    if (!event.getItem().getType().equals(Material.PAPER) && !event.getItem().getType().equals(Material.MAP)) {
        return;
    }
    if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
        return;
    }
    World world = event.getClickedBlock().getWorld();
    if (!world.equals(getBeaconzWorld())) {
        //getLogger().info("DEBUG: not right world");
        return;
    }
    Player player = event.getPlayer();
    // Get the player's team
    Team team = getScorecard().getTeam(player);
    if (team == null) {
        // TODO: Probably should put the player in a team
        event.setCancelled(true);
        player.sendMessage(ChatColor.RED + "You must be in a team to play in this world");
        return;
    }
    // Apply triangle effects
    applyEffects(player,
            getRegister().getTriangle(player.getLocation().getBlockX(), player.getLocation().getBlockZ()),
            team);

    // Check if the block is a beacon or the surrounding pyramid
    Block b = event.getClickedBlock();
    final BeaconObj beacon = getRegister().getBeacon(b);
    if (beacon == null) {
        //getLogger().info("DEBUG: not a beacon");
        return;
    }
    // Check the team
    if (beacon.getOwnership() == null || !beacon.getOwnership().equals(team)) {
        player.sendMessage(ChatColor.RED + "You must capture this beacon first!");
        event.setCancelled(true);
        return;
    }
    if (event.getItem().getType().equals(Material.PAPER)) {
        // Make a map!
        player.sendMessage(
                ChatColor.GREEN + "You made a beacon map! Take it to another beacon to link them up!");
        int amount = event.getItem().getAmount() - 1;
        MapView map = Bukkit.createMap(getBeaconzWorld());
        //map.setWorld(getBeaconzWorld());
        map.setCenterX(beacon.getX());
        map.setCenterZ(beacon.getZ());
        map.getRenderers().clear();
        map.addRenderer(new BeaconMap(getBeaconzPlugin()));
        event.getItem().setType(Material.MAP);
        event.getItem().setAmount(1);
        event.getItem().setDurability(map.getId());
        // 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());
        if (amount > 0) {
            HashMap<Integer, ItemStack> leftOver = player.getInventory()
                    .addItem(new ItemStack(Material.PAPER, amount));
            if (!leftOver.isEmpty()) {
                for (ItemStack stack : leftOver.values()) {
                    player.getLocation().getWorld().dropItemNaturally(player.getLocation(), stack);
                }
            }
        }
        ItemMeta meta = event.getItem().getItemMeta();
        meta.setDisplayName("Beacon map for " + beacon.getName());
        event.getItem().setItemMeta(meta);
        // Stop the beacon inventory opening
        event.setCancelled(true);
        return;
    } else {
        // Map!
        BeaconObj mappedBeacon = getRegister().getBeaconMap(event.getItem().getDurability());
        if (mappedBeacon == null) {
            // This is not a beacon map
            return;
        }
        event.setCancelled(true);
        if (Settings.linkDistance >= 0 && Settings.expDistance > 0) {
            // Check if the player has sufficient experience to link the beacons
            double distance = beacon.getLocation().distance(mappedBeacon.getLocation());
            distance -= Settings.linkDistance;
            if (distance > 0) {
                if (!testForExp(player, (int) (distance / Settings.expDistance))) {
                    player.sendMessage(
                            ChatColor.RED + "You do not have enough experience to link to this beacon!");
                    player.sendMessage(ChatColor.RED + "You can link up to "
                            + (int) (Settings.expDistance * player.getTotalExperience()) + " blocks away.");
                    player.sendMessage(ChatColor.RED + "This beacon is " + (int) distance + " blocks away.");
                    return;
                }
            }
        }
        if (linkBeacons(player, team, beacon, mappedBeacon)) {
            player.sendMessage(ChatColor.GREEN + "The map disintegrates!");
            player.setItemInHand(null);
        }
    }
}

From source file:nl.cyso.vcloud.client.vCloudClient.java

public void login(String uri, String username, String password) {
    VcloudClient.setLogLevel(Level.ALL);
    this.vcc = new VcloudClient(uri, Version.V1_5);
    try {/*from w ww .  j  a  va2s  .com*/
        this.vcc.registerScheme("https", 443, FakeSSLSocketFactory.getInstance());
    } catch (Exception e) {
        Formatter.printErrorLine("Unexpected error");
        Formatter.printStackTrace(e);
        System.exit(1);
    }

    HashMap<String, ReferenceType> organizationsMap = null;
    try {
        this.vcc.login(username, password);
        organizationsMap = this.vcc.getOrgRefsByName();
    } catch (VCloudException ve) {
        Formatter.printErrorLine("An error occurred while logging in:\n");
        Formatter.printErrorLine(ve.getLocalizedMessage());
        System.exit(1);
    }

    if (organizationsMap.isEmpty()) {
        Formatter.printErrorLine("Invalid login for user " + username);
        System.exit(1);
    }
}

From source file:com.gameanalytics.android.BatchThread.java

@SuppressWarnings("unchecked")
private void sendEvents() {
    // Get events from database
    Object[] eventLists = eventDatabase.getEvents();
    HashMap<String, EventList<DesignEvent>> designEvents = (HashMap<String, EventList<DesignEvent>>) eventLists[0];
    HashMap<String, EventList<BusinessEvent>> businessEvents = (HashMap<String, EventList<BusinessEvent>>) eventLists[1];
    HashMap<String, EventList<UserEvent>> userEvents = (HashMap<String, EventList<UserEvent>>) eventLists[2];
    HashMap<String, EventList<QualityEvent>> qualityEvents = (HashMap<String, EventList<QualityEvent>>) eventLists[3];
    HashMap<String, EventList<ErrorEvent>> errorEvents = (HashMap<String, EventList<ErrorEvent>>) eventLists[4];

    // For each game id and event array
    String eventGameKey;//from   w  w  w .j  av a 2s.  c  om
    EventList<?> eventList;
    // Convert event lists to json using GSON
    Gson gson = new Gson();
    // Send events if the list is not empty
    if (!designEvents.isEmpty()) {
        for (Entry<String, EventList<DesignEvent>> e : designEvents.entrySet()) {
            eventGameKey = e.getKey();
            eventList = e.getValue();
            if (!eventList.isEmpty()) {
                sendEventSet(gson.toJson(eventList), GameAnalytics.DESIGN, eventGameKey, eventList);
            }
        }
    } else {
        GALog.i("No design events to send.");
    }
    if (!businessEvents.isEmpty()) {
        for (Entry<String, EventList<BusinessEvent>> e : businessEvents.entrySet()) {
            eventGameKey = e.getKey();
            eventList = e.getValue();
            if (!eventList.isEmpty()) {
                sendEventSet(gson.toJson(eventList), GameAnalytics.BUSINESS, eventGameKey, eventList);
            }
        }
    } else {
        GALog.i("No business events to send.");
    }
    if (!qualityEvents.isEmpty()) {
        for (Entry<String, EventList<QualityEvent>> e : qualityEvents.entrySet()) {
            eventGameKey = e.getKey();
            eventList = e.getValue();
            if (!eventList.isEmpty()) {
                sendEventSet(gson.toJson(eventList), GameAnalytics.QUALITY, eventGameKey, eventList);
            }
        }
    } else {
        GALog.i("No quality events to send.");
    }
    if (!userEvents.isEmpty()) {
        for (Entry<String, EventList<UserEvent>> e : userEvents.entrySet()) {
            eventGameKey = e.getKey();
            eventList = e.getValue();
            if (!eventList.isEmpty()) {
                sendEventSet(gson.toJson(eventList), GameAnalytics.USER, eventGameKey, eventList);
            }
        }
    } else {
        GALog.i("No user events to send.");
    }
    if (!errorEvents.isEmpty()) {
        for (Entry<String, EventList<ErrorEvent>> e : errorEvents.entrySet()) {
            eventGameKey = e.getKey();
            eventList = e.getValue();
            if (!eventList.isEmpty()) {
                sendEventSet(gson.toJson(eventList), GameAnalytics.ERROR, eventGameKey, eventList);
            }
        }
    } else {
        GALog.i("No error events to send.");
    }
    // If there are no events to be sent then allow a new thread to be
    // started
    GameAnalytics.checkIfNoEvents();
}

From source file:structuredPredictionNLG.DatasetParser.java

/**
 *
 * @param attribute//from   w  w w. j a  va 2  s . c o m
 * @param attrValuesToBeMentioned
 * @return
 */
public String chooseNextValue(String attribute, HashSet<String> attrValuesToBeMentioned) {
    HashMap<String, Integer> relevantValues = new HashMap<>();
    attrValuesToBeMentioned.stream().forEach((attrValue) -> {
        String attr = attrValue.substring(0, attrValue.indexOf('='));
        String value = attrValue.substring(attrValue.indexOf('=') + 1);
        if (attr.equals(attribute)) {
            relevantValues.put(value, 0);
        }
    });
    if (!relevantValues.isEmpty()) {
        if (relevantValues.keySet().size() == 1) {
            for (String value : relevantValues.keySet()) {
                return value;
            }
        } else {
            String bestValue = "";
            int minIndex = Integer.MAX_VALUE;
            for (String value : relevantValues.keySet()) {
                if (value.startsWith("x")) {
                    int vI = Integer.parseInt(value.substring(1));
                    if (vI < minIndex) {
                        minIndex = vI;
                        bestValue = value;
                    }
                }
            }
            if (!bestValue.isEmpty()) {
                return bestValue;
            }
            for (ArrayList<String> mentionedValueSeq : observedAttrValueSequences) {
                boolean doesSeqContainValues = true;
                minIndex = Integer.MAX_VALUE;
                for (String value : relevantValues.keySet()) {
                    int index = mentionedValueSeq.indexOf(attribute + "=" + value);
                    if (index != -1 && index < minIndex) {
                        minIndex = index;
                        bestValue = value;
                    } else if (index == -1) {
                        doesSeqContainValues = false;
                    }
                }
                if (doesSeqContainValues) {
                    relevantValues.put(bestValue, relevantValues.get(bestValue) + 1);
                }
            }
            int max = -1;
            for (String value : relevantValues.keySet()) {
                if (relevantValues.get(value) > max) {
                    max = relevantValues.get(value);
                    bestValue = value;
                }
            }
            return bestValue;
        }
    }
    return "";
}