java.util.HashMap#isEmpty ( )源码实例Demo

下面列出了java.util.HashMap#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: BedwarsRel   文件: BStatsMetrics.java
@Override
protected JSONObject getChartData() {
  JSONObject data = new JSONObject();
  JSONObject values = new JSONObject();
  HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
  if (map == null || map.isEmpty()) {
    // Null = skip the chart
    return null;
  }
  for (Map.Entry<String, Integer> entry : map.entrySet()) {
    JSONArray categoryValues = new JSONArray();
    categoryValues.add(entry.getValue());
    values.put(entry.getKey(), categoryValues);
  }
  data.put("values", values);
  return data;
}
 
源代码2 项目: syncer   文件: ESRequestMapper.java
private QueryBuilder getFilter(SyncData data) {
  BoolQueryBuilder builder = boolQuery();
  HashMap<String, Object> syncBy = data.getSyncBy();
  if (syncBy.isEmpty()) {
    throw new InvalidConfigException("No data used to do sync(update/delete) filter");
  }
  for (Entry<String, Object> entry : syncBy.entrySet()) {
    String[] key = entry.getKey().split("\\.");
    if (key.length == 2) {
      builder.filter(nestedQuery(key[0], boolQuery().filter(getSingleFilter(entry)), ScoreMode.Avg));
    } else if (key.length == 1) {
      builder.filter(getSingleFilter(entry));
    } else {
      logger.error("Only support one level nested obj for the time being");
    }
  }
  return builder;
}
 
源代码3 项目: Barricade   文件: BarricadeProcessor.java
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
  try {
    HashMap<String, BarricadeResponseSet> configs = new HashMap<>();
    // Iterate over all @Barricade annotated elements
    for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(Barricade.class)) {
      Barricade barricade = annotatedElement.getAnnotation(Barricade.class);
      messager.printMessage(NOTE, "[Barricade] Processing endpoint: " + barricade.endpoint());

      List<BarricadeResponse> responses = new ArrayList<>(barricade.responses().length);
      int defaultIndex = 0;

      for (int i = 0; i < barricade.responses().length; i++) {
        Response option = barricade.responses()[i];
        responses.add(new BarricadeResponse(option));
        if (option.isDefault()) {
          defaultIndex = i;
        }
      }
      configs.put(barricade.endpoint(), new BarricadeResponseSet(responses, defaultIndex));
    }

    // This method is called multiple times, but we want to generate code only once
    if (!configs.isEmpty()) {
      generateCode(configs);
    }
  } catch (Exception e) {
    messager.printMessage(ERROR, "Couldn't process class:" + e.getMessage());
  }

  return true;
}
 
/**
 * It happends that the factory get called with properties that only contain
 * service.pid and service.factoryPid. If that happens we don't want to create
 * an engine.
 * 
 * @param properties
 * @return
 */
@SuppressWarnings("unchecked")
private boolean hasPropertiesConfiguration(Dictionary properties) {
  HashMap<Object, Object> mapProperties = new HashMap<Object, Object>(properties.size());
  for (Object key : Collections.list(properties.keys())) {
    mapProperties.put(key, properties.get(key));
  }
  mapProperties.remove(Constants.SERVICE_PID);
  mapProperties.remove("service.factoryPid");
  return !mapProperties.isEmpty();
}
 
public static ActionSelectionStrategy deserialize(String conf){
    String[] comps = conf.split(";");

    HashMap<String, String> attributes = new HashMap<String, String>();
    for(int i=0; i < comps.length; ++i){
        String comp = comps[i];
        String[] field = comp.split("=");
        if(field.length < 2) continue;
        String fieldname = field[0].trim();
        String fieldvalue = field[1].trim();

        attributes.put(fieldname, fieldvalue);
    }
    if(attributes.isEmpty()){
        attributes.put("prototype", conf);
    }

    String prototype = attributes.get("prototype");
    if(prototype.equals(GreedyActionSelectionStrategy.class.getCanonicalName())){
        return new GreedyActionSelectionStrategy();
    } else if(prototype.equals(SoftMaxActionSelectionStrategy.class.getCanonicalName())){
        return new SoftMaxActionSelectionStrategy();
    } else if(prototype.equals(EpsilonGreedyActionSelectionStrategy.class.getCanonicalName())){
        return new EpsilonGreedyActionSelectionStrategy(attributes);
    } else if(prototype.equals(GibbsSoftMaxActionSelectionStrategy.class.getCanonicalName())){
        return new GibbsSoftMaxActionSelectionStrategy();
    }

    return null;
}
 
