org.apache.commons.lang3.math.NumberUtils Java Examples

The following examples show how to use org.apache.commons.lang3.math.NumberUtils. 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: StringSeries.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to infer a tighter native series type based on pattern matching
 * against individual values in the series.
 *
 * @return inferred series type
 */
public SeriesType inferType() {
  if(this.isEmpty())
    return SeriesType.STRING;

  boolean isBoolean = true;
  boolean isLong = true;
  boolean isDouble = true;

  for(String s : this.values) {
    isBoolean &= (s == null) || (s.length() <= 0) || (s.compareToIgnoreCase("true") == 0 || s.compareToIgnoreCase("false") == 0);
    isLong &= (s == null) || (s.length() <= 0) || (NumberUtils.isNumber(s) && !s.contains(".") && !s.contains("e"));
    isDouble &= (s == null) || (s.length() <= 0) || NumberUtils.isNumber(s);
  }

  if(isBoolean)
    return SeriesType.BOOLEAN;
  if(isLong)
    return SeriesType.LONG;
  if(isDouble)
    return SeriesType.DOUBLE;
  return SeriesType.STRING;
}
 
Example #2
Source File: WebSplitPanel.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void applySettings(Element element) {
    if (!isSettingsEnabled()) {
        return;
    }

    Element e = element.element("position");
    if (e != null) {
        String value = e.attributeValue("value");
        String unit = e.attributeValue("unit");

        if (!StringUtils.isBlank(value) && !StringUtils.isBlank(unit)) {
            Unit convertedUnit;
            if (NumberUtils.isNumber(unit)) {
                convertedUnit = convertLegacyUnit(Integer.parseInt(unit));
            } else {
                convertedUnit = Unit.getUnitFromSymbol(unit);
            }
            component.setSplitPosition(Float.parseFloat(value), convertedUnit, component.isSplitPositionReversed());
        }
    }
}
 
Example #3
Source File: GradebookNgEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
@EntityCustomAction(action = "comments", viewKey = EntityView.VIEW_LIST)
public String getComments(final EntityView view, final Map<String, Object> params) {
	// get params
	final String siteId = (String) params.get("siteId");
	final long assignmentId = NumberUtils.toLong((String) params.get("assignmentId"));
	final String studentUuid = (String) params.get("studentUuid");

	// check params supplied are valid
	if (StringUtils.isBlank(siteId) || assignmentId == 0 || StringUtils.isBlank(studentUuid)) {
		throw new IllegalArgumentException(
				"Request data was missing / invalid");
	}

	checkValidSite(siteId);
	checkInstructorOrTA(siteId);

	return this.businessService.getAssignmentGradeComment(siteId, assignmentId, studentUuid);
}
 
Example #4
Source File: UserPrefsTool.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public int compareTo(Term other) {
	if (termOrder != null && (termOrder.contains(this.label) || termOrder.contains(other.label))) {
		return(NumberUtils.compare(termOrder.indexOf(this.label), termOrder.indexOf(other.label)));
	}
	
	String myType = this.getType();
	String theirType = other.getType();

	// Otherwise if not found in a term course sites win out over non-course-sites
	if (myType == null) {
		return 1;
	} else if (theirType == null) {
		return -1;
	} else if (myType.equals(theirType)) {
		return 0;
	} else if ("course".equals(myType)) {
		return -1;
	} else {
		return 1;
	}
}
 
