Java Code Examples for java.util.Map.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: letv   File: o.java   View Source Code Vote up 6 votes
private boolean a(Map<String, Object> map) {
    if (map == null || map.isEmpty()) {
        bv.f("map is null or empty in onEvent");
        return false;
    }
    for (Entry entry : map.entrySet()) {
        if (!a((String) entry.getKey())) {
            return false;
        }
        if (entry.getValue() == null) {
            return false;
        }
        if ((entry.getValue() instanceof String) && !b(entry.getValue().toString())) {
            return false;
        }
    }
    return true;
}
 
Example 2
Project: TextEmoji   File: HttpRequest.java   View Source Code Vote up 6 votes
/**
 * Append given map as query parameters to the base URL
 * <p>
 * Each map entry's key will be a parameter name and the value's
 * {@link Object#toString()} will be the parameter value.
 *
 * @param url
 * @param params
 * @return URL with appended query params
 */
public static String append(final CharSequence url, final Map<?, ?> params) {
  final String baseUrl = url.toString();
  if (params == null || params.isEmpty())
    return baseUrl;

  final StringBuilder result = new StringBuilder(baseUrl);

  addPathSeparator(baseUrl, result);
  addParamPrefix(baseUrl, result);

  Entry<?, ?> entry;
  Iterator<?> iterator = params.entrySet().iterator();
  entry = (Entry<?, ?>) iterator.next();
  addParam(entry.getKey().toString(), entry.getValue(), result);

  while (iterator.hasNext()) {
    result.append('&');
    entry = (Entry<?, ?>) iterator.next();
    addParam(entry.getKey().toString(), entry.getValue(), result);
  }

  return result.toString();
}
 
Example 3
Project: hashsdn-controller   File: RpcRegistry.java   View Source Code Vote up 6 votes
@Override
protected void onBucketsUpdated(final Map<Address, Bucket<RoutingTable>> buckets) {
    final Map<Address, Optional<RemoteRpcEndpoint>> endpoints = new HashMap<>(buckets.size());

    for (Entry<Address, Bucket<RoutingTable>> e : buckets.entrySet()) {
        final RoutingTable table = e.getValue().getData();

        final Collection<DOMRpcIdentifier> rpcs = table.getRoutes();
        endpoints.put(e.getKey(), rpcs.isEmpty() ? Optional.empty()
                : Optional.of(new RemoteRpcEndpoint(table.getRpcInvoker(), rpcs)));
    }

    if (!endpoints.isEmpty()) {
        rpcRegistrar.tell(new UpdateRemoteEndpoints(endpoints), ActorRef.noSender());
    }
}
 
Example 4
Project: cf-mta-deploy-service   File: CleanUpJob.java   View Source Code Vote up 6 votes
private Map<String, List<String>> getSpaceToFileIds(Map<String, List<String>> spaceToProcessIds,
    Map<String, String> processIdToAppArchiveId) {
    if (spaceToProcessIds.isEmpty()) {
        return Collections.emptyMap();
    }
    Map<String, List<String>> spaceToFileIds = new HashMap<String, List<String>>();
    for (String space : spaceToProcessIds.keySet()) {
        if (spaceToProcessIds.get(space) == null) {
            continue;
        }
        List<String> fileIds = new ArrayList<String>();
        for (String processId : spaceToProcessIds.get(space)) {
            if (processIdToAppArchiveId.containsKey(processId)) {
                fileIds.add(processIdToAppArchiveId.get(processId));
            }
        }
        spaceToFileIds.put(space, fileIds);
    }
    return spaceToFileIds;
}
 
Example 5
Project: loom   File: FibreIntrospectionUtils.java   View Source Code Vote up 6 votes
protected static <T> PropertyResult<T> getItemProperty(final String propertyName, final Fibre fibre,
        final OperationContext context) {

    T mappedValue = (T) ((Item) fibre).getPropertyValueForName(propertyName);
    if (mappedValue != null) {
        return new PropertyResult<T>(true, mappedValue);
    }

    Map<String, Item> relatedItemsMap = ((Item) fibre).getConnectedRelationships().get(propertyName);

    if (relatedItemsMap == null) {
        return new PropertyResult<T>(false, null); // Not a known relationship

    }
    if (relatedItemsMap.isEmpty()) {
        return new PropertyResult<T>(true, null); // No relationships
    }

    T readValue = (relatedItemsMap.size() == 1) ? (T) relatedItemsMap.values().iterator().next() : // return
                                                                                                   // the
                                                                                                   // related
                                                                                                   // Item
            (T) relatedItemsMap.values(); // return the collection of related Items

    return new PropertyResult<T>(true, readValue);
}
 
