List of usage examples for java.util Date compareTo
public int compareTo(Date anotherDate)
From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java
License:asdf
@Test public void addDate() { Calendar calendarDay1 = ConversorToolkit.getCalendar("01/01/2017"); Calendar calendarDay2 = ConversorToolkit.getCalendar("02/01/2017"); Calendar calendarDay3 = ConversorToolkit.getCalendar("03/01/2017"); MElement raiz = MElement.newInstance("raiz"); raiz.addDate("dataSimple", "01/01/2017"); raiz.addDate("dataWithDefaultOption", "02/01/2017", "03/01/2017"); raiz.addDate("dataWithNullOption", null, "03/01/2017"); Date dataSimple = raiz.getDate("dataSimple"); Date dataWithDefaultOption = raiz.getDate("dataWithDefaultOption"); Date dataWithNullOption = raiz.getDate("dataWithNullOption"); Assert.assertEquals(0, dataSimple.compareTo(calendarDay1.getTime())); Assert.assertEquals(0, dataWithDefaultOption.compareTo(calendarDay2.getTime())); Assert.assertEquals(0, dataWithNullOption.compareTo(calendarDay3.getTime())); }
From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java
public static int compareFilterKeyBasedOnDataType(String dictionaryVal, String memberVal, DataType dataType) { try {//from ww w . ja v a 2 s . c o m if (dataType == DataTypes.BOOLEAN) { return Boolean.compare((Boolean.parseBoolean(dictionaryVal)), (Boolean.parseBoolean(memberVal))); } else if (dataType == DataTypes.SHORT) { return Short.compare((Short.parseShort(dictionaryVal)), (Short.parseShort(memberVal))); } else if (dataType == DataTypes.INT) { return Integer.compare((Integer.parseInt(dictionaryVal)), (Integer.parseInt(memberVal))); } else if (dataType == DataTypes.DOUBLE) { return Double.compare((Double.parseDouble(dictionaryVal)), (Double.parseDouble(memberVal))); } else if (dataType == DataTypes.LONG) { return Long.compare((Long.parseLong(dictionaryVal)), (Long.parseLong(memberVal))); } else if (dataType == DataTypes.BOOLEAN) { return Boolean.compare((Boolean.parseBoolean(dictionaryVal)), (Boolean.parseBoolean(memberVal))); } else if (dataType == DataTypes.DATE || dataType == DataTypes.TIMESTAMP) { String format = CarbonUtil.getFormatFromProperty(dataType); SimpleDateFormat parser = new SimpleDateFormat(format); Date dateToStr; Date dictionaryDate; dateToStr = parser.parse(memberVal); dictionaryDate = parser.parse(dictionaryVal); return dictionaryDate.compareTo(dateToStr); } else if (DataTypes.isDecimal(dataType)) { java.math.BigDecimal javaDecValForDictVal = new java.math.BigDecimal(dictionaryVal); java.math.BigDecimal javaDecValForMemberVal = new java.math.BigDecimal(memberVal); return javaDecValForDictVal.compareTo(javaDecValForMemberVal); } else { return -1; } } catch (ParseException | NumberFormatException e) { return -1; } }
From source file:com.pearson.dashboard.util.Util.java
public static void retrieveTestCasesUsingSets(DashboardForm dashboardForm, Configuration configuration, String cutoffDateStr, List<String> testSets) throws IOException, URISyntaxException, ParseException { RallyRestApi restApi = loginRally(configuration); QueryRequest testSetRequest = new QueryRequest("TestSet"); testSetRequest.setProject("/project/" + dashboardForm.getProjectId()); String wsapiVersion = "1.43"; restApi.setWsapiVersion(wsapiVersion); testSetRequest.setFetch(new Fetch(new String[] { "Name", "Priority", "Description", "TestCases", "FormattedID", "LastVerdict", "LastBuild", "LastRun" })); QueryFilter queryFilter = new QueryFilter("FormattedID", "=", testSets.get(0)); int q = 1;// w ww. java2 s. c o m while (testSets.size() > q) { queryFilter = queryFilter.or(new QueryFilter("FormattedID", "=", testSets.get(q))); q++; } testSetRequest.setQueryFilter(queryFilter); boolean dataNotReceived = true; while (dataNotReceived) { try { QueryResponse testSetQueryResponse = restApi.query(testSetRequest); dataNotReceived = false; List<Priority> priorities = new ArrayList<Priority>(); Priority priority0 = new Priority(); priority0.setPriorityName("Pass"); Priority priority1 = new Priority(); priority1.setPriorityName("Blocked"); Priority priority2 = new Priority(); priority2.setPriorityName("Error"); Priority priority3 = new Priority(); priority3.setPriorityName("Fail"); Priority priority4 = new Priority(); priority4.setPriorityName("Inconclusive"); Priority priority5 = new Priority(); priority5.setPriorityName("NotAttempted"); int testCasesCount = 0; List<TestCase> testCases = new ArrayList<TestCase>(); for (int i = 0; i < testSetQueryResponse.getResults().size(); i++) { JsonObject testSetJsonObject = testSetQueryResponse.getResults().get(i).getAsJsonObject(); int numberOfTestCases = testSetJsonObject.get("TestCases").getAsJsonArray().size(); if (numberOfTestCases > 0) { DateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd"); Date cutoffDate = (Date) formatter1.parse(cutoffDateStr); for (int j = 0; j < numberOfTestCases; j++) { JsonObject jsonObject = testSetJsonObject.get("TestCases").getAsJsonArray().get(j) .getAsJsonObject(); TestCase testCase = new TestCase(); testCase.setTestCaseId(jsonObject.get("FormattedID").getAsString()); Date lastVerdictDate = null; if (null != jsonObject.get("LastRun") && !jsonObject.get("LastRun").isJsonNull()) { lastVerdictDate = (Date) formatter1.parse(jsonObject.get("LastRun").getAsString()); } String lastVerdict = ""; if (!jsonObject.get("LastVerdict").isJsonNull()) { lastVerdict = jsonObject.get("LastVerdict").getAsString(); } if (null != lastVerdictDate && lastVerdictDate.compareTo(cutoffDate) >= 0) { if (lastVerdict.equalsIgnoreCase("Pass")) { priority0.setPriorityCount(priority0.getPriorityCount() + 1); } if (lastVerdict.equalsIgnoreCase("Blocked")) { priority1.setPriorityCount(priority1.getPriorityCount() + 1); } if (lastVerdict.equalsIgnoreCase("Error")) { priority2.setPriorityCount(priority2.getPriorityCount() + 1); } if (lastVerdict.equalsIgnoreCase("Fail")) { priority3.setPriorityCount(priority3.getPriorityCount() + 1); } if (lastVerdict.equalsIgnoreCase("Inconclusive")) { priority4.setPriorityCount(priority4.getPriorityCount() + 1); } if (lastVerdict.equalsIgnoreCase("")) { priority5.setPriorityCount(priority5.getPriorityCount() + 1); } } else { priority5.setPriorityCount(priority5.getPriorityCount() + 1); } testCasesCount++; testCase.setLastVerdict(jsonObject.get("LastVerdict") == null || jsonObject.get("LastVerdict").isJsonNull() ? "" : jsonObject.get("LastVerdict").getAsString()); testCase.setName( jsonObject.get("Name") == null || jsonObject.get("Name").isJsonNull() ? "" : jsonObject.get("Name").getAsString()); testCase.setDescription(jsonObject.get("Description") == null || jsonObject.get("Description").isJsonNull() ? "" : jsonObject.get("Description").getAsString()); testCase.setLastRun( jsonObject.get("LastRun") == null || jsonObject.get("LastRun").isJsonNull() ? "" : jsonObject.get("LastRun").getAsString()); testCase.setLastBuild( jsonObject.get("LastBuild") == null || jsonObject.get("LastBuild").isJsonNull() ? "" : jsonObject.get("LastBuild").getAsString()); testCase.setPriority( jsonObject.get("Priority") == null || jsonObject.get("Priority").isJsonNull() ? "" : jsonObject.get("Priority").getAsString()); testCases.add(testCase); } } } dashboardForm.setTestCases(testCases); List<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(priority0.getPriorityCount()); arrayList.add(priority1.getPriorityCount()); arrayList.add(priority2.getPriorityCount()); arrayList.add(priority3.getPriorityCount()); arrayList.add(priority4.getPriorityCount()); arrayList.add(priority5.getPriorityCount()); Integer maximumCount = Collections.max(arrayList); if (maximumCount <= 0) { priority0.setPxSize("0"); priority1.setPxSize("0"); priority2.setPxSize("0"); priority3.setPxSize("0"); priority4.setPxSize("0"); priority5.setPxSize("0"); } else { priority0.setPxSize(Math.round((100 * priority0.getPriorityCount()) / maximumCount) + ""); priority1.setPxSize(Math.round((100 * priority1.getPriorityCount()) / maximumCount) + ""); priority2.setPxSize(Math.round((100 * priority2.getPriorityCount()) / maximumCount) + ""); priority3.setPxSize(Math.round((100 * priority3.getPriorityCount()) / maximumCount) + ""); priority4.setPxSize(Math.round((100 * priority4.getPriorityCount()) / maximumCount) + ""); priority5.setPxSize(Math.round((100 * priority5.getPriorityCount()) / maximumCount) + ""); } priorities.add(priority0); priorities.add(priority1); priorities.add(priority2); priorities.add(priority3); priorities.add(priority4); priorities.add(priority5); dashboardForm.setTestCasesCount(testCasesCount); dashboardForm.setTestCasesPriorities(priorities); } catch (HttpHostConnectException connectException) { if (restApi != null) { restApi.close(); } try { restApi = loginRally(configuration); } catch (URISyntaxException e) { e.printStackTrace(); } } } }
From source file:gov.utah.dts.det.ccl.service.impl.FacilityServiceImpl.java
protected Facility performDeactivation(Facility facility, PickListValue reason, Date effectiveDate) { List<PickListValue> deactivationReasons = pickListService .getValuesForPickList("Facility Deactivation Reasons", true); if (effectiveDate.compareTo(new Date()) > 0) { List<FacilityTag> deactTags = facility.getTags(deactivationReasons); if (deactTags.isEmpty()) { // set the effective date FacilityTag deact = new FacilityTag(); deact.setTag(reason);/*from ww w . j a v a2 s . c om*/ deact.setStartDate(effectiveDate); deact.setExpirationDate(effectiveDate); facility.addTag(deact); } else { FacilityTag deact = deactTags.get(0); deact.setTag(reason); deact.setStartDate(effectiveDate); deact.setExpirationDate(effectiveDate); } } else { if (facility.getStatus() == FacilityStatus.INACTIVE) { return facility; } Date eDate = DateUtils.truncate(effectiveDate, Calendar.DATE); // any licenses and exemptions that start after the closure date should be deleted for (Iterator<License> itr = facility.getLicenses().iterator(); itr.hasNext();) { License lic = itr.next(); if (lic.getStartDate().compareTo(effectiveDate) >= 0) { itr.remove(); } else if (lic.getStartDate().compareTo(effectiveDate) < 0 && lic.getExpirationDate().compareTo(effectiveDate) > 0) { lic.setExpirationDate(eDate); } } for (Iterator<Exemption> itr = facility.getExemptions().iterator(); itr.hasNext();) { Exemption ex = itr.next(); if (ex.getStartDate().compareTo(effectiveDate) >= 0) { itr.remove(); } else if (ex.getStartDate().compareTo(effectiveDate) < 0 && ex.getExpirationDate().compareTo(effectiveDate) > 0) { ex.setExpirationDate(effectiveDate); } } PickListValue condTag = applicationService .getPickListValueForApplicationProperty(ApplicationPropertyKey.TAG_CONDITIONAL.getKey()); for (Iterator<FacilityTag> itr = facility.getTags().iterator(); itr.hasNext();) { FacilityTag tag = itr.next(); if (tag.getTag().equals(condTag)) { if (tag.getStartDate().compareTo(effectiveDate) >= 0) { itr.remove(); } else if (tag.getStartDate().compareTo(effectiveDate) < 0 && tag.getExpirationDate().compareTo(effectiveDate) > 0) { tag.setExpirationDate(effectiveDate); } } else if (deactivationReasons.contains(tag.getTag())) { // remove pending deactivation if it exists because we are deactivating now itr.remove(); } } ActionLog statusChangeLog = new ActionLog(); statusChangeLog.setFacility(facility); statusChangeLog.setActionDate(effectiveDate); statusChangeLog.setActionType(reason); actionLogService.saveActionLog(statusChangeLog, null); facility.setStatus(FacilityStatus.INACTIVE); } return facilityDao.save(facility); }
From source file:org.jpos.gl.GLSession.java
/** * Summarize transactions in a journal./*from w w w. j a v a 2 s . c o m*/ * * @param journal the journal. * @param start date (inclusive). * @param end date (inclusive). * @param description summary transaction's description * @return GLTransaction a summary transaction * @throws GLException if user doesn't have READ permission on this jounral. * @throws HibernateException on database/mapping errors */ public GLTransaction summarize(Journal journal, Date start, Date end, String description, short[] layers) throws HibernateException, GLException { checkPermission(GLPermission.SUMMARIZE, journal); start = Util.floor(start); end = Util.ceil(end); if (end.compareTo(start) < 0) { throw new GLException("Invalid date range " + Util.dateToString(start) + ":" + Util.dateToString(end)); } Date lockDate = journal.getLockDate(); if (lockDate != null && start.compareTo(lockDate) <= 0) { throw new GLException("Journal is locked at " + Util.dateToString(lockDate)); } setLockDate(journal, end); GLTransaction txn = new GLTransaction(description); for (int i = 0; i < layers.length; i++) { Iterator debits = findSummarizedGLEntries(journal, start, end, false, layers[i]); Iterator credits = findSummarizedGLEntries(journal, start, end, true, layers[i]); while (debits.hasNext()) { Object[] obj = (Object[]) debits.next(); txn.createDebit((FinalAccount) obj[0], (BigDecimal) obj[1], null, layers[i]); } while (credits.hasNext()) { Object[] obj = (Object[]) credits.next(); txn.createCredit((FinalAccount) obj[0], (BigDecimal) obj[1], null, layers[i]); } } txn.setJournal(journal); txn.setTimestamp(new Date()); txn.setPostDate(end); deleteGLTransactions(journal, start, end); session.save(txn); // force post - no rule validations journal.setLockDate(null); return txn; }
From source file:org.carbondata.processing.dataprocessor.dataretention.CarbonDataRetentionUtil.java
/** * This API will scan the level file and return the surrogate key for the * valid member/*from w w w .java 2s . c o m*/ * * @param levelName * @throws ParseException */ public static Map<Integer, Integer> getSurrogateKeyForRetentionMember(CarbonFile memberFile, String levelName, String columnValue, String format, Map<Integer, Integer> mapOfSurrKeyAndAvailStatus) { DataInputStream inputStream = null; Date storeDateMember = null; Date columnValDateMember = null; DataInputStream inputStreamForMaxVal = null; try { columnValDateMember = convertToDateObjectFromStringVal(columnValue, format, true); } catch (ParseException e) { LOGGER.error(e, "Not able to get surrogate key for value : " + columnValue); return mapOfSurrKeyAndAvailStatus; } try { inputStream = FileFactory.getDataInputStream(memberFile.getPath(), FileFactory.getFileType(memberFile.getPath())); long currPosIndex = 0; long size = memberFile.getSize() - 4; int minVal = inputStream.readInt(); int surrogateKeyIndex = minVal; currPosIndex += 4; // int current = 0; boolean enableEncoding = Boolean.valueOf( CarbonProperties.getInstance().getProperty(CarbonCommonConstants.ENABLE_BASE64_ENCODING, CarbonCommonConstants.ENABLE_BASE64_ENCODING_DEFAULT)); String memberName = null; while (currPosIndex < size) { int len = inputStream.readInt(); currPosIndex += 4; byte[] rowBytes = new byte[len]; inputStream.readFully(rowBytes); currPosIndex += len; if (enableEncoding) { memberName = new String(Base64.decodeBase64(rowBytes), Charset.defaultCharset()); } else { memberName = new String(rowBytes, Charset.defaultCharset()); } int surrogateVal = surrogateKeyIndex + current; current++; try { storeDateMember = convertToDateObjectFromStringVal(memberName, format, false); } catch (Exception e) { LOGGER.error(e, "Not able to get surrogate key for value : " + memberName); continue; } // means date1 is before date2 if (null != columnValDateMember && null != storeDateMember) { if (storeDateMember.compareTo(columnValDateMember) < 0) { mapOfSurrKeyAndAvailStatus.put(surrogateVal, surrogateVal); } } } } catch (IOException e) { LOGGER.error(e, "Not able to read level file for Populating Cache : " + memberFile.getName()); } finally { CarbonUtil.closeStreams(inputStream); CarbonUtil.closeStreams(inputStreamForMaxVal); } return mapOfSurrKeyAndAvailStatus; }
From source file:org.etudes.tool.melete.ModulePage.java
protected boolean validateDates(FacesContext context, ResourceLoader bundle, Date st, Date end) { Calendar calstart = new GregorianCalendar(); Calendar calend = new GregorianCalendar(); boolean errorFlag = false; if ((st != null) || (end != null)) { if (st != null) { calstart.setTime(st);/*from www . ja v a 2 s .co m*/ if (calstart.get(Calendar.YEAR) > 9999) { String errMsg = bundle.getString("year_toobig_error"); addMessage(context, "Error Message", errMsg, FacesMessage.SEVERITY_ERROR); errorFlag = true; } } if (end != null) { calend.setTime(end); if (calend.get(Calendar.YEAR) > 9999) { String errMsg = bundle.getString("year_toobig_error"); addMessage(context, "Error Message", errMsg, FacesMessage.SEVERITY_ERROR); errorFlag = true; } } // validation no 4 b if ((end != null) && (st != null)) { if (end.compareTo(st) <= 0) { String errMsg = ""; errMsg = bundle.getString("end_date_before_start"); addMessage(context, "Error Message", errMsg, FacesMessage.SEVERITY_ERROR); errorFlag = true; } } } //If there is an error, validation fails and the method returns false //If there are no errors, validation passes and the method returns true; if (errorFlag == true) return false; return true; }
From source file:org.apache.carbondata.core.scan.filter.FilterUtil.java
private static int compareFilterMembersBasedOnActualDataType(String filterMember1, String filterMember2, DataType dataType) {/*w w w. j ava 2 s . co m*/ try { if (dataType == DataTypes.SHORT || dataType == DataTypes.INT || dataType == DataTypes.LONG || dataType == DataTypes.DOUBLE) { if (CarbonCommonConstants.MEMBER_DEFAULT_VAL.equals(filterMember1)) { return 1; } Double d1 = Double.parseDouble(filterMember1); Double d2 = Double.parseDouble(filterMember2); return d1.compareTo(d2); } else if (DataTypes.isDecimal(dataType)) { if (CarbonCommonConstants.MEMBER_DEFAULT_VAL.equals(filterMember1)) { return 1; } java.math.BigDecimal val1 = new BigDecimal(filterMember1); java.math.BigDecimal val2 = new BigDecimal(filterMember2); return val1.compareTo(val2); } else if (dataType == DataTypes.DATE || dataType == DataTypes.TIMESTAMP) { if (CarbonCommonConstants.MEMBER_DEFAULT_VAL.equals(filterMember1)) { return 1; } String format = null; if (dataType == DataTypes.DATE) { format = CarbonProperties.getInstance().getProperty(CarbonCommonConstants.CARBON_DATE_FORMAT, CarbonCommonConstants.CARBON_DATE_DEFAULT_FORMAT); } else { format = CarbonProperties.getInstance().getProperty( CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, CarbonCommonConstants.CARBON_TIMESTAMP_DEFAULT_FORMAT); } SimpleDateFormat parser = new SimpleDateFormat(format); Date date1 = null; Date date2 = null; date1 = parser.parse(filterMember1); date2 = parser.parse(filterMember2); return date1.compareTo(date2); } else { return filterMember1.compareTo(filterMember2); } } catch (ParseException | NumberFormatException e) { return -1; } }
From source file:ddf.catalog.util.impl.TemporalResultComparator.java
/** * Compares the effective date between the two results. * * @return 1 if A is null and B is non-null -1 if A is non-null and B is null 0 if both A and B * are null 1 if temporal ascending and A > B; -1 if temporal ascending and B > A -1 if * temporal descending and A > B; 1 if temporal descending and B > A */// w w w . j a v a2s. co m @Override public int compare(Result contentA, Result contentB) { Date dateA = null; Date dateB = null; // Extract the temporal attribute from the Result objects passed in. // If either the result object is null or its contained metacard is null or is not a Date, // then catch the NPE and set the Result's temporal attribute to null and proceed with // the comparison. try { dateA = (Date) contentA.getMetacard().getAttribute(temporalAttribute).getValue(); } catch (NullPointerException npe) { dateA = null; } catch (ClassCastException e) { dateA = null; } try { dateB = (Date) contentB.getMetacard().getAttribute(temporalAttribute).getValue(); } catch (NullPointerException npe) { dateB = null; } catch (ClassCastException e) { dateB = null; } if (dateA == null && dateB != null) { LOGGER.debug("dateA is null and dateB is not null: " + dateB); return 1; } else if (dateA != null && dateB == null) { LOGGER.debug("dateA is not null: " + dateA + " and dateB is null"); return -1; } else if (dateA == null && dateB == null) { LOGGER.debug("both are null"); return 0; } if (SortOrder.ASCENDING.equals(sortOrder)) { return dateA.compareTo(dateB); } else if (SortOrder.DESCENDING.equals(sortOrder)) { return dateB.compareTo(dateA); } else { LOGGER.warn("Unknown order type. Returning 0."); return 0; } }
From source file:com.inkubator.hrm.service.impl.TempAttendanceRealizationServiceImpl.java
private Boolean isDateIsBetWeenTwoDates(Date dateToCheck, Date dateFrom, Date dateUntill) { Boolean isGreaterOrEqThanStartDate = dateToCheck.compareTo(dateFrom) >= 0; Boolean isLessOrEqThanEndDate = dateToCheck.compareTo(dateUntill) <= 0; return isGreaterOrEqThanStartDate && isLessOrEqThanEndDate; }