Example #5
Source File: AggregationMethod.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
public float countDistinct(KpiVO kpi) throws Exception {
	List<BbMeasureData> measureDatas = kpi.getMeasureDatas();
	List<Float> scores = new ArrayList<Float>();
	for (BbMeasureData measureData : measureDatas) {
		BscMeasureData data = new BscMeasureData();
		data.setActual( measureData.getActual() );
		data.setTarget( measureData.getTarget() );
		data.setKpi(kpi); // 2018-12-02
		try {
			Object value = BscFormulaUtils.parse(kpi.getFormula(), data);
			if (value == null) {
				continue;
			}
			if ( !NumberUtils.isCreatable( String.valueOf(value) ) ) {
				continue;
			}
			float nowScore = NumberUtils.toFloat(String.valueOf(value), 0.0f);
	      	if ( !scores.contains(nowScore) ) {
				scores.add( nowScore );
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
	return Float.valueOf( scores.size() );
}
 
Example #6
Source File: ValidationStepDefinitions.java    From IridiumApplicationTesting with MIT License 6 votes vote down vote up
/**
 * Verifies that the element is placed in the DOM within a certain amount of time. Note that the element
 * does not have to be visible, just present in the HTML.
 * You can use this step to verify that the page is in the correct state before proceeding with the script.
 *
 * @param waitDuration    The maximum amount of time to wait for
 * @param alias           If this word is found in the step, it means the selectorValue is found from the
 *                        data set.
 * @param selectorValue   The value used in conjunction with the selector to match the element. If alias
 *                        was set, this value is found from the data set. Otherwise it is a literal
 *                        value.
 * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be
 *                        present
 */
@Then("^(?:I verify(?: that)? )?(?:a|an|the)(?: element found by)?( alias)? \"([^\"]*)\"(?: \\w+)*? "
	+ "is present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void presentSimpleWaitStep(
	final String alias,
	final String selectorValue,
	final String waitDuration,
	final String ignoringTimeout) {

	try {
		simpleWebElementInteraction.getPresenceElementFoundBy(
			StringUtils.isNotBlank(alias),
			selectorValue,
			State.getFeatureStateForThread(),
			NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()));
	} catch (final WebElementException ex) {
		/*
			Rethrow if we have not ignored errors
		 */
		if (StringUtils.isBlank(ignoringTimeout)) {
			throw ex;
		}
	}
}
 
Example #7
Source File: RecipientsDetailedStatisticDataSet.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Get Data for Recipient Report
   * message key "report.recipient.statistics.recipientDevelopmentDetailed.label"
   * en: "Recipient development detailed (Opt-ins, Opt-outs, Bounces)"
   * de: "Empfängerentwicklung detailliert (Anmeldungen, Abmeldungen, Bounces)"
   */
  public void initRecipientsStatistic(@VelocityCheck int companyId, String selectedMailingLists, String selectedTargetsAsString, String startDate, String stopDate) throws Exception {
  	List<Integer> mailingListIds = new ArrayList<>();
for (String mailingListIdString : selectedMailingLists.split(",")) {
	mailingListIds.add(NumberUtils.toInt(mailingListIdString));
}

      Date dateStart = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
      Date dateStop = new SimpleDateFormat("yyyy-MM-dd").parse(stopDate);

      int mailinglistIndex = 0;
      for (LightMailingList mailinglist : getMailingLists(mailingListIds, companyId)) {
	int mailinglistID = mailinglist.getMailingListId();
	mailinglistIndex++;

	int targetGroupIndex = CommonKeys.ALL_SUBSCRIBERS_INDEX;
	insertStatistic(companyId, mailinglistID, mailinglistIndex, null, targetGroupIndex, dateStart, dateStop);
 
	for (LightTarget target : getTargets(selectedTargetsAsString, companyId)) {
          	targetGroupIndex++;
          	insertStatistic(companyId, mailinglistID, mailinglistIndex, target, targetGroupIndex, dateStart, dateStop);
          }
      }
  }
 
Example #8
Source File: IndentFilter.java    From jinjava with Apache License 2.0 6 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  int width = 4;
  if (args.length > 0) {
    width = NumberUtils.toInt(args[0], 4);
  }

  boolean indentFirst = false;
  if (args.length > 1) {
    indentFirst = BooleanUtils.toBoolean(args[1]);
  }

  List<String> indentedLines = new ArrayList<>();
  for (String line : NEWLINE_SPLITTER.split(Objects.toString(var, ""))) {
    int thisWidth = indentedLines.size() == 0 && !indentFirst ? 0 : width;
    indentedLines.add(StringUtils.repeat(' ', thisWidth) + line);
  }

  return NEWLINE_JOINER.join(indentedLines);
}
 
Example #9
Source File: ConstructorUtilsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testInvokeConstructor() throws Exception {
    assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class,
            ArrayUtils.EMPTY_CLASS_ARRAY).toString());
    assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class,
            (Class[]) null).toString());
    assertEquals("(String)", ConstructorUtils.invokeConstructor(
            TestBean.class, "").toString());
    assertEquals("(Object)", ConstructorUtils.invokeConstructor(
            TestBean.class, new Object()).toString());
    assertEquals("(Object)", ConstructorUtils.invokeConstructor(
            TestBean.class, Boolean.TRUE).toString());
    assertEquals("(Integer)", ConstructorUtils.invokeConstructor(
            TestBean.class, NumberUtils.INTEGER_ONE).toString());
    assertEquals("(int)", ConstructorUtils.invokeConstructor(
            TestBean.class, NumberUtils.BYTE_ONE).toString());
    assertEquals("(double)", ConstructorUtils.invokeConstructor(
            TestBean.class, NumberUtils.LONG_ONE).toString());
    assertEquals("(double)", ConstructorUtils.invokeConstructor(
            TestBean.class, NumberUtils.DOUBLE_ONE).toString());
}
 