源代码6 项目: syncer   文件: MysqlDispatcher.java
public MysqlDispatcher(HashMap<ConsumerSchemaMeta, ProducerSink> sinkHashMap,
                       AtomicReference<BinlogInfo> binlogInfo, boolean onlyUpdated) {
  consumerChannels = new ArrayList<>(sinkHashMap.size());
  this.binlogInfo = binlogInfo;
  if (sinkHashMap.isEmpty()) {
    logger.error("No dispatch info fetched: no meta info dispatcher & output sink");
    throw new InvalidConfigException("Invalid address & schema & table config");
  }
  for (Entry<ConsumerSchemaMeta, ProducerSink> entry : sinkHashMap.entrySet()) {
    logger.info("Listening {}, dispatch to {}", entry.getKey(), entry.getValue());
    consumerChannels.add(new ConsumerChannel(entry.getKey(), entry.getValue(), onlyUpdated));
  }
}
 
源代码7 项目: uyuni   文件: ProjectActionsApiController.java
/**
 * Return the JSON with the result of promoting the content project.
 * @param req the http request
 * @param res the http response
 * @param user the current user
 * @return the JSON data
 */
public static String promoteProject(Request req, Response res, User user) {
    ProjectPromoteRequest projectPromoteReq = ProjectActionsHandler.getProjectPromoteRequest(req);
    HashMap<String, String> requestErrors = ProjectActionsHandler.validateProjectPromoteRequest(projectPromoteReq);
    if (!requestErrors.isEmpty()) {
        return json(GSON, res, HttpStatus.SC_BAD_REQUEST, ResultJson.error(Arrays.asList(""), requestErrors));
    }

    String projectLabel = projectPromoteReq.getProjectLabel();
    CONTENT_MGR.promoteProject(projectLabel, projectPromoteReq.getEnvironmentPromoteLabel(), true, user);

    return ControllerApiUtils.fullProjectJsonResponse(res, projectLabel, user);
}
 
源代码8 项目: TrackRay   文件: SQLMapApp.java
@Function
public void scan(){
    String url = param.getOrDefault("url", "").toString();
    String cookie = param.getOrDefault("cookie", "").toString();
    String data = param.getOrDefault("data", "").toString();
    String level = param.getOrDefault("level", "").toString();
    String risk = param.getOrDefault("risk", "").toString();
    HashMap<String, String> map = new HashMap<>();
    if (sqlMapInner.newTask()){

        if (StringUtils.isNotEmpty(url))
            sqlMapInner.setTarget(url);

        if (StringUtils.isNotEmpty(cookie))
            sqlMapInner.setCookie(cookie);

        if (StringUtils.isNotEmpty(data))
            sqlMapInner.setData(data);

        if (StringUtils.isNotEmpty(level))
            map.put("level",level);

        if (StringUtils.isNotEmpty(risk))
            map.put("risk",risk);

        if (!map.isEmpty())
            sqlMapInner.optionSet(map);

        if (sqlMapInner.startScan()){
            write("正在扫描中");
        }else{
            write("扫描失败,请检查日志");
        }
        return;
    }else{
        write("创建任务失败");
    }
}
 