Example 6
Project: uavstack   File: GrafanaHttpCallBack.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public GrafanaHttpCallBack(Map _params, CountDownLatch latch) {
    if (null != _params && !_params.isEmpty()) {
        this.params.putAll(_params);
    }
    this.latch = latch;
}
 
Example 7
Project: Equella   File: AbstractEntityEditor.java   View Source Code Vote up 5 votes
private boolean validatePrivate(SectionInfo info, EntityEditingSession<B, E> session)
{
	final Map<String, Object> errors = session.getValidationErrors();
	errors.clear();

	final LanguageBundleBean bundle = title.getLanguageBundle(info);
	if( LangUtils.isEmpty(bundle) )
	{
		errors.put(KEY_ERROR_TITLE, getTitleMandatoryErrorLabel().getText());
	}

	validate(info, session);
	return errors.isEmpty();
}
 
Example 8
Project: lams   File: DictionaryCompoundWordTokenFilterFactory.java   View Source Code Vote up 5 votes
/** Creates a new DictionaryCompoundWordTokenFilterFactory */
public DictionaryCompoundWordTokenFilterFactory(Map<String, String> args) {
  super(args);
  assureMatchVersion();
  dictFile = require(args, "dictionary");
  minWordSize = getInt(args, "minWordSize", CompoundWordTokenFilterBase.DEFAULT_MIN_WORD_SIZE);
  minSubwordSize = getInt(args, "minSubwordSize", CompoundWordTokenFilterBase.DEFAULT_MIN_SUBWORD_SIZE);
  maxSubwordSize = getInt(args, "maxSubwordSize", CompoundWordTokenFilterBase.DEFAULT_MAX_SUBWORD_SIZE);
  onlyLongestMatch = getBoolean(args, "onlyLongestMatch", true);
  if (!args.isEmpty()) {
    throw new IllegalArgumentException("Unknown parameters: " + args);
  }
}
 
Example 9
Project: sstable-adaptor   File: CompressionParams.java   View Source Code Vote up 5 votes
public static CompressionParams fromMap(Map<String, String> opts)
{
    Map<String, String> options = copyOptions(opts);

    String sstableCompressionClass;

    if (!opts.isEmpty() && isEnabled(opts) && !containsSstableCompressionClass(opts))
        throw new ConfigurationException(format("Missing sub-option '%s' for the 'compression' option.", CLASS));

    if (!removeEnabled(options))
    {
        sstableCompressionClass = null;

        if (!options.isEmpty())
            throw new ConfigurationException(format("If the '%s' option is set to false no other options must be specified", ENABLED));
    }
    else
    {
        sstableCompressionClass = removeSstableCompressionClass(options);
    }

    Integer chunkLength = removeChunkLength(options);

    CompressionParams cp = new CompressionParams(sstableCompressionClass, chunkLength, options);
    cp.validate();

    return cp;
}
 
Example 10
Project: Backmemed   File: ModelBlockDefinition.java   View Source Code Vote up 5 votes
public ModelBlockDefinition deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
    JsonObject jsonobject = p_deserialize_1_.getAsJsonObject();
    Map<String, VariantList> map = this.parseMapVariants(p_deserialize_3_, jsonobject);
    Multipart multipart = this.parseMultipart(p_deserialize_3_, jsonobject);

    if (!map.isEmpty() || multipart != null && !multipart.getVariants().isEmpty())
    {
        return new ModelBlockDefinition(map, multipart);
    }
    else
    {
        throw new JsonParseException("Neither \'variants\' nor \'multipart\' found");
    }
}
 
Example 11
Project: lams   File: HyphenatedWordsFilterFactory.java   View Source Code Vote up 5 votes
/** Creates a new HyphenatedWordsFilterFactory */
public HyphenatedWordsFilterFactory(Map<String,String> args) {
  super(args);
  if (!args.isEmpty()) {
    throw new IllegalArgumentException("Unknown parameters: " + args);
  }
}
 
Example 12
Project: powsybl-core   File: CIMModel.java   View Source Code Vote up 5 votes
/**
 * Utility to properly delete a SvTapStep instance given its id
 *
 * @param id
 *            Id of the instance to delete
 * @return a boolean indicating if the instance has been correctly found
 *         and deleted
 */
public boolean deleteSvTapStep(final String id) {

    if (subsetsInstances.containsKey(
            Subset.StateVariables)) {
        Map<String, CIMInstance> instances = subsetsInstances.get(
                Subset.StateVariables);

        if (instances.containsKey(id)) {
            // The instance is being deleted
            LOGGER.debug("The instance '" + id + "' is being deleted");
            subsetsInstances
                    .get(Subset.StateVariables)
                    .remove(id);
            if (instances.isEmpty()) {
                // If there is no more class belonging to that
                // subset, we unload it
                setUnloaded(Subset.Equipment);
                // Are we back in a "merged" state ?
                this.currentSubsetSet = this.loadedSubsets.isEmpty();
            }

        }

        // We clear among the "id_SvTapStep" map
        id_SvTapStep.remove(id);

        // We clear among the "allinstances" map
        allInstances.remove(id);
        return true;
    }

    return false;
}
 