Example #10
Source File: CenterServiceSMOImpl.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 * @param reqJson
 * @return
 */
private String decrypt(String reqJson,Map<String,String> headers) throws DecryptException{
    try {
        if (MappingConstant.VALUE_ON.equals(headers.get(CommonConstant.ENCRYPT))) {
            logger.debug("解密前字符:" + reqJson);
            reqJson = new String(AuthenticationFactory.decrypt(reqJson.getBytes("UTF-8"), AuthenticationFactory.loadPrivateKey(MappingConstant.KEY_PRIVATE_STRING)
                    , NumberUtils.isNumber(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) ? Integer.parseInt(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) :
                            Integer.parseInt(MappingCache.getValue(MappingConstant.KEY_DEFAULT_DECRYPT_KEY_SIZE))),"UTF-8");
            logger.debug("解密后字符:" + reqJson);
        }
    }catch (Exception e){
        throw new DecryptException(ResponseConstant.RESULT_CODE_NO_AUTHORITY_ERROR,"解密失败");
    }

    return reqJson;
}
 
Example #11
Source File: OXRCurrencyConverter.java    From para with Apache License 2.0 6 votes vote down vote up
@Override
public Double convertCurrency(Number amount, String from, String to) {
	if (amount == null || StringUtils.isBlank(from) || StringUtils.isBlank(to)) {
		return 0.0;
	}
	Sysprop s = dao.read(FXRATES_KEY);
	if (s == null) {
		s = fetchFxRatesJSON();
	} else if ((Utils.timestamp() - s.getTimestamp()) > REFRESH_AFTER) {
		// lazy refresh fx rates
		Para.asyncExecute(new Runnable() {
			public void run() {
				fetchFxRatesJSON();
			}
		});
	}

	double ratio = 1.0;

	if (s.hasProperty(from) && s.hasProperty(to)) {
		Double f = NumberUtils.toDouble(s.getProperty(from).toString(), 1.0);
		Double t = NumberUtils.toDouble(s.getProperty(to).toString(), 1.0);
		ratio = t / f;
	}
	return amount.doubleValue() * ratio;
}
 
Example #12
Source File: CloudWatchReporter.java    From metrics-cloudwatch with Apache License 2.0 6 votes vote down vote up
void reportGauge(Map.Entry<String, Gauge> gaugeEntry, String typeDimValue, List<MetricDatum> data) {
    Gauge gauge = gaugeEntry.getValue();

    Object valueObj = gauge.getValue();
    if (valueObj == null) {
        return;
    }

    String valueStr = valueObj.toString();
    if (NumberUtils.isNumber(valueStr)) {
        final Number value = NumberUtils.createNumber(valueStr);

        DemuxedKey key = new DemuxedKey(appendGlobalDimensions(gaugeEntry.getKey()));
        Iterables.addAll(data, key.newDatums(typeDimName, typeDimValue, new Function<MetricDatum, MetricDatum>() {
            @Override
            public MetricDatum apply(MetricDatum datum) {
                return datum.withValue(value.doubleValue());
            }
        }));
    }
}
 
Example #13
Source File: PdfConvertUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
	if (args == null || args.length != 2) {
		System.out.println("PdfConvertUtils [FILE] [RESOLUTION]");
		System.out.println("Example: PdfConvertUtils /test.pdf 120");		
		System.exit(1);
	}		
	System.out.println("source document file: " + args[0]);		
	int res = NumberUtils.toInt(args[1], 300);
	List<File> imageFiles = toImageFiles(new File(args[0]), res);
	for (File file : imageFiles) {
		System.out.println( file.getPath() );
	}
}
 
Example #14
Source File: Version.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * @param version the {@link String} to interpret as version
 */