源代码9 项目: Skript   文件: Metrics.java
@SuppressWarnings("unchecked")
@Override
      protected JSONObject getChartData() {
          JSONObject data = new JSONObject();
          JSONObject values = new JSONObject();
          HashMap<String, int[]> map = getValues(new HashMap<String, int[]>());
          if (map == null || map.isEmpty()) {
              // Null = skip the chart
              return null;
          }
          boolean allSkipped = true;
          for (Map.Entry<String, int[]> entry : map.entrySet()) {
              if (entry.getValue().length == 0) {
                  continue; // Skip this invalid
              }
              allSkipped = false;
              JSONArray categoryValues = new JSONArray();
              for (int categoryValue : entry.getValue()) {
                  categoryValues.add(categoryValue);
              }
              values.put(entry.getKey(), categoryValues);
          }
          if (allSkipped) {
              // Null = skip the chart
              return null;
          }
          data.put("values", values);
          return data;
      }
 
源代码10 项目: uyuni   文件: FilterApiController.java
/**
 * Return the JSON with the result of updating a content project environemnt.
 * @param req the http request
 * @param res the http response
 * @param user the current user
 * @return the JSON data
 */
public static String updateContentFilter(Request req, Response res, User user) {
    FilterRequest updateFilterRequest = FilterHandler.getFilterRequest(req);

    HashMap<String, String> requestErrors = FilterHandler.validateFilterRequest(updateFilterRequest);
    if (!requestErrors.isEmpty()) {
        return json(GSON, res, HttpStatus.SC_BAD_REQUEST, ResultJson.error(Arrays.asList(""), requestErrors));
    }

    FilterCriteria filterCriteria = new FilterCriteria(
            FilterCriteria.Matcher.lookupByLabel(updateFilterRequest.getMatcher()),
            updateFilterRequest.getCriteriaKey(),
            updateFilterRequest.getCriteriaValue());
    CONTENT_MGR.updateFilter(
            Long.parseLong(req.params("filterId")),
            Optional.ofNullable(updateFilterRequest.getName()),
            Optional.ofNullable(updateFilterRequest.getRule()).map(ContentFilter.Rule::lookupByLabel),
            Optional.of(filterCriteria),
            user
    );

    if (!StringUtils.isEmpty(updateFilterRequest.getProjectLabel())) {
        FlashScopeHelper.flash(
                req, String.format("Filter %s updated successfully.", updateFilterRequest.getName())
        );
    }

    return ControllerApiUtils.listFiltersJsonResponse(res, user);
}
 
源代码11 项目: DDMQ   文件: MQClientInstance.java
public FindBrokerResult findBrokerAddressInAdmin(final String brokerName) {
    String brokerAddr = null;
    boolean slave = false;
    boolean found = false;

    HashMap<Long/* brokerId */, String/* address */> map = this.brokerAddrTable.get(brokerName);
    if (map != null && !map.isEmpty()) {
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            Long id = entry.getKey();
            brokerAddr = entry.getValue();
            if (brokerAddr != null) {
                found = true;
                if (MixAll.MASTER_ID == id) {
                    slave = false;
                } else {
                    slave = true;
                }
                break;

            }
        } // end of for
    }

    if (found) {
        return new FindBrokerResult(brokerAddr, slave, findBrokerVersion(brokerName, brokerAddr));
    }

    return null;
}
 
源代码12 项目: Weather-Forecast   文件: BackgroundWorker.java
@Override
protected String doInBackground() throws Exception {
    this.RefreshIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ring.gif")));

    final WeatherHttpRest doRequest = new WeatherHttpRest(entrys, DynJLabelList);

    final HashMap<DynJLabelObject, ForecastValues> ForecastMap = doRequest.HttpRestRequest();
    if (ForecastMap.isEmpty()) {
        ErrorCode = Error.LISTVALUES;
        return "";
    }
    UpdateStatus(ForecastMap);
    return "";
}
 
