List of usage examples for java.util Calendar after
public boolean after(Object when)
Calendar
represents a time after the time represented by the specified Object
. From source file:org.structr.util.StructrLicenseManager.java
private boolean isValid(final Map<String, String> properties) { if (!licensePresent) { return false; }/*w w w . ja va 2 s . c om*/ final String src = collectLicenseFieldsForSignature(properties); final String name = properties.get(NameKey); final String key = properties.get(SignatureKey); final String hostId = properties.get(MachineKey); final String thisHostId = createHash(); final String edition = properties.get(EditionKey); final String modules = properties.get(ModulesKey); final String dateString = properties.get(DateKey); final String startDateString = properties.get(StartKey); final String endDateString = properties.get(EndKey); final String serversString = properties.get(ServersKey); final Date now = new Date(); if (StringUtils.isEmpty(key)) { logger.error("Unable to read key from license file."); return false; } try { final byte[] data = src.getBytes(CharSet); final Signature signer = Signature.getInstance(SignatureAlgorithm); final byte[] signature = Hex.decodeHex(key.toCharArray()); signer.initVerify(certificate); signer.update(data); if (!signer.verify(signature)) { logger.error("License signature verification failed, license is not valid."); return false; } } catch (Throwable t) { logger.error("Unable to verify license.", t); return false; } if (StringUtils.isEmpty(name)) { logger.error("License file doesn't contain licensee name."); return false; } if (StringUtils.isEmpty(edition)) { logger.error("License file doesn't contain edition."); return false; } if (StringUtils.isEmpty(modules)) { logger.error("License file doesn't contain modules."); return false; } if (StringUtils.isEmpty(hostId)) { logger.error("License file doesn't contain host ID."); return false; } if (StringUtils.isEmpty(dateString)) { logger.error("License file doesn't contain license date."); return false; } if (StringUtils.isEmpty(startDateString)) { logger.error("License file doesn't contain start date."); return false; } if (StringUtils.isEmpty(endDateString)) { logger.error("License file doesn't contain end date."); return false; } // verify host ID if (!thisHostId.equals(hostId) && !"*".equals(hostId)) { logger.error("Host ID found in license ({}) file does not match current host ID.", hostId); return false; } if ("*".equals(hostId)) { // check volume license against server addresses if (StringUtils.isNotBlank(serversString)) { // send HostID to server properties.put(HostIdKey, thisHostId); return checkVolumeLicense(properties, serversString); } final Calendar issuedAtPlusOneMonth = GregorianCalendar.getInstance(); final Calendar cal = GregorianCalendar.getInstance(); // set issuedAt to license date plus one month issuedAtPlusOneMonth.setTime(parseDate(dateString)); issuedAtPlusOneMonth.add(Calendar.MONTH, 1); // check that the license file was issued not more than one month ago if (cal.after(issuedAtPlusOneMonth)) { logger.error( "Development license found in license file is not valid any more, license period ended {}.", format.format(issuedAtPlusOneMonth.getTime())); return false; } } // verify that the license is valid for the current date final Date startDate = parseDate(startDateString); if (startDate != null && now.before(startDate) && !now.equals(startDate)) { logger.error("License found in license file is not yet valid, license period starts {}.", format.format(startDate.getTime())); return false; } // verify that the license is valid for the current date final Date endDate = parseDate(endDateString); if (endDate != null && now.after(endDate) && !now.equals(endDate)) { logger.error("License found in license file is not valid any more, license period ended {}.", format.format(endDate.getTime())); return false; } return true; }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.DateComparator.java
/** * Return <code>true</code> if left operand is on or before right operand, or if any of the operand is null, <code>false</code> otherwise * * * @param leftOperandValue the <code>Calendar</code> value for the left operand * @param rightOperandValue the <code>Calendar</code> value for the right operand * @param leastPrecision the least precise precision of the 2 dates * @return <code>true</code> if left operand is on or before right operand, or if any of the operand is null, <code>false</code> otherwise *//*ww w. j a v a 2 s.co m*/ private boolean isLowerThanOrEqual(final Calendar leftOperandValue, final Calendar rightOperandValue, final String leastPrecision) { if (leftOperandValue == null || rightOperandValue == null) { return true; } else { if (PRECISION_YEAR.equals(leastPrecision)) { // if year is the same, can't say for sure so return true return leftOperandValue.get(Calendar.YEAR) <= rightOperandValue.get(Calendar.YEAR); } else if (PRECISION_MONTH.equals(leastPrecision)) { return (leftOperandValue.get(Calendar.YEAR) < rightOperandValue.get(Calendar.YEAR)) || (leftOperandValue.get(Calendar.YEAR) == rightOperandValue.get(Calendar.YEAR) && leftOperandValue.get(Calendar.MONTH) <= rightOperandValue.get(Calendar.MONTH)); } else { return !leftOperandValue.after(rightOperandValue); } } }
From source file:dbtimetable.DBTimetableMIDletClass.java
public void commandAction(Command command, Displayable displayable) { if (command == List.SELECT_COMMAND) { if (mainscreen) { String selection = routeList.getString(routeList.getSelectedIndex()); routeSelectionList = new List(selection, Choice.IMPLICIT); routeSelectionList.addCommand(back); routeSelectionList.setCommandListener(this); String[] subroutes = (String[]) routelistTable.get(selection); for (int i = 0; i < subroutes.length; i++) { routeSelectionList.append(subroutes[i], null); }// w w w .j a v a 2 s .co m display.setCurrent(routeSelectionList); mainscreen = false; } else { String selection = routeSelectionList.getString(routeSelectionList.getSelectedIndex()); String filename = (String) subroutelistTable.get(selection); String the_filename = ""; form = new Form(selection); form.addCommand(back_to_main); form.setCommandListener(this); Calendar current_time = DateHelper.timenow(); // Fetching the 1st day's listing if (is_weekdays(DateHelper.timenow()) && (!(is_public_holiday_check(DateHelper.timenow())))) { the_filename = filename + "_Weekdays.txt"; } else if (is_sunday(DateHelper.timenow()) || is_public_holiday_check(DateHelper.timenow())) { the_filename = filename + "_Sunday_and_Public_Holiday.txt"; } else if (is_saturday(DateHelper.timenow())) { the_filename = filename + "_Saturday.txt"; } String timetable_file = readFile("/" + the_filename); String[] timetable_readlines = DateHelper.splitWithUnix(timetable_file); int counter = 0; for (int i = 0; i < timetable_readlines.length; i++) { Calendar the_timeslot = DateHelper.time_of_slot(timetable_readlines[i].substring(0, 2), timetable_readlines[i].substring(3, 5)); if (the_timeslot.after(current_time)) { /* System.out.println("Time should be: " + timetable_readlines[i].substring(0, 2) + ":" + timetable_readlines[i].substring(3, 5) + " with " + ( the_timeslot.getTime().getTime() - current_time.getTime().getTime() ) / 1000 / 60 + " minutes |" + the_timeslot); */ if (counter < 5) { form.append(timetable_readlines[i] + " (" + (the_timeslot.getTime().getTime() - current_time.getTime().getTime()) / 1000 / 60 + " mins left)\n"); } else { form.append(timetable_readlines[i] + "\n"); } counter++; } } if (counter < 10) { // Fetching the second's day listing Calendar tomorrow = Calendar.getInstance(TimeZone.getTimeZone("GMT+8")); long difftime = DateHelper.timenow().getTime().getTime() + 24 * 60 * 60 * 1000; tomorrow.setTime(new Date(difftime)); if (is_weekdays(tomorrow) && (!(is_public_holiday_check(tomorrow)))) { the_filename = filename + "_Weekdays.txt"; } else if (is_sunday(tomorrow) || is_public_holiday_check(tomorrow)) { the_filename = filename + "_Sunday_and_Public_Holiday.txt"; } else if (is_saturday(tomorrow)) { the_filename = filename + "_Saturday.txt"; } timetable_file = readFile("/" + the_filename); timetable_readlines = DateHelper.splitWithUnix(timetable_file); for (int i = 0; i < timetable_readlines.length; i++) { Calendar the_timeslot = DateHelper.time_of_slot_tomorrow( timetable_readlines[i].substring(0, 2), timetable_readlines[i].substring(3, 5)); if (the_timeslot.after(current_time)) { /* System.out.println("Time should be: " + timetable_readlines[i].substring(0, 2) + ":" + timetable_readlines[i].substring(3, 5) + " with " + ( the_timeslot.getTime().getTime() - current_time.getTime().getTime() ) / 1000 / 60 + " minutes |" + the_timeslot); */ if (counter < 5) { form.append(timetable_readlines[i] + " (" + (the_timeslot.getTime().getTime() - current_time.getTime().getTime()) / 1000 / 60 + " mins left)\n"); } else { form.append(timetable_readlines[i] + "\n"); } counter++; } } } display.setCurrent(form); mainscreen = true; // System.out.println( table_content); } } else if (command == back) { System.out.println("--> Back triggered"); display = Display.getDisplay(this); display.setCurrent(routeList); mainscreen = true; } else if (command == back_to_main) { display = Display.getDisplay(this); display.setCurrent(routeList); mainscreen = true; } else if (command == about) { alert = new Alert("About DBTimetable", help_text, null, null); alert.setTimeout(Alert.FOREVER); alert.setType(AlertType.INFO); display.setCurrent(alert); } else if (command == exit) { destroyApp(false); notifyDestroyed(); } }
From source file:com.stasbar.knowyourself.alarms.AlarmStateManager.java
/** * Fix and update all alarm instance when a time change event occurs. * * @param context application context/*from w w w . j av a2 s . co m*/ */ public static void fixAlarmInstances(Context context) { // Register all instances after major time changes or when phone restarts final ContentResolver contentResolver = context.getContentResolver(); final Calendar currentTime = getCurrentTime(); // Sort the instances in reverse chronological order so that later instances are fixed or // deleted before re-scheduling prior instances (which may re-create or update the later // instances). final List<AlarmInstance> instances = AlarmInstance.getInstances(contentResolver, null /* selection */); Collections.sort(instances, new Comparator<AlarmInstance>() { @Override public int compare(AlarmInstance lhs, AlarmInstance rhs) { return rhs.getAlarmTime().compareTo(lhs.getAlarmTime()); } }); for (AlarmInstance instance : instances) { final Alarm alarm = Alarm.getAlarm(contentResolver, instance.mAlarmId); if (alarm == null) { unregisterInstance(context, instance); AlarmInstance.deleteInstance(contentResolver, instance.mId); LogUtils.e("Found instance without matching alarm; deleting instance %s", instance); continue; } final Calendar priorAlarmTime = alarm.getPreviousAlarmTime(instance.getAlarmTime()); final Calendar missedTTLTime = instance.getMissedTimeToLive(); if (currentTime.before(priorAlarmTime) || currentTime.after(missedTTLTime)) { final Calendar oldAlarmTime = instance.getAlarmTime(); final Calendar newAlarmTime = alarm.getNextAlarmTime(currentTime); final CharSequence oldTime = DateFormat.format("MM/dd/yyyy hh:mm a", oldAlarmTime); final CharSequence newTime = DateFormat.format("MM/dd/yyyy hh:mm a", newAlarmTime); LogUtils.i("A time change has caused an existing alarm scheduled to fire at %s to" + " be replaced by a new alarm scheduled to fire at %s", oldTime, newTime); // The time change is so dramatic the AlarmInstance doesn't make any sense; // remove it and schedule the new appropriate instance. AlarmStateManager.deleteInstanceAndUpdateParent(context, instance); } else { registerInstance(context, instance, false /* updateNextAlarm */); } } updateNextAlarm(context); }
From source file:com.androidinspain.deskclock.alarms.AlarmStateManager.java
/** * Fix and update all alarm instance when a time change event occurs. * * @param context application context/*from ww w . ja v a2 s .co m*/ */ public static void fixAlarmInstances(Context context) { LogUtils.i("Fixing alarm instances"); // Register all instances after major time changes or when phone restarts final ContentResolver contentResolver = context.getContentResolver(); final Calendar currentTime = getCurrentTime(); // Sort the instances in reverse chronological order so that later instances are fixed or // deleted before re-scheduling prior instances (which may re-create or update the later // instances). final List<AlarmInstance> instances = AlarmInstance.getInstances(contentResolver, null /* selection */); Collections.sort(instances, new Comparator<AlarmInstance>() { @Override public int compare(AlarmInstance lhs, AlarmInstance rhs) { return rhs.getAlarmTime().compareTo(lhs.getAlarmTime()); } }); for (AlarmInstance instance : instances) { final Alarm alarm = Alarm.getAlarm(contentResolver, instance.mAlarmId); if (alarm == null) { unregisterInstance(context, instance); AlarmInstance.deleteInstance(contentResolver, instance.mId); LogUtils.e("Found instance without matching alarm; deleting instance %s", instance); continue; } final Calendar priorAlarmTime = alarm.getPreviousAlarmTime(instance.getAlarmTime()); final Calendar missedTTLTime = instance.getMissedTimeToLive(); if (currentTime.before(priorAlarmTime) || currentTime.after(missedTTLTime)) { final Calendar oldAlarmTime = instance.getAlarmTime(); final Calendar newAlarmTime = alarm.getNextAlarmTime(currentTime); final CharSequence oldTime = DateFormat.format("MM/dd/yyyy hh:mm a", oldAlarmTime); final CharSequence newTime = DateFormat.format("MM/dd/yyyy hh:mm a", newAlarmTime); LogUtils.i("A time change has caused an existing alarm scheduled to fire at %s to" + " be replaced by a new alarm scheduled to fire at %s", oldTime, newTime); // The time change is so dramatic the AlarmInstance doesn't make any sense; // remove it and schedule the new appropriate instance. AlarmStateManager.deleteInstanceAndUpdateParent(context, instance); } else { registerInstance(context, instance, false /* updateNextAlarm */); } } updateNextAlarm(context); }
From source file:org.op4j.MiscTest.java
@Test public void test() throws Exception { final StopWatch watch = new StopWatch(); watch.start();//from w w w. j av a 2 s . c o m final String[] stringsArr1 = new String[] { "Hello", "Goodbye", null }; final List<String> stringsList1 = Arrays.asList(stringsArr1); final String[][] stringsStrings1 = new String[][] { new String[] { "Hello!", "Goodbye!" }, new String[] { "Hola!", "Adis!" } }; final List<String>[] stringsListStrings1 = (List<String>[]) new List<?>[] { Arrays.asList(new String[] { "Hello!", "Goodbye!" }), Arrays.asList(new String[] { "Hola!", "Adis!" }) }; final List<List<String>> stringsListStringsList1 = Arrays.asList(stringsListStrings1); final Map<String, String> map1 = new LinkedHashMap<String, String>(); map1.put("es", "Hola!"); map1.put("en", "Hello!"); map1.put("gl", "Ola!"); map1.put("ca", "Hola!"); final Map<String, String> map2 = new LinkedHashMap<String, String>(); map2.put("es", "Adis!"); map2.put("en", "Goodbye!"); map2.put("gl", "Adus!"); map2.put("ca", "Adu!"); map2.put("fr", "Adieu!"); final Map<String, String>[] maps1 = (Map<String, String>[]) new Map<?, ?>[] { map1, map2 }; System.out.println(Op.onList(stringsList1).get()); System.out.println(Op.onList(stringsList1).forEach().get()); final BigDecimal bd = new BigDecimal("3455234.6325"); final Float f = Float.valueOf(3455234.6325f); final Double d = Double.valueOf(3455234.6325); System.out.println(bd.doubleValue()); System.out.println(f); System.out.println(d); System.out.println( Op.onList(Arrays.asList(new Integer[] { 2, 3, 4, 1, 2, 2, 4, 5, 2, 3, 5, 6, 87, 45, 2, 3, 34, 1 })) .get()); System.out.println( Op.onList(Arrays.asList(new Integer[] { 2, 3, 4, 1, 2, 2, 4, 5, 2, 3, 5, 6, 87, 45, 2, 3, 34, 1 })) .distinct().get()); final List<List<String>> listOfListOfString1 = Arrays.asList((List<String>[]) new List<?>[] { Arrays.asList(new String[] { "a", "b", "a" }), Arrays.asList(new String[] { "a", "b", "a" }) }); final Set<Set<String>> setOfsetOfString1 = new LinkedHashSet<Set<String>>( Arrays.asList((Set<String>[]) new Set<?>[] { new LinkedHashSet<String>(Arrays.asList(new String[] { "a", "b", "a" })), new LinkedHashSet<String>(Arrays.asList(new String[] { "a", "b", "a" })) })); final String[][] arrayOfArrayOfString1 = new String[][] { new String[] { "a", "b", "a" }, new String[] { "a", "b", "a" } }; System.out.println(Op.onList(stringsList1).addAll("World!", "Mars!").get()); System.out.println(Op.onList(stringsList1).insertAll(1, "World!", "Mars!").get()); System.out.println(Op.onList(stringsList1).addAll(stringsList1).get()); System.out.println(Op.onList(stringsList1).get()); System.out.println(Op.onList(stringsList1).removeAllIndexes(0, 2).get()); System.out.println(Op.onList(stringsList1).removeAllIndexesNot(0).get()); System.out.println(Op.onList(stringsList1).removeAllIndexesNot(0, 2).get()); System.out.println(Op.onList(stringsList1).removeAllTrue(new IFunction<String, Boolean>() { public Boolean execute(String target, final ExecCtx ctx) { return Boolean.valueOf(target == null); } }).get()); System.out.println(Op.onList(stringsList1).removeAllNull().get()); System.out.println("================"); final Set<String> stringSet1 = new LinkedHashSet<String>(stringsList1); System.out.println(Op.onSet(stringSet1).addAll("World!", "Mars!").get()); System.out.println(Op.onSet(stringSet1).insertAll(1, "World!", "Mars!").get()); System.out.println(Op.onSet(stringSet1).addAll(stringsList1).get()); System.out.println("---"); System.out.println(Op.onSet(stringSet1).get()); System.out.println(Op.onSet(stringSet1).removeAllIndexes(0, 2).get()); System.out.println(Op.onSet(stringSet1).removeAllIndexesNot(0).get()); System.out.println(Op.onSet(stringSet1).removeAllIndexesNot(0, 2).get()); System.out.println(Op.onSet(stringSet1).removeAllNull().get()); System.out.println( printArray(Op.onArrayOf(Types.STRING, stringsArr1).insertAll(2, "lalero", "lururu").get())); System.out.println(Op.onMap(map1).put("fr", "All!").get()); System.out.println(Op.onMap(map1).insert(0, "fr", "All!").get()); System.out.println(Op.onMap(map1).insert(2, "fr", "All!").get()); System.out.println(Op.onMap(map2).get()); System.out.println(Op.onMap(map2).putAll(Op.onMap(map1).insert(0, "gl", "Meuuuu!").get()).get()); System.out.println(Op.onListFor(234, 12, 231)); System.out.println(Op.onListFor(234).addAll(10)); System.out.println(Op.onListFor(234).insert(0, 10)); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3)); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).addAll((Integer) null)); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).addAll((Integer) null).removeAllNull()); System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).removeAllIndexesNot(1)); System.out.println(printArray(Op.on(234).intoSingletonArrayOf(Types.INTEGER).addAll(8).get())); System.out.println(Op.on((List) null).addAll(123)); System.out.println(Op.on((Object) null).intoSingletonList().get()); System.out.println(Op.on((Object) null).intoSingletonSet().get()); System.out.println(printArray(Op.on((String) null).intoSingletonArrayOf(Types.STRING).addAll("a") .removeAllNull().removeAllIndexes(0).get())); // System.out.println(printArray(Op.buildArrayOfArray(Types.STRING).addAll(Op.buildArray(Types.STRING).addAll("a","b").get()).addAll(Op.buildArray(Types.STRING).addAll("1","2","3").get()).get())); // System.out.println(Op.buildMap(Types.INTEGER,Types.STRING).put(12,"hello!").get()); System.out.println(Op.onListFor("a", 1, "b", 3).couple().get()); System.out.println(Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").sort().get()); System.out.println( Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").toSet().sort(new Comparator<String>() { public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return -1; } else if (o1.length() == o2.length()) { return 0; } return 1; } }).get()); System.out.println(printArray( Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").toArrayOf(Types.STRING).sort().get())); System.out.println(printArray(Op.onListFor("hello", "goodbye", "adios", "ciao", "hola") .toArrayOf(Types.STRING).sort(new Comparator<String>() { public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return -1; } else if (o1.length() == o2.length()) { return 0; } return 1; } }).get())); System.out.println( Op.on("12314123.4123").exec(FnString.toInteger(RoundingMode.CEILING, DecimalPoint.IS_POINT)).get()); System.out.println( Op.on("12314123.4123").exec(FnString.toInteger(RoundingMode.CEILING, DecimalPoint.IS_POINT)).get()); System.out.println(Op.on("12314123").exec(FnString.toInteger()).get()); System.out.println(Op.on("12314123").exec(FnString.toLong()).get()); System.out.println(Op.on("12314123").exec(FnString.toBigInteger()).get()); System.out.println(Op.on("12314123.4123").exec(FnString.toDouble()).get()); System.out.println(Op.on("12314123.4123").exec(FnString.toDouble(3, RoundingMode.CEILING)).get()); System.out.println(Op.on("12314123.4123").exec(FnString.toBigDecimal(3, RoundingMode.CEILING)).get()); final SimpleDateFormat dateFormat = new SimpleDateFormat(); System.out.println(dateFormat .format(Op.on(Calendar.getInstance()).exec(FnCalendar.truncate(Calendar.DATE)).get().getTime())); System.out.println(dateFormat .format(Op.on("25/nov/1979").exec(FnString.toCalendar("dd/MMM/yyyy", "es")).get().getTime())); // System.out.println(dateFormat.format(Op.onAll(1979, 11, 25, 12, 30).buildList().exec(ToCalendar.fromString("dd/MMM/yyyy", "es")).get().getTime())); System.out.println(dateFormat.format(Op.on(Op.onListFor(1979, 11, 25, 12, 30).get()) .exec(FnCalendar.fieldIntegerListToCalendar()).get().getTime())); System.out.println(dateFormat.format(Op.on(Op.onListFor("1979", "11", "25", "12", "30").get()) .toArrayOf(Types.STRING).exec(FnCalendar.fieldStringArrayToCalendar()).get().getTime())); System.out.println(Op.on(Op.onListFor(1979, 11, 25, 12, 30).get()).exec(FnList.ofInteger().sort()).get()); System.out.println(Op.on(Op.onSetFor(1979, 11, 25, 12, 30).get()).exec(FnSet.ofInteger().sort()).get()); System.out.println(Op.on(Op.onListFor(1979, 11, 25, 12, 30, 1980, 2, 43, 12, 11).get()) .exec(FnList.ofInteger().distinct()).get()); System.out.println(Op.on("hello").intoSingletonList().get()); System.out.println(printArray(Op.on("hello").intoSingletonArrayOf(Types.STRING).get())); // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar(DateStyle.FULL, TimeStyle.NONE, Locale.UK)).get()); // // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar(DateStyle.FULL, TimeStyle.SHORT, Locale.UK)).get()); // // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar("dd-MMM-yyyy", Locale.UK)).get()); // // System.out.println(Op.buildList(Types.CALENDAR) // .addAll(Calendar.getInstance(), Calendar.getInstance()) // .forEach().exec(ToString.fromCalendar("dd-MMMM-yyyy")).get()); // // System.out.println(Op.buildList(Types.DATE) // .addAll(new java.sql.Date(Calendar.getInstance().getTimeInMillis())) // .forEach().exec(ToString.fromDate("dd-MMM-yyyy", Locale.UK)).get()); // // // System.out.println(Op.buildList(Types.STRING) // .addAll(" Company ", " day ") // .forEach().exec(StringFuncs.trim()).get()); // System.out.println(Op.buildList(Types.STRING) // .addAll(" Company ", " day ") // .forEach().exec(StringFuncs.trim()).exec(StringFuncs.toUpperCase()).get()); System.out.println(Op.on("Dublin").exec(FnString.toHexadecimal(Charset.forName("ISO-8859-1"))) .exec(FnString.fromHexadecimal(Charset.forName("ISO-8859-1"))).get()); // System.out.println(Op.buildList(Types.NUMBER) // .addAll(45.9, new BigDecimal(34.456)) // .forEach().exec(ToString.fromCurrency(Locale.getDefault(), // 1, 2, 10, true)).get()); // System.out.println(Op.buildList(Types.NUMBER) // .addAll(45.9, 45, new BigDecimal(34.456)) // .forEach().exec(ToString.fromCurrency(Locale.getDefault(), // 1, 0, 0, true)).get()); // // System.out.println(Op.buildList(Types.NUMBER) // .addAll(45.9, 45, new BigDecimal(34.456), 0, 0.5, 0.211) // .forEach().exec(ToString.fromPercent(Locale.getDefault(), // 1, 0, 10, ',', '\'', false)).get()); System.out.println(Op.onArrayOf(Types.STRING, stringsArr1).toSet().get()); final List<String[]> listOfStringArray1 = new ArrayList<String[]>(); listOfStringArray1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toArrayOf(Types.STRING).get()); listOfStringArray1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toArrayOf(Types.STRING).get()); final List<Set<String>> listOfStringSet1 = new ArrayList<Set<String>>(); listOfStringSet1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toSet().get()); listOfStringSet1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toSet().get()); final Set<String[]> setOfStringArray1 = new LinkedHashSet<String[]>(); setOfStringArray1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toArrayOf(Types.STRING).get()); setOfStringArray1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toArrayOf(Types.STRING).get()); final Set<List<String>> setOfStringList1 = new LinkedHashSet<List<String>>(); setOfStringList1.add(Op.onArrayFor("Hola", "Hello", "Ciao", "Ola").toList().get()); setOfStringList1.add(Op.onArrayFor("Adios", "Goodbye", "Ciao", "Adus").toList().get()); final Set<Set<String>> setOfStringSet1 = new LinkedHashSet<Set<String>>(); setOfStringSet1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toSet().get()); setOfStringSet1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toSet().get()); System.out.println(Op.on("http://www.google.es/search?q=op4j&unusedParam=unusedValue '' 2^2 ") .exec(FnString.escapeJavaScript()).get()); System.out.println( Op.on("Body tag is written like \"<body>content here</body>\"").exec(FnString.escapeHTML()).get()); System.out.println("***___****___****"); System.out.println(Op.onList(stringsList1).forEach().ifNotNull().exec(FnString.toUpperCase()).get()); System.out.println("***___****___****"); System.out.println(Op.onList(listOfListOfString1).get()); // System.out.println(Op.onMap(map1).forEachEntry().exec(Ognl.forString("'in ' + #target.key + ' you say ' + #target.value")).get()); System.out.println(Op.onList(stringsList1).removeAllNull().sort().get()); // final List<Map<String,String>> listOfMapOfStringString1 = // Op.buildList(Types.MAP_OF_STRING_STRING).add(map1).add(map2).get(); // // System.out.println(printArray(Op.onListOfMap(listOfMapOfStringString1).toArrayOfMap().get())); System.out.println(Types.LIST_ITERATOR_OF_BOOLEAN.getSimpleName()); System.out.println(Op.onList(stringsList1).get()); System.out.println(Op.onList(stringsList1).forEach().replaceWith("op4j is great!").get()); System.out.println(Op.onList(stringsList1).forEach().replaceIfNullWith("op4j is great!").get()); System.out.println(printArray( Op.onArrayOf(Types.STRING, stringsArr1).forEach().replaceIfNullWith("op4j is great!").get())); System.out.println(printArray(Op.onArrayOf(Types.STRING, stringsArr1) .replaceWith(new String[] { "alpha", "beta" }).forEach().exec(FnString.toUpperCase()).get())); // System.out.println(Op.buildListOfList(Types.STRING).add(stringsList1).add(stringsList1).get()); // System.out.println(Op.buildListOfList(Types.STRING).addAll(stringsList1, stringsList1).get()); Op.on(Integer.valueOf(12)).exec(FnObject.intoSingletonArrayOf(Types.INTEGER)).get(); watch.stop(); System.out.println("TIME: " + watch.toString()); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); System.out.println("**********************"); List<String> list = Arrays.asList(new String[] { "12/10/1492", "6/12/1978", "15/07/2045", null }); Set<String> set1 = new LinkedHashSet<String>(list); Set<String> set2 = Op.on(list).toSet().get(); System.out.println("set1 : " + set1); System.out.println("set2 : " + set2); Set<Calendar> set3 = Op.on(list).toSet().forEach().exec(FnString.toCalendar("dd/MM/yyyy")).get(); System.out.println("set3asStr : " + Op.on(set3).map(FnCalendar.toStr("EEEE dd MMMM yyyy")).get()); Set<Calendar> set4 = Op.on(list).toSet().removeAllNull().forEach().exec(FnString.toCalendar("dd/MM/yyyy")) .get(); System.out.println( "set4asStr : " + Op.on(set4).map(FnCalendar.toStr("EEEE dd MMMM yyyy", new Locale("en"))).get()); Set<Calendar> set5 = Op.on(list).toSet().removeAllNull().map(FnString.toCalendar("dd/MM/yyyy")).get(); System.out.println( "set5asStr : " + Op.on(set5).map(FnCalendar.toStr("EEEE dd MMMM yyyy", new Locale("en"))).get()); Calendar now = Calendar.getInstance(); Set<Calendar> set6 = Op.on(list).toSet().map(FnString.toCalendar("dd/MM/yyyy")) .removeAllNullOrTrue(FnCalendar.after(now)).get(); System.out.println("set6asStr : " + Op.on(set6).map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get()); // **************************** // WARNING: Non-op4j code!! // **************************** SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy"); Set<Calendar> set = new LinkedHashSet<Calendar>(); for (String element : list) { if (element != null) { Date date = null; try { date = dateFormat1.parse(element); } catch (ParseException e) { throw new RuntimeException(e); } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(date.getTime()); if (!calendar.after(now)) { set.add(calendar); } } } System.out.println("setasStr : " + Op.on(set).map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get()); Function<List<String>, Set<Calendar>> conversionFunction = Fn.onListOf(Types.STRING).toSet() .map(FnString.toCalendar("dd/MM/yyyy")).removeAllNullOrTrue(FnCalendar.after(now)).get(); System.out.println("setFnasStr : " + Op.on(conversionFunction.execute(list)) .map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get()); int[] v1 = new int[] { 3, 2, 1, 3 }; long[] v2 = new long[] { 3, 2, 1, 3 }; Op.on(1).get(); List<Integer> iL = Op.onListFor(2, 1, 4, 213).get(); System.out.println(iL); System.out.println(Arrays.asList(Op.on(v1).forEach().exec(FnInteger.add(Integer.valueOf(10))).get())); Op.on(v2).forEach().get(); Op.on(123).exec(new IFunction<Integer, String>() { public String execute(Integer input, ExecCtx ctx) throws Exception { return "The input number is: " + input; } }).get(); System.out.println(Op.on(23.24).exec(FnDouble.add(43)).get()); System.out.println(Op.on(BigDecimal.valueOf(23.24)).exec(FnBigDecimal.add(1.2)).get()); System.out.println(Op.onListFor(30, 30, 40).map(FnNumber.toBigInteger()) .exec(FnBigInteger.avg(RoundingMode.CEILING)).get()); System.out.println(Op.on(10).exec(FnInteger.divideBy(3, RoundingMode.CEILING)).get()); Function<Integer, Boolean> fnAnd1 = FnBoolean.and(FnObject.eq("lala"), FnNumber.notEq(534)); System.out.println(Op.on(233).exec(FnBoolean.and(FnNumber.greaterThan(44), FnObject.lessThan(534))).get()); System.out.println( Op.on(1233).ifTrue(FnBoolean.not(FnBoolean.and(FnNumber.greaterThan(44), FnObject.lessThan(534)))) .exec(FnInteger.add(10)).get()); System.out.println(Op.on(1233).exec(FnFunc.chain(FnInteger.add(10), FnNumber.greaterThan(1200))).get()); System.out.println(Op.onListFor(1, 2, 3, 4).exec(FnList.ofInteger().containsAny(12, 3)).get()); String[] arr231 = new String[] { "be", "a", "31aa", "31_l", "31A" }; System.out.println(Arrays.asList(FnArray.ofString().sort().execute(arr231))); System.out .println(Arrays.asList(FnArray.ofString().sortBy(Call.methodForInteger("length")).execute(arr231))); System.out .println(FnList.ofString().sortBy(Call.methodForInteger("length")).execute(Arrays.asList(arr231))); String[] datesStr = new String[] { "12-10-1492", "06-12-1978" }; List<Calendar> dates = Op.on(datesStr).toList().map(FnString.toCalendar("dd-MM-yyyy")).get(); System.out.println(Op.on(dates).map(FnCalendar.toStr("yyyy, MMMM dd", new Locale("gl", "ES"))).get()); Function<Integer, Boolean> afnb1 = new Function<Integer, Boolean>() { public Boolean execute(Integer input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> afnb2 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Integer, Boolean> afnb = FnBoolean.and(afnb1, afnb2); Function<Number, Boolean> bfnb1 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Integer, Boolean> bfnb2 = new Function<Integer, Boolean>() { public Boolean execute(Integer input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Integer, Boolean> bfnb = FnBoolean.and(bfnb1, bfnb2); Op.on(231).ifTrue(afnb).get(); Op.on(231).ifTrue(bfnb).get(); Op.on(231).ifTrue(FnBoolean.and(afnb1, afnb2)).get(); Op.on(231).ifTrue(FnBoolean.and(bfnb1, bfnb2)).get(); Function<Object, Boolean> cfnb1 = new Function<Object, Boolean>() { public Boolean execute(Object input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> cfnb2 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> cfnb = FnBoolean.and(cfnb1, cfnb2); Function<Number, Boolean> dfnb1 = new Function<Number, Boolean>() { public Boolean execute(Number input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Object, Boolean> dfnb2 = new Function<Object, Boolean>() { public Boolean execute(Object input, ExecCtx ctx) throws Exception { return Boolean.TRUE; } }; Function<Number, Boolean> dfnb = FnBoolean.and(dfnb1, dfnb2); Op.on(231.2).ifTrue(cfnb).get(); Op.on(231.1).ifTrue(dfnb).get(); Op.on(231.2).ifTrue(FnBoolean.and(cfnb1, cfnb2)).get(); Op.on(231.1).ifTrue(FnBoolean.and(dfnb1, dfnb2)).get(); Function<Number, Integer> fnz1 = new Function<Number, Integer>() { public Integer execute(Number input, ExecCtx ctx) throws Exception { // TODO Auto-generated method stub return null; } }; Function<Integer, Integer> fnn1 = FnFunc.ifTrueThen(Types.INTEGER, FnNumber.greaterThan(2), fnz1); Fn.on(Types.INTEGER).exec(FnFunc.ifTrueThen(Types.NUMBER, FnNumber.greaterThan(2), fnz1)).get(); BigInteger biValue = BigInteger.valueOf(-1256565646); System.out.println("Starting value = " + biValue); BigInteger biOpResult = Op.on(biValue).exec(FnBigInteger.divideBy(BigInteger.valueOf(23))) .exec(FnBigInteger.pow(3)).exec(FnBigInteger.subtract(BigInteger.valueOf(5))) .exec(FnBigInteger.abs()).get(); System.out.println("With op4j: " + biOpResult); BigInteger biNorResult = biValue.divide(BigInteger.valueOf(23)).pow(3).subtract(BigInteger.valueOf(5)) .abs(); System.out.println("Without op4j: " + biNorResult); BigInteger biOpResult1 = Op.on(biValue).exec(FnBigInteger.divideBy(BigInteger.valueOf(23))).get(); System.out.println("[1] With op4j: " + biOpResult1); BigInteger biNorResult1 = biValue.divide(BigInteger.valueOf(23)); System.out.println("[1] Without op4j: " + biNorResult1); BigDecimal biOpResult1d = Op.on(new BigDecimal(biValue)) .exec(FnBigDecimal.divideBy(BigDecimal.valueOf(23.0), RoundingMode.DOWN)).get(); System.out.println("[1D] With op4j: " + biOpResult1d); BigDecimal biNorResult1d = new BigDecimal(biValue).divide(BigDecimal.valueOf(23.0), RoundingMode.DOWN); System.out.println("[1D] Without op4j: " + biNorResult1d); System.out .println( Op.on(Types.STRING, null) .exec(FnFunc.ifTrueThen(Types.STRING, FnBoolean.or(FnObject.isNull(), FnBoolean.and(FnObject.isNotNull(), FnFunc.chain(FnString.toInteger(), FnNumber.greaterThan(100)))), FnObject.replaceWith("lelo"))) .get()); System.out.println(Arrays.asList(Op.onArrayFor(4, 2).get())); System.out.println(Op.on("hello").zipKey(98).get()); System.out.println(Op.onListFor("en", "en", "es", "gl", "fr") .zipAndGroupValues("hello", "goodbye", "hola", "ola", "all").get()); System.out.println(Op.onListFor("hello", "goodbye", "hola", "ola", "all") .zipAndGroupKeys("en", "en", "es", "gl", "fr").get()); System.out.println(Op.onArrayFor("hello", "goodbye", "hola", "ola", "all") .zipAndGroupKeys("en", "en", "es", "gl", "fr").get()); System.out.println(Op.onMapFor(23, "twenty-three").and(43, "forty-three").and(10, "ten").sort().get()); System.out.println(Arrays.asList(Op.onArrayFor(1, 2, 1, 2, 2) .zipAndGroupValues(Types.STRING, "a", "b", "c", "d", "e").get().get(1))); System.out.println( Op.on("hello").ifTrue(FnString.notEq("uncapitalizable")).exec(FnString.toUpperCase()).get()); System.out.println(Op.on("uncapitalizable").ifTrue(FnString.notEq("uncapitalizable")) .exec(FnString.toUpperCase()).get()); Map<String, Integer> agesByName = Op.onListFor(27, 49, 19).zipKeys("John", "Mary", "Derek").get(); System.out.println(agesByName); Map<String, String> capitals = Op .onListFor("Spain", "Madrid", "United Kingdom", "London", "France", "Paris").couple().get(); System.out.println(capitals); String date = "06/12/1978"; Calendar cal = Op.on(date).exec(FnString.toCalendar("dd/MM/yyyy")).get(); System.out.println(dateFormat.format(cal.getTime())); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date dt = sdf.parse("06/12/1978"); Calendar c = Calendar.getInstance(); c.setTime(dt); System.out.println(dateFormat.format(c.getTime())); System.out.println(Op.onListFor(2, 12, 42, 5, 9, 24) .mapIfTrue(FnNumber.lessOrEqTo(10), FnObject.replaceWith("<"), FnObject.replaceWith(">")).get()); System.out.println(Op.on("LO E I N OR! ae").exec(FnString.asciify()).get()); System.out.println(Op.on(" a nu NU nu NU ").exec(FnString.asciify()).get()); System.out.println(Op.on("").exec(FnString.asciify()).get()); Pair<Integer, Integer> p = Op.on(dt).exec(FnTuple.pairWith(Call.i("getYear"), Get.i("month"))).get(); System.out.println(p); Integer i10 = Op.on(dt).exec(FnTuple.pairWith(Call.i("getYear"), Get.i("month"))) .exec(FnTuple.getValue1Of(Types.INTEGER)).get(); System.out.println(i10); }
From source file:com.virtusa.akura.reporting.controller.GenarateTeacherWisePresentAndAbsentDaysReportController.java
/** * Perform the logic of the controller to generate Teacher Wise Attendance Report . * * @param teacherWisePresentAbsentTemplate of type TeacherWisePresentAbsentTemplate * @param request of type HttpServletRequest * @param response of type HttpServletResponse * @param errors of type BindingResult/* w w w . j a va 2 s . c o m*/ * @return java.lang.String * @param map of type ModelMap * @throws AkuraAppException AkuraAppException * @throws ParseException ParseException */ @RequestMapping(method = RequestMethod.POST) public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(TEMPLATENAME) TeacherWisePresentAbsentTemplate teacherWisePresentAbsentTemplate, BindingResult errors, ModelMap map) throws AkuraAppException, ParseException { String selectedClass = request.getParameter(SELECTED_CLASS); String selectedAddmissionWithName = request.getParameter(SELECTED_ADDMISSION); ModelAndView modelAndView = new ModelAndView(); Map<String, Object> params = new HashMap<String, Object>(); params.put(DATE_DEPARTURE_FIELD, AkuraWebConstant.EMPTY_STRING); params.put(DATE_TO_FIELD, teacherWisePresentAbsentTemplate.getDateTo()); String selectedAddmission = null; if (selectedAddmissionWithName != null) { String[] selectedAdmissionArray = selectedAddmissionWithName.split("-"); selectedAddmission = selectedAdmissionArray[0].trim(); } if (selectedAddmission != null) { teacherWisePresentAbsentTemplate.setTeacherRegNo(selectedAddmission); } if (selectedAddmission == null) { String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED); map.addAttribute(MESSAGE, message); StaffCategory staffCategory = staffCommonService.getStaffCategory(Integer.parseInt(selectedClass)); if (staffCategory != null) { map.addAttribute(MODEL_ATT_SELECTED_CLASS_GRADE_ID, staffCategory.getCatogaryID()); } modelAndView.setViewName(MODELANDVIEW); return modelAndView; } presentAndAbsentDaysValidator.validate(teacherWisePresentAbsentTemplate, errors); if (errors.hasErrors()) { return setPreviousDataWhileError(map, selectedClass, selectedAddmission, modelAndView); } if (selectedClass.equals(AkuraWebConstant.STRING_ZERO)) { String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED); map.addAttribute(MESSAGE, message); return setPreviousDataWhileError(map, selectedClass, selectedAddmission, modelAndView); } String teacherRegNo = teacherWisePresentAbsentTemplate.getTeacherRegNo(); int staffId = staffService.findStaffIdForRegistrationNo(teacherRegNo); if (staffId == 0) { errors.rejectValue(FIELD_NAME, STAFFID_ERROR_MSG); modelAndView.setViewName(MODELANDVIEW); return modelAndView; } Staff staff = staffService.findStaff(staffId); String year = AkuraWebConstant.EMPTY_STRING; if (staff.getDateOfDeparture() != null) { year = DateUtil.getStringYear(staff.getDateOfDeparture()); } TeacherAttendance tempTAa = new TeacherAttendance(); List<TeacherAttendance> absentList = new ArrayList<TeacherAttendance>(); if (year != AkuraWebConstant.EMPTY_STRING) { Date departureDateObj = staff.getDateOfDeparture(); tempTAa.setDateOfDeparture(DateUtil.getFormatDate(departureDateObj)); teacherWisePresentAbsentTemplate.setDateTo(DateUtil.getFormatDate(departureDateObj)); params.put(DATE_DEPARTURE_FIELD, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, DATE_DEPARTURE_FIELD_KEY)); params.put(DEPARTURE_DATE_VALUE, DateUtil.getFormatDate(departureDateObj)); } else { params.put(DEPARTURE_DATE_VALUE, AkuraWebConstant.EMPTY_STRING); } absentList.add(tempTAa); String startDate = teacherWisePresentAbsentTemplate.getDateFrom(); SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY); Date dateFrom = sdf.parse(teacherWisePresentAbsentTemplate.getDateFrom()); if (staff.getDateOfHire() != null) { setHireDate(teacherWisePresentAbsentTemplate, params, staff, dateFrom); } String endDate = teacherWisePresentAbsentTemplate.getDateTo(); Date startDateObj = DateUtil.getParseDate(teacherWisePresentAbsentTemplate.getDateFrom()); Date endDateObj = DateUtil.getParseDate(endDate); List<TeacherAttendance> attendanceList = attendanceReportingService .teacherWisePresentAndAbsentDays(teacherWisePresentAbsentTemplate); List<StaffLeave> staffLeaveList = staffService.getStaffLeaveListByDatePeriodAndStaffId(startDateObj, endDateObj, staffId); Calendar start = Calendar.getInstance(); start.setTime(startDateObj); Calendar end = Calendar.getInstance(); end.setTime(endDateObj); List<String> presentList = new ArrayList<String>(); List<Holiday> holidayList = getHolidayList(startDateObj, endDateObj); boolean flag = false; boolean isHoliday = false; boolean isReason = false; String temp = null; int count = 0; while (!start.after(end)) { for (TeacherAttendance ta : attendanceList) { if (DateUtil.getFormatDate(start.getTime()).equals(ta.getDate())) { temp = ta.getDate(); flag = true; break; } } isReason = false; isHoliday = isHoliday(holidayList, start.getTime(), start); if (flag) { presentList.add(temp); flag = false; temp = null; count++; } else { if (!isHoliday) { TeacherAttendance tempTA = new TeacherAttendance(); tempTA.setDate(DateUtil.getFormatDate(start.getTime()).toString()); for (StaffLeave staffLeave : staffLeaveList) { if (DateUtil.isDateBetween(staffLeave.getFromDate(), staffLeave.getToDate(), start.getTime())) { isReason = setReasonAndApprovalBy(tempTA, staffLeave); break; } } if (!isReason) { setReportParametersWhenNotReason(tempTA); } absentList.add(tempTA); count++; } } start.add(Calendar.DATE, 1); } JRBeanCollectionDataSource jrBeanDataSource = new JRBeanCollectionDataSource(absentList); setReportParameters(params, teacherRegNo, staff, absentList, startDate, presentList, count); ReportUtil.displayReportInPdfForm(response, jrBeanDataSource, params, JRXML_NAME); return null; }
From source file:org.apache.ws.security.handler.WSHandler.java
/** * Evaluate whether a timestamp is considered valid on the receivers' side. Hook to * allow subclasses to implement custom validation methods however they see fit. * // w w w . j a va 2 s. c o m * Policy used in this implementation: * * 1. The receiver can set its own time to live (besides from that set on * sender side) * * 2. If the message was created before (now-ttl) the message is rejected * * @param timestamp * the timestamp that is validated * @param timeToLive * the limit on the receivers' side, that the timestamp is validated against * @return true if the timestamp is before (now-timeToLive), false otherwise * @throws WSSecurityException */ protected boolean verifyTimestamp(Timestamp timestamp, int timeToLive) throws WSSecurityException { // Calculate the time that is allowed for the message to travel Calendar validCreation = Calendar.getInstance(); Calendar cre = timestamp.getCreated(); if (cre != null && cre.after(validCreation)) { if (doDebug) { log.debug("Validation of Timestamp: The message was created in the future!"); } return false; } long currentTime = validCreation.getTime().getTime(); currentTime -= timeToLive * 1000; validCreation.setTime(new Date(currentTime)); if (doDebug) { log.debug("Preparing to verify the timestamp"); DateFormat zulu = new XmlSchemaDateFormat(); log.debug("Validation of Timestamp: Current time is " + zulu.format(Calendar.getInstance().getTime())); log.debug("Validation of Timestamp: Valid creation is " + zulu.format(validCreation.getTime())); if (timestamp.getCreated() != null) { log.debug("Validation of Timestamp: Timestamp created is " + zulu.format(timestamp.getCreated().getTime())); } } // Validate the time it took the message to travel // if (timestamp.getCreated().before(validCreation) || // !timestamp.getCreated().equals(validCreation)) { if (cre != null && !cre.after(validCreation)) { if (doDebug) { log.debug("Validation of Timestamp: The message was created too long ago"); } return false; } if (doDebug) { log.debug("Validation of Timestamp: Everything is ok"); } return true; }
From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java
/** * List events./*from w w w .j av a2 s . c o m*/ * * @param thermostatId * the thermostat id * @param startTime * the start time * @return the list * @see com.ecofactor.qa.automation.algorithm.service.DataService#listEvents(java.lang.Integer, * java.util.Calendar) */ @Override public List<PartitionedThermostatEvent> listEvents(Integer thermostatId, Calendar startTime) { loadEvents(thermostatId); List<PartitionedThermostatEvent> events = new ArrayList<PartitionedThermostatEvent>(); Calendar startTimeUTC = DateUtil.copyToUTC(startTime); Set<Calendar> timeSet = timeEventMap.keySet(); for (Calendar time : timeSet) { if (time.after(startTimeUTC)) { events.add(timeEventMap.get(time)); } } return events; }
From source file:com.flyhz.avengers.framework.application.CrawlApplication.java
@SuppressWarnings("unchecked") private void initHbase() { LOG.info("init hbase"); HConnection hConnection = null;// w w w .j a v a 2 s. c om HBaseAdmin hbaseAdmin = null; HTable hDomain = null; try { hConnection = HConnectionManager.createConnection(hbaseConf); hbaseAdmin = new HBaseAdmin(hConnection); // av_fetch if (!hbaseAdmin.tableExists(AVTable.av_fetch.name())) { LOG.info("table[av_fetch] create it"); HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(AVTable.av_fetch.name())); HColumnDescriptor info = new HColumnDescriptor(AVTable.AVFamily.i.name()); tableDesc.addFamily(info); hbaseAdmin.createTable(tableDesc); } // av_page if (!hbaseAdmin.tableExists(AVTable.av_page.name())) { LOG.info("table[av_page] create it"); HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(AVTable.av_page.name())); HColumnDescriptor info = new HColumnDescriptor(AVTable.AVFamily.i.name()); tableDesc.addFamily(info); hbaseAdmin.createTable(tableDesc); } // av_crawl if (hbaseAdmin.tableExists(AVTable.av_crawl.name())) { LOG.info("table[av_crawl] exist drop it"); if (hbaseAdmin.isTableEnabled(AVTable.av_crawl.name())) { hbaseAdmin.disableTable(AVTable.av_crawl.name()); } hbaseAdmin.deleteTable(Bytes.toBytes(AVTable.av_crawl.name())); HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(AVTable.av_crawl.name())); HColumnDescriptor info = new HColumnDescriptor(AVTable.AVFamily.i.name()); tableDesc.addFamily(info); LOG.info("table[av_crawl] dropped then create it"); hbaseAdmin.createTable(tableDesc); } else { LOG.info("table[av_crawl] create it"); HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(AVTable.av_crawl.name())); HColumnDescriptor info = new HColumnDescriptor(AVTable.AVFamily.i.name()); tableDesc.addFamily(info); hbaseAdmin.createTable(tableDesc); } if (!hbaseAdmin.tableExists(AVTable.av_domain.name())) { HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(AVTable.av_domain.name())); HColumnDescriptor info = new HColumnDescriptor(AVTable.AVFamily.i.name()); tableDesc.addFamily(info); hbaseAdmin.createTable(tableDesc); } if (!hbaseAdmin.tableExists(AVTable.av_color.name())) { HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(AVTable.av_color.name())); HColumnDescriptor info = new HColumnDescriptor(AVTable.AVFamily.i.name()); tableDesc.addFamily(info); hbaseAdmin.createTable(tableDesc); } Configuration configuration = HBaseConfiguration.create(hbaseConf); configuration.setLong("hbase.rpc.timeout", 600000); // Scan configuration.setLong("hbase.client.scanner.caching", 1000); Map<String, Object> context = XConfiguration.getAvengersContext(); hDomain = new HTable(hbaseConf, AVTable.av_domain.name()); for (String root : (Set<String>) context.get(XConfiguration.ROOTS)) { Map<String, Object> domainMap = (Map<String, Object>) context.get(root); Get hDomainGet = new Get(Bytes.toBytes(root)); hDomainGet.addColumn(Bytes.toBytes(AVFamily.i.name()), Bytes.toBytes(AVColumn.bid.name())); Result result = hDomain.get(hDomainGet); LOG.info("root[{}] result.isEmpty -> {}", root, result == null ? null : result.isEmpty()); if (result != null && !result.isEmpty()) { Cell cell = result.rawCells()[0]; Calendar calendar = Calendar.getInstance(); LOG.info("root[{}] av_domain.batchId -> ", root, Bytes.toLong(cell.getValueArray())); calendar.setTime(new Date(Bytes.toLong(cell.getValueArray()))); // ? Integer period = (Integer) domainMap.get(XConfiguration.CRAWL_PERIOD); calendar.add(Calendar.HOUR_OF_DAY, period.intValue()); LOG.info("root[{}] calendar -> {},current.version -> {}", calendar.getTimeInMillis(), batchId); if (calendar.after(new Date(batchId))) { continue; } } domainRootForCrawlSet.add(root); } } catch (IOException e) { LOG.error("", e); } catch (Throwable e) { LOG.error("", e); } finally { if (hbaseAdmin != null) { try { hbaseAdmin.close(); } catch (IOException e) { LOG.error("", e); } } if (hConnection != null) { try { hConnection.close(); } catch (IOException e) { LOG.error("", e); } } } }