public Version(final String version) {
	Objects.requireNonNull(version, "Null does not represent a Version.");
	if (!version.matches(REGEX_FORMAT_CHECK)) {
		throw new IllegalArgumentException(
				String.format("The given String '%s' does not represent a Version.", version));
	}
	final String[] split = version.replaceAll("\\.[\\.0+]*$", "") // trim all '.0' at the end as they are useless
			.split("\\."); // split for '.'
	parts = Arrays.stream(split).filter(NumberUtils::isDigits).mapToInt(Integer::parseInt).toArray();
	if (parts.length == 0) {
		throw new IllegalArgumentException(
				String.format("The given String '%s' does not represent a Version.", version));
	}
}
 
Example #15
Source File: MyArrayUtils.java    From WiFi-and-Sensors-Indoor-Positioning with GNU General Public License v3.0 5 votes vote down vote up
public static float[] StrArrayToFloat(String[] arr) {
	int len = 0;
	for (int i = 0; i < arr.length; i++) {
		if (NumberUtils.isNumber(arr[i])) {
			len++;
		}
	}
	float[] nums = new float[len];
	for (int i = 0; i < nums.length; i++) {
		if (NumberUtils.isNumber(arr[i])) {
			nums[i] = Float.parseFloat(arr[i]);
		}
	}
	return nums;
}
 
Example #16
Source File: ValidationStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Verifies that the element is placed in the DOM within a certain amount of time. Note that the element
 * does not have to be visible, just present in the HTML.
 * You can use this step to verify that the page is in the correct state before proceeding with the script.
 *
 * @param waitDuration    The maximum amount of time to wait for
 * @param selector        Either ID, class, xpath, name or css selector
 * @param alias           If this word is found in the step, it means the selectorValue is found from the
 *                        data set.
 * @param selectorValue   The value used in conjunction with the selector to match the element. If alias
 *                        was set, this value is found from the data set. Otherwise it is a literal
 *                        value.
 * @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be
 *                        present
 */
@Then("^(?:I verify(?: that)? )?(?:a|an|the) element with (?:a|an|the) "
	+ "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" "
	+ "is present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void presentWaitStep(
	final String selector,
	final String alias,
	final String selectorValue,
	final String waitDuration,
	final String ignoringTimeout) {

	final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
	final By by = getBy.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, State.getFeatureStateForThread());
	final WebDriverWait wait = new WebDriverWait(
		webDriver,
		NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()),
		Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
	try {
		wait.until(ExpectedConditions.presenceOfElementLocated(by));
	} catch (final TimeoutException ex) {
		/*
			Rethrow if we have not ignored errors
		 */
		if (StringUtils.isBlank(ignoringTimeout)) {
			throw ex;
		}
	}
}
 
Example #17
Source File: GitVersion.java    From onedev with MIT License 5 votes vote down vote up
public GitVersion(String versionStr) {
	for (String each: StringUtils.splitAndTrim(versionStr, ".")) {
		if (NumberUtils.isDigits(each))
			parts.add(Integer.valueOf(each));
		else if (each.equals("msysgit"))
			msysgit = true;
	}
}
 
Example #18
Source File: StringUtils.java    From easter_eggs_for_java_9 with Apache License 2.0 5 votes vote down vote up
public int safeParseInt(String s) {
    int result = Integer.MIN_VALUE;

    if (NumberUtils.isParsable(s)) {
        try {
            result = Integer.parseInt(s);
        } catch(Exception ex) {
        } 
    }

    return result;
}
 
Example #19
Source File: Query.java    From conductor with Apache License 2.0 5 votes vote down vote up
protected Integer convertInt(Object value) {
    if (null == value) {
        return null;
    }

    if (value instanceof Integer) {
        return (Integer) value;
    }

    if (value instanceof Number) {
        return ((Number) value).intValue();
    }

    return NumberUtils.toInt(value.toString());
}
 