public byte[] getSystemTopicList() {
    TopicList topicList = new TopicList();
    try {
        try {
            this.lock.readLock().lockInterruptibly();
            for (Map.Entry<String, Set<String>> entry : clusterAddrTable.entrySet()) {
                topicList.getTopicList().add(entry.getKey());
                topicList.getTopicList().addAll(entry.getValue());
            }

            if (brokerAddrTable != null && !brokerAddrTable.isEmpty()) {
                Iterator<String> it = brokerAddrTable.keySet().iterator();
                while (it.hasNext()) {
                    BrokerData bd = brokerAddrTable.get(it.next());
                    HashMap<Long, String> brokerAddrs = bd.getBrokerAddrs();
                    if (brokerAddrs != null && !brokerAddrs.isEmpty()) {
                        Iterator<Long> it2 = brokerAddrs.keySet().iterator();
                        topicList.setBrokerAddr(brokerAddrs.get(it2.next()));
                        break;
                    }
                }
            }
        } finally {
            this.lock.readLock().unlock();
        }
    } catch (Exception e) {
        log.error("getAllTopicList Exception", e);
    }

    return topicList.encode();
}
 
源代码14 项目: cineast   文件: AudioFingerprint.java
/**
 * This method represents the last step that's executed when processing a query. A list of partial-results (DistanceElements) returned by
 * the lookup stage is processed based on some internal method and finally converted to a list of ScoreElements. The filtered list of
 * ScoreElements is returned by the feature module during retrieval.
 *
 * @param partialResults List of partial results returned by the lookup stage.
 * @param qc A ReadableQueryConfig object that contains query-related configuration parameters.
 * @return List of final results. Is supposed to be de-duplicated and the number of items should not exceed the number of items per module.
 */
@Override
protected List<ScoreElement> postprocessQuery(List<SegmentDistanceElement> partialResults, ReadableQueryConfig qc) {
    /* Prepare empty list of results. */
    final ArrayList<ScoreElement> results = new ArrayList<>();
    final HashMap<String, DistanceElement> map = new HashMap<>();

    /* Merge into map for final results; select the minimum distance. */
    for (DistanceElement result : partialResults) {
        map.merge(result.getId(), result, (d1, d2)-> {
            if (d1.getDistance() > d2.getDistance()) {
                return d2;
            } else {
                return d1;
            }
        });
    }

    /* Return immediately if no partial results are available.  */
    if (map.isEmpty()) {
      return results;
    }

    /* Prepare final results. */
    final CorrespondenceFunction fkt = qc.getCorrespondenceFunction().orElse(this.correspondence);
    map.forEach((key, value) -> results.add(value.toScore(fkt)));
    return ScoreElement.filterMaximumScores(results.stream());
}
 
源代码15 项目: DDMQ   文件: MQClientInstance.java
public String findBrokerAddressInPublish(final String brokerName) {
    HashMap<Long/* brokerId */, String/* address */> map = this.brokerAddrTable.get(brokerName);
    if (map != null && !map.isEmpty()) {
        return map.get(MixAll.MASTER_ID);
    }

    return null;
}
 
源代码16 项目: mobile-sdk-android   文件: ImageService.java
public void registerImageReceiver(ImageReceiver imageReceiver, HashMap<String, String> imageUrlMap) {
    if (imageReceiver != null && imageUrlMap != null && !imageUrlMap.isEmpty()) {
        this.imageReceiver = imageReceiver;
        this.imageUrlMap = imageUrlMap;
    }
}
 
源代码17 项目: ankush   文件: MonitoringManager.java
/**
 * Save Technology Service Status.
 * 
 * @param nodeId
 * @param agentServiceStatus
 */
