Java Code Examples for org.apache.commons.collections4.MapUtils#isNotEmpty()

The following examples show how to use org.apache.commons.collections4.MapUtils#isNotEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RouterProcessor.java    From DDComponentForAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * generate HostRouterTable.txt
 */
private void generateRouterTable() {
    String fileName = RouteUtils.genRouterTable(host);
    if (FileUtils.createFile(fileName)) {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("auto generated, do not change !!!! \n\n");
        stringBuilder.append("HOST : " + host + "\n\n");

        for (Node node : routerNodes) {
            stringBuilder.append(node.getDesc() + "\n");
            stringBuilder.append(node.getPath() + "\n");
            Map<String, String> paramsType = node.getParamsDesc();
            if (MapUtils.isNotEmpty(paramsType)) {
                for (Map.Entry<String, String> types : paramsType.entrySet()) {
                    stringBuilder.append(types.getKey() + ":" + types.getValue() + "\n");
                }
            }
            stringBuilder.append("\n");
        }
        FileUtils.writeStringToFile(fileName, stringBuilder.toString(), false);
    }
}
 
Example 2
Source File: SystemSettingsActor.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
private void getAllSystemSettings() {
  ProjectLogger.log("SystemSettingsActor: getAllSystemSettings called", LoggerEnum.DEBUG.name());
  Map<String, String> systemSettings = DataCacheHandler.getConfigSettings();
  Response response = new Response();
  List<SystemSetting> allSystemSettings = null;
  if (MapUtils.isNotEmpty(systemSettings)) {
    allSystemSettings = new ArrayList<>();
    for (Map.Entry setting : systemSettings.entrySet()) {
      allSystemSettings.add(
          new SystemSetting(
              (String) setting.getKey(), (String) setting.getKey(), (String) setting.getValue()));
    }
  } else {
    allSystemSettings = systemSettingDaoImpl.readAll();
  }
  response.put(JsonKey.RESPONSE, allSystemSettings);
  sender().tell(response, self());
}
 
Example 3
Source File: WrapperTransModel.java    From jvm-sandbox-repeater with Apache License 2.0 6 votes vote down vote up
public static WrapperTransModel build(HttpServletRequest request) {
    Map<String, String> headers = new HashMap<String, String>(2);
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames != null && headerNames.hasMoreElements()) {
        String header = headerNames.nextElement();
        headers.put(header, request.getHeader(header));
    }
    Map<String, String[]> parameterMap = request.getParameterMap();
    Map<String, String[]> parameterMapHolder = new HashMap<String, String[]>(2);
    if (MapUtils.isNotEmpty(parameterMap)) {
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            parameterMapHolder.put(entry.getKey(), entry.getValue());
        }
    }
    return new WrapperTransModel(
            request.getRequestURL().toString(),
            request.getRequestURI(),
            request.getLocalPort(),
            request.getMethod(),
            request.getContentType(),
            headers,
            parameterMapHolder
    );
}
 
Example 4
Source File: RouterProcessor.java    From JIMU with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    routerNodes = new ArrayList<>();

    mFiler = processingEnv.getFiler();
    types = processingEnv.getTypeUtils();
    elements = processingEnv.getElementUtils();
    typeUtils = new TypeUtils(types, elements);

    type_String = elements.getTypeElement("java.lang.String").asType();

    logger = new Logger(processingEnv.getMessager());

    Map<String, String> options = processingEnv.getOptions();
    if (MapUtils.isNotEmpty(options)) {
        host = options.get(KEY_HOST_NAME);
        logger.info(">>> host is " + host + " <<<");
    }
    if (host == null || host.equals("")) {
        host = "default";
    }
    logger.info(">>> RouteProcessor init. <<<");
}
 