Example #20
Source File: ComTargetServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TargetSavingAndAnalysisResult saveTargetWithAnalysis(ComAdmin admin, ComTarget newTarget, ComTarget target, ActionMessages errors, UserActivityLog userActivityLog) throws Exception {	// TODO: Remove "ActionMessages" to remove dependencies to Struts
       if (target == null) {
           // be sure to use id 0 if there is no existing object
           newTarget.setId(0);
       }

       if (validateTargetDefinition(admin.getCompanyID(), newTarget.getEQL())) {
		newTarget.setComplexityIndex(calculateComplexityIndex(newTarget.getEQL(), admin.getCompanyID()));

		final int newId = targetDao.saveTarget(newTarget);

		// Check for maximum "compare to"-value of gender equations
		// Must be done after saveTarget(..)-call because there the new target sql expression is generated
		if (newTarget.getTargetSQL().contains("cust.gender")) {
			final int maxGenderValue = getMaxGenderValue(admin);

			Matcher matcher = GENDER_EQUATION_PATTERN.matcher(newTarget.getTargetSQL());
			while (matcher.find()) {
				int genderValue = NumberUtils.toInt(matcher.group(1));
				if (genderValue < 0 || genderValue > maxGenderValue) {
					errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.gender.invalid"));
					break;
				}
			}
		} else if (newTarget.getTargetSQL().equals("1=0")) {
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.target.definition"));
		}
		newTarget.setId(newId);

		final EqlAnalysisResult analysisResultOrNull = this.eqlFacade.analyseEql(newTarget.getEQL());

		logTargetGroupSave(admin, newTarget, target, userActivityLog);

		return new TargetSavingAndAnalysisResult(newId, analysisResultOrNull);
	} else {
           errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.target.definition"));
           return new TargetSavingAndAnalysisResult(0, null);
       }
   }
 
Example #21
Source File: CenterServiceSMOImpl.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 * @param resJson
 * @param headers
 * @return
 */
private String encrypt(String resJson,Map<String,String> headers){
    try {
        if (MappingConstant.VALUE_ON.equals(headers.get(CommonConstant.ENCRYPT))) {
            logger.debug("加密前字符:" + resJson);
            resJson = new String(AuthenticationFactory.encrypt(resJson.getBytes("UTF-8"), AuthenticationFactory.loadPubKey(MappingConstant.KEY_PUBLIC_STRING)
                    , NumberUtils.isNumber(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) ? Integer.parseInt(headers.get(CommonConstant.ENCRYPT_KEY_SIZE)) :
                            Integer.parseInt(MappingCache.getValue(MappingConstant.KEY_DEFAULT_DECRYPT_KEY_SIZE))),"UTF-8");
            logger.debug("加密后字符:" + resJson);
        }
    }catch (Exception e){
        logger.error("加密失败:",e);
    }
    return resJson;
}
 
Example #22
Source File: IgniteBrokerDao.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
private SqlQuery buildQuery(BrokerQuery query) {
    IgniteDao.SimpleSqlBuilder sqlBuilder = IgniteDao.SimpleSqlBuilder.create(IgniteBroker.class);
    if (query != null) {
        if (query.getIp() != null && !query.getIp().isEmpty()) {
            sqlBuilder.and(IgniteBroker.COLUMN_IP, query.getIp());
        }

        if (query.getBrokerId() > 0) {
            sqlBuilder.and(IgniteBroker.COLUMN_BROKER_ID, query.getBrokerId());
        }
        if (query.getPort() > 0) {
            sqlBuilder.and(IgniteBroker.COLUMN_PORT, query.getPort());
        }
        if (query.getRetryType() != null && !query.getRetryType().isEmpty()) {
            sqlBuilder.and(IgniteBroker.COLUMN_RETRY_TYPE, query.getRetryType());
        }
        if (StringUtils.isNotEmpty(query.getKeyword())) {
            sqlBuilder.and(IgniteBroker.COLUMN_IP,query.getKeyword());
            if (NumberUtils.isNumber(query.getKeyword())){
                sqlBuilder.or(IgniteBroker.COLUMN_BROKER_ID,Integer.valueOf(query.getKeyword()).intValue());
            }
        }
        if (query.getBrokerList() != null && !query.getBrokerList().isEmpty()) {
            sqlBuilder.in(IgniteBroker.COLUMN_BROKER_ID, query.getBrokerList());
        }
    }
    return sqlBuilder.build();
}
 
Example #23
Source File: GradebookServiceHibernateImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public String getAssignmentScoreStringByNameOrId(final String gradebookUid, final String assignmentName, final String studentUid)
		throws GradebookNotFoundException, AssessmentNotFoundException {
	String score = null;
	try {
		score = getAssignmentScoreString(gradebookUid, assignmentName, studentUid);
	} catch (final AssessmentNotFoundException e) {
		// Don't fail on this exception
		log.debug("Assessment not found by name", e);
	} catch (final GradebookSecurityException gse) {
		log.warn("User {} does not have permission to retrieve score for assignment {}", studentUid, assignmentName, gse);
		return null;
	}

	if (score == null) {
		// Try to get the assignment by id
		if (NumberUtils.isCreatable(assignmentName)) {
			final Long assignmentId = NumberUtils.toLong(assignmentName, -1L);
			try {
				score = getAssignmentScoreString(gradebookUid, assignmentId, studentUid);
			} catch (AssessmentNotFoundException anfe) {
				log.debug("Assessment could not be found for gradebook id {} and assignment id {} and student id {}", gradebookUid, assignmentName, studentUid);
			}
		}
	}
	return score;
}
 