public boolean saveTecnologyServiceStatus(Long nodeId,
		HashMap<String, Map<String, Boolean>> agentServiceStatus) {
	boolean status = true;
	try {

		// getting the node object.
		Node node = nodeManager.get(nodeId);

		// get cluster from nodedId
		GenericManager<Cluster, Long> clusterManager = AppStoreWrapper
				.getManager(Constant.Manager.CLUSTER, Cluster.class);

		// Return if not is not in deployed state
		if (clusterManager
				.get(node.getClusterId())
				.getState()
				.equalsIgnoreCase(
						Constant.Cluster.State.REMOVING.toString())
				|| !node.getState().equalsIgnoreCase(
						Constant.Node.State.DEPLOYED.toString())) {
			LOG.error("Cann't save node service status as Cluster or node State is not Deployed.");
			status = false;
		} else {

			// Get the db node monitoring info
			NodeMonitoring nodeMonitoring = monitoringManager
					.getByPropertyValueGuarded(NODE_ID, nodeId);

			// if null create the new node monitoring obj.
			if (nodeMonitoring == null) {
				nodeMonitoring = new NodeMonitoring();
				// Set initial node monitoring data
				nodeMonitoring.setNodeId(nodeId);
				// set service status.
				nodeMonitoring
						.setTechnologyServiceStatus(new HashMap<String, Map<String, Boolean>>());
			}

			// Update service into database if it is not empty
			if (!agentServiceStatus.isEmpty()) {

				Map<String, Map<String, Boolean>> serviceStatus = nodeMonitoring
						.getTechnologyServiceStatus();

				if (serviceStatus == null) {
					serviceStatus = new HashMap<String, Map<String, Boolean>>();
				}

				for (String key : agentServiceStatus.keySet()) {
					if (serviceStatus.containsKey(key)) {
						serviceStatus.get(key).putAll(
								agentServiceStatus.get(key));
					} else {
						serviceStatus.put(key, agentServiceStatus.get(key));
					}
				}
				// set service status.
				nodeMonitoring
						.setTechnologyServiceStatus((HashMap<String, Map<String, Boolean>>) serviceStatus);

				// Set service status into service table
				DBServiceManager.getManager().setServicesStatus(
						node.getClusterId(), node.getPublicIp(),
						agentServiceStatus);
			}

			// Set monitoring info in node monitoring info.
			nodeMonitoring.setUpdateTime(new Date());

			// Saving node monitoring info in database.
			nodeMonitoring = monitoringManager.save(nodeMonitoring);

			DBEventManager eventManager = new DBEventManager();
			eventManager.checkAlertsForService(node.getPublicIp(),
					node.getClusterId(), agentServiceStatus);
		}
	} catch (Exception e) {
		// Setting log error.
		LOG.error("Unable to save node service status against nodeId : "
				+ nodeId, e);
		status = false;
	}
	return status;
}
 
源代码18 项目: Telegram   文件: PhotoAlbumPickerActivity.java
private void sendSelectedPhotos(HashMap<Object, Object> photos, ArrayList<Object> order, boolean notify, int scheduleDate) {
    if (photos.isEmpty() || delegate == null || sendPressed) {
        return;
    }
    sendPressed = true;

    ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>();
    for (int a = 0; a < order.size(); a++) {
        Object object = photos.get(order.get(a));
        SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
        media.add(info);
        if (object instanceof MediaController.PhotoEntry) {
            MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object;
            if (photoEntry.imagePath != null) {
                info.path = photoEntry.imagePath;
            } else {
                info.path = photoEntry.path;
            }
            info.thumbPath = photoEntry.thumbPath;
            info.videoEditedInfo = photoEntry.editedInfo;
            info.isVideo = photoEntry.isVideo;
            info.caption = photoEntry.caption != null ? photoEntry.caption.toString() : null;
            info.entities = photoEntry.entities;
            info.masks = photoEntry.stickers;
            info.ttl = photoEntry.ttl;
        } else if (object instanceof MediaController.SearchImage) {
            MediaController.SearchImage searchImage = (MediaController.SearchImage) object;
            if (searchImage.imagePath != null) {
                info.path = searchImage.imagePath;
            } else {
                info.searchImage = searchImage;
            }
            info.thumbPath = searchImage.thumbPath;
            info.videoEditedInfo = searchImage.editedInfo;
            info.caption = searchImage.caption != null ? searchImage.caption.toString() : null;
            info.entities = searchImage.entities;
            info.masks = searchImage.stickers;
            info.ttl = searchImage.ttl;
            if (searchImage.inlineResult != null && searchImage.type == 1) {
                info.inlineResult = searchImage.inlineResult;
                info.params = searchImage.params;
            }

            searchImage.date = (int) (System.currentTimeMillis() / 1000);
        }
    }

    delegate.didSelectPhotos(media, notify, scheduleDate);
}
 