Example 13
Project: sstore-soft   File: CatalogUtil.java   View Source Code Vote up 5 votes
/**
 * Get a mapping of sites for each host. We have to return the Site objects
 * in order to get the Partition handle that we want
 * 
 * @return
 */
public static synchronized Map<Host, Set<Site>> getSitesPerHost(CatalogType catalog_item) {
    final CatalogUtil.Cache cache = CatalogUtil.getCatalogCache(catalog_item);
    final Map<Host, Set<Site>> sites = cache.HOST_SITES;

    if (sites.isEmpty()) {
        // Sort them by site ids
        final Comparator<Site> comparator = new Comparator<Site>() {
            @Override
            public int compare(Site o1, Site o2) {
                return (o1.getId() - o2.getId());
            }
        };

        Cluster catalog_clus = CatalogUtil.getCluster(catalog_item);
        for (Site catalog_site : catalog_clus.getSites()) {
            Host catalog_host = catalog_site.getHost();
            if (!sites.containsKey(catalog_host)) {
                sites.put(catalog_host, new TreeSet<Site>(comparator));
            }
            sites.get(catalog_host).add(catalog_site);
            if (debug.val)
                LOG.debug(catalog_host + " => " + catalog_site);
        } // FOR
        assert (sites.size() == catalog_clus.getHosts().size());
        if (debug.val)
            LOG.debug("HOST SITES: " + sites);
    }
    return (sites);
}
 
Example 14
Project: springboot-shiro-cas-mybatis   File: CachingPrincipalAttributesRepository.java   View Source Code Vote up 5 votes
/**
 * Set/add the received attributes into the cache.
 * @param id the principal id that controls the grouping of the attributes in the cache.
 * @param attributes principal attributes to add to the cache
 */
private void addPrincipalAttributesIntoCache(final String id, final Map<String, Object> attributes) {
    synchronized (this.cache) {
        if (attributes.isEmpty()) {

            this.cache.remove(id);
            LOGGER.debug("No attributes are provided, so removed principal id [{}] from the cache", id);
        } else {
            this.cache.put(id, attributes);
            LOGGER.debug("Cached [{}] attributes for the principal id [{}]", attributes.size(), id);
        }
    }
}
 
Example 15
Project: scoold   File: ScooldUtils.java   View Source Code Vote up 5 votes
public Map<String, String> getLang(Locale currentLocale) {
	Map<String, String> lang = langutils.readLanguage(currentLocale.getLanguage());
	if (lang == null || lang.isEmpty()) {
		lang = langutils.getDefaultLanguage();
	}
	return lang;
}
 
Example 16
Project: xm-ms-entity   File: XmGroovyExecutionStrategy.java   View Source Code Vote up 5 votes
@Override
public Object executeLepResource(UrlLepResourceKey compositeResourceKey,
                                 LepMethod method,
                                 LepManagerService managerService,
                                 Supplier<GroovyScriptRunner> resourceExecutorSupplier) throws LepInvocationCauseException {

    Map<XmLepResourceSubType, UrlLepResourceKey> atomicResourceKeys = getAvailableAtomicResourceKeys(
        compositeResourceKey, managerService);

    // validate resource sub type combinations
    XmLepScriptRules.validateScriptsCombination(atomicResourceKeys.keySet(),
                                                method,
                                                compositeResourceKey);

    if (atomicResourceKeys.isEmpty()) {
        // target method execution case
        return onNoScripts(compositeResourceKey, method);
    } else if (atomicResourceKeys.containsKey(AROUND)) {
        // AROUND script call case
        return onAroundScript(compositeResourceKey, atomicResourceKeys, method, managerService,
                              resourceExecutorSupplier);
    } else {
        // BEFORE and/or TENANT and/or DEFAULT and/or AFTER script call case
        return onWithoutAroundScript(compositeResourceKey, atomicResourceKeys, method,
                                     managerService, resourceExecutorSupplier);
    }
}
 
Example 17
Project: HueSense   File: LanComm.java   View Source Code Vote up 5 votes
private void updatePingSensor() {
    Map<String, Integer> values = new HashMap<>();
    synchronized (pingDevices) {
        for (NetworkDevice dev : pingDevices) {
            try {
                values.put(dev.toString(), pingDevice(dev));
            } catch (IOException ex) {
                LOG.error("Error pinging " + dev);
            }
        }
    }
    if (!values.isEmpty()) {
        sensor.updateSensor(values);
    }
}
 