Example 5
Source File: BidResponseCreator.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
private Map<String, List<ExtBidderError>> toExtBidderErrors(List<BidderResponse> bidderResponses,
                                                            BidRequest bidRequest, CacheServiceResult cacheResult,
                                                            VideoStoredDataResult videoStoredDataResult,
                                                            Map<String, List<ExtBidderError>> bidErrors) {
    final Map<String, List<ExtBidderError>> errors = new HashMap<>();

    errors.putAll(extractBidderErrors(bidderResponses));
    errors.putAll(extractDeprecatedBiddersErrors(bidRequest));
    errors.putAll(extractPrebidErrors(cacheResult, videoStoredDataResult));

    if (MapUtils.isNotEmpty(bidErrors)) {
        addBidErrors(errors, bidErrors);
    }

    return errors.isEmpty() ? null : errors;
}
 
Example 6
Source File: TopicServiceImpl.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void addPProxy(String host, List<TopicConf> confList) throws Exception {
    String ipPort = HostUtils.getIpPortFromHost(host, ZKV4ConfigServiceImpl.DEFAULT_PPROXY_PORT);
    Set<Long> clusterIds = Sets.newHashSet();
    for (TopicConf topicConf : confList) {
        if (topicConf.getTopicConfConfig() != null && MapUtils.isNotEmpty(topicConf.getTopicConfConfig().getProxies())) {
            Map<String, Set<String>> proxyMap = topicConf.getTopicConfConfig().getProxies();
            for (Set<String> ipLists : proxyMap.values()) {
                if (ipLists.contains(ipPort)) {
                    continue;
                }

                ipLists.add(ipPort);
                clusterIds.add(topicConf.getClusterId());
                topicConfService.updateByPrimaryKey(topicConf);
                pushV4ZkInfo(topicConf.getTopicId(), null);

                LOGGER.info("add pproxy {} success, topicConfId={}, topic={}", ipPort, topicConf.getId(), topicConf.getTopicName());
            }
        }
    }
    if (CollectionUtils.isNotEmpty(clusterIds)) {
        zkv4ConfigService.updatePProxyConfigByClusterId("addPProxy", clusterIds);
    }
}
 
Example 7
Source File: ScreenNavigationHandler.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected Screen createEditor(WindowInfo windowInfo, String screenRoute, NavigationState requestedState, AppUI ui) {
    Map<String, Object> options = createEditorScreenOptions(windowInfo, requestedState, ui);

    if (MapUtils.isEmpty(options)) {
        log.info("Unable to load entity for editor: '{}'. " +
                "Subscribe for 'UrlParamsChangedEvent' to obtain its serialized id", windowInfo.getId());
    }

    Screen editor;
    OpenMode openMode = getScreenOpenMode(requestedState.getNestedRoute(), screenRoute, ui);

    if (isLegacyScreen(windowInfo.getControllerClass())) {
        editor = ui.getScreens().create(windowInfo.getId(), openMode, new MapScreenOptions(options));
    } else {
        editor = ui.getScreens().create(windowInfo.getId(), openMode);
    }

    if (MapUtils.isNotEmpty(options)) {
        Entity entity = (Entity) options.get(WindowParams.ITEM.name());
        //noinspection unchecked
        ((EditorScreen<Entity>) editor).setEntityToEdit(entity);
    }

    return editor;
}
 
Example 8
Source File: RouterProcessor.java    From DDComponentForAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * create init map method
 */
private MethodSpec generateInitMapMethod() {
    TypeName returnType = TypeName.VOID;

    MethodSpec.Builder openUriMethodSpecBuilder = MethodSpec.methodBuilder("initMap")
            .returns(returnType)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC);

    openUriMethodSpecBuilder.addStatement("super.initMap()");

    for (Node node : routerNodes) {
        openUriMethodSpecBuilder.addStatement(
                mRouteMapperFieldName + ".put($S,$T.class)",
                node.getPath(),
                ClassName.get((TypeElement) node.getRawType()));

        // Make map body for paramsType
        StringBuilder mapBodyBuilder = new StringBuilder();
        Map<String, Integer> paramsType = node.getParamsType();
        if (MapUtils.isNotEmpty(paramsType)) {
            for (Map.Entry<String, Integer> types : paramsType.entrySet()) {
                mapBodyBuilder.append("put(\"").append(types.getKey()).append("\", ").append(types.getValue()).append("); ");
            }
        }
        String mapBody = mapBodyBuilder.toString();
        logger.info(">>> mapBody: " + mapBody + " <<<");
        if (!StringUtils.isEmpty(mapBody)) {
            openUriMethodSpecBuilder.addStatement(
                    mParamsMapperFieldName + ".put($T.class,"
                            + "new java.util.HashMap<String, Integer>(){{" + mapBody + "}}" + ")",
                    ClassName.get((TypeElement) node.getRawType()));
        }
    }

    return openUriMethodSpecBuilder.build();
}
 