Example #24
Source File: SolrUtils.java    From vind with Apache License 2.0 5 votes vote down vote up
public static Map<String,Integer> getChildCounts(SolrResponse response) {

        //check if there are subdocs
        if (Objects.nonNull(response.getResponse())) {
            final Object subDocumentFacetResult = response.getResponse().get("facets");
            if (Objects.nonNull(subDocumentFacetResult)) {
                Map<String,Integer> childCounts = new HashMap<>();

                log.debug("Parsing subdocument facet result from JSON ");

                final Object count = ((SimpleOrderedMap) subDocumentFacetResult).get("count");
                final Number facetCount = Objects.nonNull(count)? NumberUtils.toLong(count.toString(), 0L) : new Integer(0);

                if (Objects.nonNull(((SimpleOrderedMap) subDocumentFacetResult).get("parent_facet")) && facetCount.longValue() > 0) {
                    final List<SimpleOrderedMap> parentDocs = (ArrayList) ((SimpleOrderedMap) ((SimpleOrderedMap) subDocumentFacetResult).get("parent_facet")).get("buckets");
                    childCounts = parentDocs.stream()
                            .collect(Collectors.toMap(
                                    p -> (String) p.get("val"),
                                    p -> {
                                        final Object childrenCount = ((SimpleOrderedMap) p.get("children_facet")).get("count");
                                        return Objects.nonNull(childrenCount)? NumberUtils.toInt(childrenCount.toString(), 0) : new Integer(0);
                                    })
                            );
                }

                return childCounts;
            }
        }

        return null;
    }
 
Example #25
Source File: FuzzyValues.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Indicates if the submitted text has the format of a SSIN. <br/>
 * It does <b>NOT</b> check if the SSIN is valid!
 */
public static boolean isSsin(String text) {
	if (!NumberUtils.isDigits(text) || text.length() != 11) {
		return false;
	}
	BigInteger checkDigits = new BigInteger(text.substring(9));
	BigInteger big97 = new BigInteger("97");
	BigInteger modBefore2000 = new BigInteger(text.substring(0, 9)).mod(big97);
	BigInteger modAfter2000 = new BigInteger("2" + text.substring(0, 9)).mod(big97);

	return big97.subtract(modBefore2000).equals(checkDigits) || big97.subtract(modAfter2000).equals(checkDigits);
}
 
Example #26
Source File: ComMailingSendActionBasic.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONObject saveStatusmailOnErrorOnly(HttpServletRequest request) {
    String isStatusmailOnErrorOnlyParam = request.getParameter("statusmailOnErrorOnly");
    String mailingIdParam = request.getParameter("mailingId");
    boolean isUpdated = false;

    if (StringUtils.isNotBlank(isStatusmailOnErrorOnlyParam) && StringUtils.isNotBlank(mailingIdParam)) {
        boolean isStatusmailOnErrorOnly = BooleanUtils.toBoolean(isStatusmailOnErrorOnlyParam);
        int mailingId = NumberUtils.toInt(mailingIdParam);
        ComAdmin admin = AgnUtils.getAdmin(request);

        try {
            // creation of UAL entry
            Mailing mailing = mailingService.getMailing(admin.getCompanyID(), mailingId);
            String action = "switched mailing statusmailonerroronly";
            String description = String.format("statusmailonerroronly: %s, mailing type: %s. %s(%d)",
            		isStatusmailOnErrorOnly ? "true" : "false",
                    mailingTypeToString(mailing.getMailingType()),
                    mailing.getShortname(),
                    mailing.getId());

            if (mailingService.switchStatusmailOnErrorOnly(admin.getCompanyID(), mailingId, isStatusmailOnErrorOnly)) {
                isUpdated = true;
                writeUserActivityLog(admin, action, description);
            }
        } catch (Exception e) {
            logger.error("Error occurred: " + e.getMessage(), e);
        }
    }

    JSONObject response = new JSONObject();
    response.element("success", isUpdated);
    return response;
}
 