Example 18
Project: elasticsearch_my   File: TransportSearchAction.java   View Source Code Vote up 5 votes
@Override
protected void doExecute(Task task, SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
    // pure paranoia if time goes backwards we are at least positive
    final long startTimeInMillis = Math.max(0, System.currentTimeMillis());
    final String[] localIndices;
    final Map<String, List<String>> remoteClusterIndices;
    final ClusterState clusterState = clusterService.state();
    if (remoteClusterService.isCrossClusterSearchEnabled()) {
        remoteClusterIndices = remoteClusterService.groupClusterIndices( searchRequest.indices(), // empty string is not allowed
            idx -> indexNameExpressionResolver.hasIndexOrAlias(idx, clusterState));
        List<String> remove = remoteClusterIndices.remove(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY);
        localIndices = remove == null ? Strings.EMPTY_ARRAY : remove.toArray(new String[remove.size()]);
    } else {
        remoteClusterIndices = Collections.emptyMap();
        localIndices = searchRequest.indices();
    }

    if (remoteClusterIndices.isEmpty()) {
        executeSearch((SearchTask)task, startTimeInMillis, searchRequest, localIndices, Collections.emptyList(),
            (nodeId) -> null, clusterState, Collections.emptyMap(), listener);
    } else {
        remoteClusterService.collectSearchShards(searchRequest, remoteClusterIndices,
            ActionListener.wrap((searchShardsResponses) -> {
                List<ShardIterator> remoteShardIterators = new ArrayList<>();
                Map<String, AliasFilter> remoteAliasFilters = new HashMap<>();
                Function<String, Transport.Connection> connectionFunction = remoteClusterService.processRemoteShards(
                    searchShardsResponses, remoteShardIterators, remoteAliasFilters);
                executeSearch((SearchTask)task, startTimeInMillis, searchRequest, localIndices, remoteShardIterators,
                    connectionFunction, clusterState, remoteAliasFilters, listener);
            }, listener::onFailure));
    }
}
 
Example 19
Project: HL4A   File: Parser.java   View Source Code Vote up 4 votes
private AstNode arrowFunction(AstNode params) throws IOException {
    int baseLineno = ts.lineno;  // line number where source starts
    int functionSourceStart = params != null ? params.getPosition() : -1;  // start of "function" kwd

    FunctionNode fnNode = new FunctionNode(functionSourceStart);
    fnNode.setFunctionType(FunctionNode.ARROW_FUNCTION);
    fnNode.setJsDocNode(getAndResetJsDoc());

    // Would prefer not to call createDestructuringAssignment until codegen,
    // but the symbol definitions have to happen now, before body is parsed.
    Map<String, Node> destructuring = new HashMap<String, Node>();
    Set<String> paramNames = new HashSet<String>();

    PerFunctionVariables savedVars = new PerFunctionVariables(fnNode);
    try {
        if (params instanceof ParenthesizedExpression) {
            fnNode.setParens(0, params.getLength());
            AstNode p = ((ParenthesizedExpression)params).getExpression();
            if (!(p instanceof EmptyExpression)) {
                arrowFunctionParams(fnNode, p, destructuring, paramNames);
            }
        } else {
            arrowFunctionParams(fnNode, params, destructuring, paramNames);
        }

        if (!destructuring.isEmpty()) {
            Node destructuringNode = new Node(Token.COMMA);
            // Add assignment helper for each destructuring parameter
            for (Map.Entry<String, Node> param: destructuring.entrySet()) {
                Node assign = createDestructuringAssignment(Token.VAR,
                                                            param.getValue(), createName(param.getKey()));
                destructuringNode.addChildToBack(assign);

            }
            fnNode.putProp(Node.DESTRUCTURING_PARAMS, destructuringNode);
        }
            
        fnNode.setBody(parseFunctionBody(FunctionNode.ARROW_FUNCTION, fnNode));
        fnNode.setEncodedSourceBounds(functionSourceStart, ts.tokenEnd);
        fnNode.setLength(ts.tokenEnd - functionSourceStart);
    } finally {
        savedVars.restore();
    }

    if (fnNode.isGenerator()) {
        reportError("msg.arrowfunction.generator");
        return makeErrorNode();
    }

    fnNode.setSourceName(sourceURI);
    fnNode.setBaseLineno(baseLineno);
    fnNode.setEndLineno(ts.lineno);

    return fnNode;
}
 
Example 20
Project: xitk   File: CollectionUtil.java   View Source Code Vote up 4 votes
public static boolean isNonEmpty(Map<?, ?> map) {
    return map != null && !map.isEmpty();
}