Example 9
Source File: HttpUtil.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
/**
 * 执行GET请求,返回body的string
 *
 * @param url 请求URL
 * @return response的内容
 */
public static Resp doGetWithHeader(String url, Map<String, String> headers) {
    final Request.Builder builder = new Request.Builder().get().url(url);
    if (MapUtils.isNotEmpty(headers)) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            builder.header(entry.getKey(), entry.getValue());
        }
    }
    return executeRequest(builder.build());
}
 
Example 10
Source File: GtpClientBuilder.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
@Override
public GtpClient build() {
    if (CollectionUtils.isEmpty(commandLine)) {
        throw new IllegalArgumentException("No command line for a GTP process.");
    }

    GeneralGtpClient gtpClient;

    final boolean environmentSet = MapUtils.isNotEmpty(environment);
    final boolean initialCurrentDirectorySet = initialCurrentDirectory != null && Files.exists(initialCurrentDirectory);
    if (environmentSet || initialCurrentDirectorySet) {
        gtpClient = new GeneralGtpClient(commandLine) {
            @Override
            protected void setUpOtherProcessParameters(NuProcessBuilder processBuilder) {
                super.setUpOtherProcessParameters(processBuilder);
                if (initialCurrentDirectorySet) {
                    processBuilder.setCwd(initialCurrentDirectory);
                }
                if (environmentSet) {
                    processBuilder.environment().putAll(environment);
                }
            }
        };
    } else {
        gtpClient = new GeneralGtpClient(commandLine);
    }

    return gtpClient;
}
 
Example 11
Source File: KafkaConfiguration.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public Properties toProperties() {
    Properties props = new Properties();
    props.put("zookeeper.connect", zookeeperAddr);
    props.put("auto.commit.interval.ms", String.valueOf(autoCommitInterval));
    props.put("partition.assignment.strategy", partitionAssignmentStrategy);
    props.put("rebalance.max.retries", String.valueOf(rebalanceMaxRetries));

    if (MapUtils.isNotEmpty(extra)) {
        props.putAll(extra);
    }
    return props;
}
 
Example 12
Source File: SecurityDocument.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the security MarkupDocument.
 *
 * @return the security MarkupDocument
 */
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, SecurityDocument.Parameters params) {
    Map<String, SecuritySchemeDefinition> definitions = params.securitySchemeDefinitions;
    if (MapUtils.isNotEmpty(definitions)) {
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
        buildSecurityTitle(markupDocBuilder, labels.getLabel(SECURITY));
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
        buildSecuritySchemeDefinitionsSection(markupDocBuilder, definitions);
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
        applySecurityDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
    }
    return markupDocBuilder;
}
 
Example 13
Source File: RouterProcessor.java    From JIMU with Apache License 2.0 5 votes vote down vote up
/**
 * create init map method
 */