Example #27
Source File: RestClientLoggingFilterTest.java    From pay-publicapi with MIT License 5 votes vote down vote up
@Test
public void shouldLogRestClientEndEventWithRequestIdAndElapsedTime() {

    String requestId = UUID.randomUUID().toString();
    URI requestUrl = URI.create("/publicapi-request");
    String requestMethod = "GET";

    when(clientRequestContext.getUri()).thenReturn(requestUrl);
    when(clientRequestContext.getMethod()).thenReturn(requestMethod);
    MultivaluedMap<String, Object> mockHeaders = new MultivaluedHashMap<>();
    MultivaluedMap<String, String> mockHeaders2 = new MultivaluedHashMap<>();

    when(clientRequestContext.getHeaders()).thenReturn(mockHeaders);
    when(clientResponseContext.getHeaders()).thenReturn(mockHeaders2);
    MDC.put(LoggingKeys.MDC_REQUEST_ID_KEY, requestId);
    loggingFilter.filter(clientRequestContext);

    loggingFilter.filter(clientRequestContext, clientResponseContext);

    verify(mockAppender, times(2)).doAppend(loggingEventArgumentCaptor.capture());
    List<LoggingEvent> loggingEvents = loggingEventArgumentCaptor.getAllValues();

    assertThat(loggingEvents.get(0).getFormattedMessage(), is(format("[%s] - %s to %s began", requestId, requestMethod, requestUrl)));
    String endLogMessage = loggingEvents.get(1).getFormattedMessage();
    assertThat(endLogMessage, containsString(format("[%s] - %s to %s ended - total time ", requestId, requestMethod, requestUrl)));
    String[] timeTaken = StringUtils.substringsBetween(endLogMessage, "total time ", "ms");
    assertTrue(NumberUtils.isCreatable(timeTaken[0]));

}
 
Example #28
Source File: ComMailingBaseForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void reset(ActionMapping map, HttpServletRequest request) {
	setAction(ComMailingBaseAction.ACTION_LIST);

	dynamicTemplate = false;
	archived = false;
	super.reset(map, request);
	clearBulkIds();

	int actionID = NumberUtils.toInt(request.getParameter("action"));
	if (actionID == ComMailingBaseAction.ACTION_SAVE
		|| actionID == ComMailingBaseAction.ACTION_SAVE_MAILING_GRID) {
		parameterMap.clear();
		addParameter = false;
	}

	intervalType = ComMailingParameterDao.IntervalType.None;
	intervalDays = new boolean[7];

	setNumberOfRows(-1);
	selectedFields = ArrayUtils.EMPTY_STRING_ARRAY;

	uploadFile = null;

	setTargetGroups(Collections.emptyList());
	setTargetExpression(StringUtils.EMPTY);
	assignTargetGroups = false;
}
 
Example #29
Source File: MultipleParameterTool.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@link MultipleParameterTool} for the given arguments. The arguments are keys followed by values.
 * Keys have to start with '-' or '--'
 *
 * <p><strong>Example arguments:</strong>
 * --key1 value1 --key2 value2 -key3 value3
 * --multi multiValue1 --multi multiValue2
 *
 * @param args Input array arguments
 * @return A {@link MultipleParameterTool}
 */
public static MultipleParameterTool fromArgs(String[] args) {
	final Map<String, Collection<String>> map = new HashMap<>(args.length / 2);

	int i = 0;
	while (i < args.length) {
		final String key = Utils.getKeyFromArgs(args, i);

		i += 1; // try to find the value

		map.putIfAbsent(key, new ArrayList<>());
		if (i >= args.length) {
			map.get(key).add(NO_VALUE_KEY);
		} else if (NumberUtils.isNumber(args[i])) {
			map.get(key).add(args[i]);
			i += 1;
		} else if (args[i].startsWith("--") || args[i].startsWith("-")) {
			// the argument cannot be a negative number because we checked earlier
			// -> the next argument is a parameter name
			map.get(key).add(NO_VALUE_KEY);
		} else {
			map.get(key).add(args[i]);
			i += 1;
		}
	}

	return fromMultiMap(map);
}
 
Example #30
Source File: ComMailingContentForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public int getDynContentId(String index) {
    DynamicTagContent tag = getContent().get(NumberUtils.toInt(index));
    if (tag == null) {
        return -1;
    }
    return tag.getId();
}