源代码19 项目: qpid-broker-j   文件: AbstractLinkEndpoint.java
private Attach handleOversizedUnsettledMapIfNecessary(final Attach attachToSend)
{
    final AMQPDescribedTypeRegistry describedTypeRegistry = getSession().getConnection().getDescribedTypeRegistry();
    final ValueWriter<Attach> valueWriter = describedTypeRegistry.getValueWriter(attachToSend);
    if (valueWriter.getEncodedSize() + 8 > getSession().getConnection().getMaxFrameSize())
    {
        _localIncompleteUnsettled = true;
        attachToSend.setIncompleteUnsettled(true);
        final int targetSize = getSession().getConnection().getMaxFrameSize();
        int lowIndex = 0;
        Map<Binary, DeliveryState> localUnsettledMap = attachToSend.getUnsettled();
        if (localUnsettledMap == null)
        {
            localUnsettledMap = Collections.emptyMap();
        }
        int highIndex = localUnsettledMap.size();
        int currentIndex = (highIndex - lowIndex) / 2;
        int oldIndex;
        HashMap<Binary, DeliveryState> unsettledMap = null;
        int totalSize;
        do
        {
            HashMap<Binary, DeliveryState> partialUnsettledMap = new HashMap<>(currentIndex);
            final Iterator<Map.Entry<Binary, DeliveryState>> iterator = localUnsettledMap.entrySet().iterator();
            for (int i = 0; i < currentIndex; ++i)
            {
                final Map.Entry<Binary, DeliveryState> entry = iterator.next();
                partialUnsettledMap.put(entry.getKey(), entry.getValue());
            }
            attachToSend.setUnsettled(partialUnsettledMap);
            totalSize = describedTypeRegistry.getValueWriter(attachToSend).getEncodedSize() + FRAME_HEADER_SIZE;
            if (totalSize > targetSize)
            {
                highIndex = currentIndex;
            }
            else if (totalSize < targetSize)
            {
                lowIndex = currentIndex;
                unsettledMap = partialUnsettledMap;
            }
            else
            {
                lowIndex = highIndex = currentIndex;
                unsettledMap = partialUnsettledMap;
            }

            oldIndex = currentIndex;
            currentIndex = lowIndex + (highIndex - lowIndex) / 2;
        }
        while (oldIndex != currentIndex);

        if (unsettledMap == null || unsettledMap.isEmpty())
        {
            final End endWithError = new End();
            endWithError.setError(new Error(AmqpError.FRAME_SIZE_TOO_SMALL, "Cannot fit a single unsettled delivery into Attach frame."));
            getSession().end(endWithError);
        }

        attachToSend.setUnsettled(unsettledMap);
    }
    else
    {
        _localIncompleteUnsettled = false;
    }
    return attachToSend;
}
 
源代码20 项目: example   文件: Card.java
/**
 * Remove ClickListener from a specif area
 * </p>
 * You can use one of these values:
 * {@link Card#CLICK_LISTENER_ALL_VIEW}
 * {@link Card#CLICK_LISTENER_HEADER_VIEW}
 * {@link Card#CLICK_LISTENER_THUMBNAIL_VIEW}
 * {@link Card#CLICK_LISTENER_CONTENT_VIEW}
 *
 *
 * @param area
 */
public void removePartialOnClickListener(int area) {

    HashMap multipleOnClickListener = getMultipleOnClickListener();
    multipleOnClickListener.remove(area);

    if (mOnClickListener == null && multipleOnClickListener.isEmpty())
        mIsClickable = false;
}