private MethodSpec generateInitMapMethod() {
    TypeName returnType = TypeName.VOID;

    MethodSpec.Builder openUriMethodSpecBuilder = MethodSpec.methodBuilder("initMap")
            .returns(returnType)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC);

    openUriMethodSpecBuilder.addStatement("super.initMap()");

    for (Node node : routerNodes) {
        openUriMethodSpecBuilder.addStatement(
                mRouteMapperFieldName + ".put($S,$T.class)",
                node.getPath(),
                ClassName.get((TypeElement) node.getRawType()));

        // Make map body for paramsType
        StringBuilder mapBodyBuilder = new StringBuilder();
        Map<String, Integer> paramsType = node.getParamsType();
        if (MapUtils.isNotEmpty(paramsType)) {
            for (Map.Entry<String, Integer> types : paramsType.entrySet()) {
                mapBodyBuilder.append("put(\"").append(types.getKey()).append("\", ").append(types.getValue()).append("); ");
            }
        }
        String mapBody = mapBodyBuilder.toString();
        logger.info(">>> mapBody: " + mapBody + " <<<");
        if (!StringUtils.isEmpty(mapBody)) {
            openUriMethodSpecBuilder.addStatement(
                    mParamsMapperFieldName + ".put($T.class,"
                            + "new java.util.HashMap<String, Integer>(){{" + mapBody + "}}" + ")",
                    ClassName.get((TypeElement) node.getRawType()));
        }
    }

    return openUriMethodSpecBuilder.build();
}
 
Example 14
Source File: XUserService.java    From ranger with Apache License 2.0 4 votes vote down vote up
private void populateUserListAttributes(Map<String, VXUser> userNameVObjMap) {
	List<XXPortalUser> allXPortalUsers = daoManager.getXXPortalUser().findAllXPortalUser();
	List<XXPortalUserRole> allXPortalUserRoles = daoManager.getXXPortalUserRole().getAll();
	if (MapUtils.isNotEmpty(userNameVObjMap) && CollectionUtils.isNotEmpty(allXPortalUsers)) {
		Map<String, XXPortalUser> loginIdXXPortalUserMap = new HashMap<>(allXPortalUsers.size());
		Map<Long, List<XXPortalUserRole>> userIdRoleMap = new HashMap<>();
		for (XXPortalUser xPortalUser : allXPortalUsers) {
			loginIdXXPortalUserMap.put(xPortalUser.getLoginId(), xPortalUser);
			List<XXPortalUserRole> xxPortalUserRoles = new ArrayList<>();
			if (allXPortalUserRoles != null) {
				for (XXPortalUserRole xPortalUserRole : allXPortalUserRoles) {
					if (Objects.equals(xPortalUserRole.getUserId(), xPortalUser.getId())) {
						xxPortalUserRoles.add(xPortalUserRole);
					}
				}
			}
			userIdRoleMap.put(xPortalUser.getId(), xxPortalUserRoles);
		}

		for (Map.Entry<String, VXUser> userNameVObjEntry : userNameVObjMap.entrySet()) {
			String userName = userNameVObjEntry.getKey();
			VXUser vObj = userNameVObjEntry.getValue();
			if (userName != null && !userName.isEmpty()) {
				List<String> userRoleList = new ArrayList<>();
				XXPortalUser xXPortalUser = loginIdXXPortalUserMap.get(userName);
				if (xXPortalUser != null) {
					vObj.setFirstName(xXPortalUser.getFirstName());
					vObj.setLastName(xXPortalUser.getLastName());
					vObj.setPassword(PropertiesUtil.getProperty("ranger.password.hidden"));
					String emailAddress = xXPortalUser.getEmailAddress();
					if (emailAddress != null
							&& stringUtil.validateEmail(emailAddress)) {
						vObj.setEmailAddress(xXPortalUser.getEmailAddress());
					}
					vObj.setStatus(xXPortalUser.getStatus());
					vObj.setUserSource(xXPortalUser.getUserSource());
					List<XXPortalUserRole> gjUserRoleList = userIdRoleMap.get(
							xXPortalUser.getId());
					for (XXPortalUserRole gjUserRole : gjUserRoleList) {
						userRoleList.add(gjUserRole.getUserRole());
					}
				}
				if(userRoleList==null || userRoleList.isEmpty()){
					userRoleList.add(RangerConstants.ROLE_USER);
				}
				vObj.setUserRoleList(userRoleList);
			}
		}
	}
}
 
Example 15
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
private List<RemoteRepositoryInfo> getRemoteRepositoryInfo(List<RemoteConfig> resultRemotes,
                                                           Map<String, List<String>> remoteBranches,
                                                           Map<String, String> unreachableRemotes,
                                                           String sandboxBranchName) {
    List<RemoteRepositoryInfo> res = new ArrayList<RemoteRepositoryInfo>();
    for (RemoteConfig conf : resultRemotes) {
        RemoteRepositoryInfo rri = new RemoteRepositoryInfo();
        rri.setName(conf.getName());
        if (MapUtils.isNotEmpty(unreachableRemotes) && unreachableRemotes.containsKey(conf.getName())) {
            rri.setReachable(false);
            rri.setUnreachableReason(unreachableRemotes.get(conf.getName()));
        }
        List<String> branches = remoteBranches.get(rri.getName());
        if (CollectionUtils.isEmpty(branches)) {
            branches = new ArrayList<String>();
            branches.add(sandboxBranchName);
        }
        rri.setBranches(branches);

        StringBuilder sbUrl = new StringBuilder();
        if (CollectionUtils.isNotEmpty(conf.getURIs())) {
            for (int i = 0; i < conf.getURIs().size(); i++) {
                sbUrl.append(conf.getURIs().get(i).toString());
                if (i < conf.getURIs().size() - 1) {
                    sbUrl.append(":");
                }
            }
        }
        rri.setUrl(sbUrl.toString());

        StringBuilder sbFetch = new StringBuilder();
        if (CollectionUtils.isNotEmpty(conf.getFetchRefSpecs())) {
            for (int i = 0; i < conf.getFetchRefSpecs().size(); i++) {
                sbFetch.append(conf.getFetchRefSpecs().get(i).toString());
                if (i < conf.getFetchRefSpecs().size() - 1) {
                    sbFetch.append(":");
                }
            }
        }
        rri.setFetch(sbFetch.toString());

        StringBuilder sbPushUrl = new StringBuilder();
        if (CollectionUtils.isNotEmpty(conf.getPushURIs())) {
            for (int i = 0; i < conf.getPushURIs().size(); i++) {
                sbPushUrl.append(conf.getPushURIs().get(i).toString());
                if (i < conf.getPushURIs().size() - 1) {
                    sbPushUrl.append(":");
                }
            }
        } else {
            sbPushUrl.append(rri.getUrl());
        }
        rri.setPushUrl(sbPushUrl.toString());
        res.add(rri);
    }
    return res;
}
 
Example 16
Source File: CommandsHolderServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
private Map<String, Command> getLocalizedMap() {
    return MapUtils.isNotEmpty(localizedCommands)
            ? localizedCommands.get(contextService.getLocale())
            : Collections.emptyMap();
}
 
Example 17
Source File: AverageThresholdDataFilter.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isQualified(MetricTimeSeries metricTimeSeries, DimensionMap dimensionMap, long windowStart,
    long windowEnd) {
  double threshold = this.threshold;
  // Read the override threshold for the dimension of this time series
  if (MapUtils.isNotEmpty(overrideThreshold)) {
    threshold = overrideThresholdForDimensions(dimensionMap, threshold);
  }

  if (threshold == Double.NEGATIVE_INFINITY) {
    return true;
  } else if (threshold == Double.POSITIVE_INFINITY) {
    return false;
  }

  // Compute average values among all buckets and check if it passes the threshold
  double sum = 0d;
  int count = 0;
  int totalCount = 0;
  for (long timestamp : metricTimeSeries.getTimeWindowSet()) {
    if (timestamp < windowStart || timestamp >= windowEnd) {
      continue;
    }
    double value = metricTimeSeries.getOrDefault(timestamp, metricName, NULL_DOUBLE).doubleValue();
    ++totalCount;
    if (Double.compare(NULL_DOUBLE, value) == 0) {
      continue;
    }
    if (isLiveBucket(value, minLiveZone, maxLiveZone)) {
      sum += value;
      ++count;
    }
  }

  if (count > 0) {
    double liveBucketPercentage = (double) count / (double) totalCount;
    if (Double.compare(liveBucketPercentage, liveBucketPercentageThreshold) >= 0) {
      double average = sum / count;
      return Double.compare(average, threshold) >= 0;
    }
  }

  return false;
}
 
Example 18
Source File: AnomaliesResource.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
/** Construct anomaly details using all details fetched from calls
 *
 * @param metricName
 * @param dataset
 * @param datasetConfig
 * @param mergedAnomaly
 * @param anomalyFunction
 * @param currentStartTime inclusive
 * @param currentEndTime inclusive
 * @param anomalyTimelinesView
 * @return
 * @throws JSONException
 */
private AnomalyDetails constructAnomalyDetails(String metricName, String dataset, DatasetConfigDTO datasetConfig,
    MergedAnomalyResultDTO mergedAnomaly, AnomalyFunctionDTO anomalyFunction, long currentStartTime,
    long currentEndTime, AnomalyTimelinesView anomalyTimelinesView, String externalUrl)
    throws JSONException {

  MetricConfigDTO metricConfigDTO = metricConfigDAO.findByMetricAndDataset(metricName, dataset);
  DateTimeZone dateTimeZone = Utils.getDataTimeZone(dataset);
  TimeUnit dataUnit = datasetConfig.bucketTimeGranularity().getUnit();

  AnomalyDetails anomalyDetails = new AnomalyDetails();
  anomalyDetails.setMetric(metricName);
  anomalyDetails.setDataset(dataset);

  if (metricConfigDTO != null) {
    anomalyDetails.setMetricId(metricConfigDTO.getId());
  }
  anomalyDetails.setTimeUnit(dataUnit.toString());

  // The filter ensures that the returned time series from anomalies function only includes the values that are
  // located inside the request windows (i.e., between currentStartTime and currentEndTime, inclusive).
  List<TimeBucket> timeBuckets = anomalyTimelinesView.getTimeBuckets();
  int timeStartIndex = -1;
  int timeEndIndex = -1;
  for (int i = 0; i < timeBuckets.size(); ++i) {
    long currentTimeStamp = timeBuckets.get(i).getCurrentStart();
    if (timeStartIndex < 0 &&  currentTimeStamp >= currentStartTime) {
      timeStartIndex = i;
      timeEndIndex = i + 1;
    } else if (currentTimeStamp <= currentEndTime) {
      timeEndIndex = i + 1;
    } else if (currentTimeStamp > currentEndTime) {
      break;
    }
  }
  if (timeStartIndex < 0 || timeEndIndex < 0) {
    timeStartIndex = 0;
    timeEndIndex = 0;
  }

  // get this from timeseries calls
  List<String> dateValues = getDateFromTimeSeriesObject(timeBuckets.subList(timeStartIndex, timeEndIndex), timeSeriesDateFormatter);
  anomalyDetails.setDates(dateValues);
  anomalyDetails.setCurrentStart(getFormattedDateTime(currentStartTime, datasetConfig));
  anomalyDetails.setCurrentEnd(getFormattedDateTime(currentEndTime, datasetConfig));
  List<String> baselineValues = getDataFromTimeSeriesObject(anomalyTimelinesView.getBaselineValues().subList(timeStartIndex, timeEndIndex));
  anomalyDetails.setBaselineValues(baselineValues);
  List<String> currentValues = getDataFromTimeSeriesObject(anomalyTimelinesView.getCurrentValues().subList(timeStartIndex, timeEndIndex));
  anomalyDetails.setCurrentValues(currentValues);

  // from function and anomaly
  anomalyDetails.setAnomalyId(mergedAnomaly.getId());
  anomalyDetails.setAnomalyStart(timeSeriesDateFormatter.print(mergedAnomaly.getStartTime()));
  anomalyDetails.setAnomalyEnd(timeSeriesDateFormatter.print(mergedAnomaly.getEndTime()));
  long newAnomalyRegionStart = appendRegionToAnomalyStart(mergedAnomaly.getStartTime(), dateTimeZone, dataUnit);
  long newAnomalyRegionEnd = subtractRegionFromAnomalyEnd(mergedAnomaly.getEndTime(), dateTimeZone, dataUnit);
  anomalyDetails.setAnomalyRegionStart(timeSeriesDateFormatter.print(newAnomalyRegionStart));
  anomalyDetails.setAnomalyRegionEnd(timeSeriesDateFormatter.print(newAnomalyRegionEnd));
  anomalyDetails.setCurrent(ThirdEyeUtils.getRoundedValue(mergedAnomaly.getAvgCurrentVal()));
  anomalyDetails.setBaseline(ThirdEyeUtils.getRoundedValue(mergedAnomaly.getAvgBaselineVal()));
  anomalyDetails.setAnomalyResultSource(mergedAnomaly.getAnomalyResultSource().toString());
  anomalyDetails.setAnomalyFunctionId(anomalyFunction.getId());
  anomalyDetails.setAnomalyFunctionName(anomalyFunction.getFunctionName());
  anomalyDetails.setAnomalyFunctionType(anomalyFunction.getType());
  anomalyDetails.setAnomalyFunctionProps(anomalyFunction.getProperties());

  // Combine dimension map and filter set to construct a new filter set for the time series query of this anomaly
  Multimap<String, String> newFilterSet = generateFilterSetForTimeSeriesQuery(mergedAnomaly);
  try {
    anomalyDetails.setAnomalyFunctionDimension(OBJECT_MAPPER.writeValueAsString(newFilterSet.asMap()));
  } catch (JsonProcessingException e) {
    LOG.warn("Failed to convert the dimension info ({}) to a JSON string; the original dimension info ({}) is used.",
        newFilterSet, mergedAnomaly.getDimensions());
    anomalyDetails.setAnomalyFunctionDimension(mergedAnomaly.getDimensions().toString());
  }
  AnomalyFeedback mergedAnomalyFeedback = mergedAnomaly.getFeedback();
  if (mergedAnomalyFeedback != null) {
    anomalyDetails.setAnomalyFeedback(AnomalyDetails.getFeedbackStringFromFeedbackType(mergedAnomalyFeedback.getFeedbackType()));
    anomalyDetails.setAnomalyFeedbackComments(mergedAnomalyFeedback.getComment());
  }
  anomalyDetails.setExternalUrl(externalUrl);
  if (MapUtils.isNotEmpty(mergedAnomaly.getProperties()) && mergedAnomaly.getProperties()
      .containsKey(MergedAnomalyResultDTO.ISSUE_TYPE_KEY)) {
    anomalyDetails.setIssueType(mergedAnomaly.getProperties().get(MergedAnomalyResultDTO.ISSUE_TYPE_KEY));
  }

  return anomalyDetails;
}
 
Example 19
Source File: VendorListServiceV2.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
protected boolean isValid(VendorListV2 vendorList) {
    return vendorList.getVendorListVersion() != null
            && vendorList.getLastUpdated() != null
            && MapUtils.isNotEmpty(vendorList.getVendors())
            && isValidVendors(vendorList.getVendors().values());
}
 
Example 20
Source File: TemplateContext.java    From cryptotrader with GNU Affero General Public License v3.0 3 votes vote down vote up
@VisibleForTesting
public String buildQueryParameter(Map<String, String> parameters, String prefix) throws IOException {

    StringBuilder sb = new StringBuilder();

    if (MapUtils.isNotEmpty(parameters)) {

        for (Entry<String, String> entry : parameters.entrySet()) {

            if (StringUtils.isEmpty(entry.getKey())) {
                continue;
            }

            if (StringUtils.isEmpty(entry.getValue())) {
                continue;
            }

            sb.append(sb.length() == 0 ? StringUtils.trimToEmpty(prefix) : "&");
            sb.append(URLEncoder.encode(entry.getKey(), UTF_8.name()));
            sb.append('=');
            sb.append(URLEncoder.encode(entry.getValue(), UTF_8.name()));

        }

    }

    return sb.toString();

}