public void testIsMinute() throws Exception { assertTrue(TimeUtil.isMinute(0)); assertTrue(TimeUtil.isMinute(15)); assertTrue(TimeUtil.isMinute(59)); assertFalse(TimeUtil.isMinute(60)); assertFalse(TimeUtil.isMinute(-1)); }
public void testIsDayOfWeek() throws Exception { assertTrue(TimeUtil.isDayOfWeek(1)); assertTrue(TimeUtil.isDayOfWeek(3)); assertTrue(TimeUtil.isDayOfWeek(7)); assertFalse(TimeUtil.isDayOfWeek(0)); assertFalse(TimeUtil.isDayOfWeek(10)); }
public void testIsSecond() throws Exception { assertTrue(TimeUtil.isSecond(0)); assertTrue(TimeUtil.isSecond(15)); assertTrue(TimeUtil.isSecond(59)); assertFalse(TimeUtil.isSecond(60)); assertFalse(TimeUtil.isSecond(-1)); }
public void testIsWeekOfMonth() throws Exception { assertTrue(TimeUtil.isWeekOfMonth(1)); assertTrue(TimeUtil.isWeekOfMonth(3)); assertTrue(TimeUtil.isWeekOfMonth(4)); assertFalse(TimeUtil.isWeekOfMonth(0)); assertFalse(TimeUtil.isWeekOfMonth(8)); }
public void testIsMonthOfYear() throws Exception { assertTrue(TimeUtil.isMonthOfYear(1)); assertTrue(TimeUtil.isMonthOfYear(8)); assertTrue(TimeUtil.isMonthOfYear(12)); assertFalse(TimeUtil.isMonthOfYear(0)); assertFalse(TimeUtil.isMonthOfYear(100)); }
public void testIsHour() throws Exception { assertTrue(TimeUtil.isHour(0)); assertTrue(TimeUtil.isHour(15)); assertTrue(TimeUtil.isHour(23)); assertFalse(TimeUtil.isHour(24)); assertFalse(TimeUtil.isHour(-1)); }
public void testIsDayOfMonth() throws Exception { assertTrue(TimeUtil.isDayOfMonth(1)); assertTrue(TimeUtil.isDayOfMonth(15)); assertTrue(TimeUtil.isDayOfMonth(31)); assertFalse(TimeUtil.isDayOfMonth(0)); assertFalse(TimeUtil.isDayOfMonth(100)); }
public void testIsSecondsWholeMinute() throws Exception { assertTrue(TimeUtil.isSecondsWholeMinute(0)); assertTrue(TimeUtil.isSecondsWholeMinute(86400)); assertTrue(TimeUtil.isSecondsWholeMinute(432000)); assertFalse(TimeUtil.isSecondsWholeMinute(431999)); assertFalse(TimeUtil.isSecondsWholeMinute(432001)); }
/** Tests for approxTimeUntil. */ @Test public void testApproxTimeUntil() { Assert.assertEquals("less than a minute", TimeUtil.approxTimeUntil(5)); Assert.assertEquals("7 minutes", TimeUtil.approxTimeUntil(421)); Assert.assertEquals("23 hours", TimeUtil.approxTimeUntil(82789)); Assert.assertEquals("just over 11 weeks", TimeUtil.approxTimeUntil(6728282)); Assert.assertEquals("about 138 and a half weeks", TimeUtil.approxTimeUntil(83736372)); }
/** * Date In Period * * @param date date * @return true if in period */ public boolean isInPeriod(Timestamp date) { if (date == null) return false; Timestamp dateOnly = TimeUtil.getDay(date); Timestamp from = TimeUtil.getDay(getStartDate()); if (dateOnly.before(from)) return false; Timestamp to = TimeUtil.getDay(getEndDate()); if (dateOnly.after(to)) return false; return true; } // isInPeriod
/** tests for timeUtil() */ @Test public void testTimeUtil() { Assert.assertEquals("5 seconds", TimeUtil.timeUntil(5, true)); Assert.assertEquals("7 minutes, 1 seconds", TimeUtil.timeUntil(421, true)); Assert.assertEquals("22 hours, 59 minutes, 49 seconds", TimeUtil.timeUntil(82789, true)); Assert.assertEquals( "11 weeks, 20 hours, 58 minutes, 2 seconds", TimeUtil.timeUntil(6728282, true)); Assert.assertEquals( "138 weeks, 3 days, 4 hours, 6 minutes, 12 seconds", TimeUtil.timeUntil(83736372, true)); }
/** * @param columnIndex * @param bits * @param offset * @param length * @param targetCalendar * @param tz * @param rollForward * @param conn * @param rs * @return * @throws SQLException */ protected Time getNativeTime( int columnIndex, byte[] bits, int offset, int length, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { int hour = 0; int minute = 0; int seconds = 0; if (length != 0) { // bits[0] // skip tm->neg // binaryData.readLong(); // skip daysPart hour = bits[offset + 5]; minute = bits[offset + 6]; seconds = bits[offset + 7]; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimeCreate( hour, minute, seconds, targetCalendar, this.exceptionInterceptor); } Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew(); synchronized (sessionCalendar) { Time time = TimeUtil.fastTimeCreate( sessionCalendar, hour, minute, seconds, this.exceptionInterceptor); Time adjustedTime = TimeUtil.changeTimezone( conn, sessionCalendar, targetCalendar, time, conn.getServerTimezoneTZ(), tz, rollForward); return adjustedTime; } }
public static Map<String, Object> baseMsgToMapConvertor() { Map<String, Object> result = new HashMap<String, Object>(); result.put("sys_time", TimeUtil.getFormatString(new Date())); result.put("pic_server", Constant.PICTURE_SERVER); result.put("code", "200"); result.put("message", "server normal"); return result; }
@Override public void progressUpdated(Progress p) { if (p.getDone() >= fnMinWork && (p.getElapsed() - fnLastElapsed > fnFrequency || p.getStopped())) { double rr = getRecentRate(); if (p.getTarget() > 0.0) { fOut.print(p.getName() + " completed"); if (fbWholeNumbers) { fOut.print(String.format(" %d/%d", (int) p.getDone(), (int) p.getTarget())); } else { fOut.print(String.format(" %g/%g", p.getDone(), p.getTarget())); } fOut.print( String.format( " (%.2f %%) in %s - overall %.2f/s - EST %s", p.getPercentDone(), TimeUtil.getHMS(p.getElapsed()), p.getRate(), TimeUtil.getHMS(p.getEstimate()))); if (rr > 0) { fOut.print( String.format(" - recent %.2f/s - EST %s", rr, TimeUtil.getHMS(p.getEstimate(rr)))); } fOut.println(); } else { fOut.print(p.getName() + " completed"); if (fbWholeNumbers) { fOut.print(String.format(" %d", (int) p.getDone())); } else { fOut.print(String.format(" %g", p.getDone())); } fOut.print( String.format(" in %s - overall %.2f/s", TimeUtil.getHMS(p.getElapsed()), p.getRate())); if (rr > 0) { fOut.print(String.format(" - recent %.2f/s", rr)); } fOut.println(); } fOut.flush(); fnLastElapsed = p.getElapsed(); fSamples.add(new Sample(p.getDone())); } }
public static Map<String, Object> baseMsgToMapConvertor(String str, Object object) { Map<String, Object> result = new HashMap<String, Object>(); result.put("sys_time", TimeUtil.getFormatString(new Date())); result.put("pic_server", Constant.PICTURE_SERVER); result.put(str, object); // result.put("etag", SecurityUtil.getMD5(object)); result.put("code", 200); return result; }
public static Map<String, Object> baseMsgToMapConvertor(String message, int code) { Map<String, Object> result = new HashMap<String, Object>(); result.put("sys_time", TimeUtil.getFormatString(new Date())); result.put("pic_server", Constant.PICTURE_SERVER); result.put("code", code); result.put("message", message); if (code != 200) System.err.println("抛出自定义异常!!:\n\t" + code + "\n\t" + message); return result; }
public static void drag(Entity enemy, Vector2 target, float force, int duration) { EnemyMovement movement = EntityUtil.getComponent(enemy, EnemyMovement.class); if (movement != null) { movement.setDraggedTo(target); movement.setDragForce(force); movement.setDragDuration(duration); movement.setStartDrag(TimeUtil.getGameTime()); movement.setDraggedFrom(PhysicsUtil.getPosition(enemy)); } }
/** * ************************************************************************ Update/save Goals for * the same measure * * @param force force to update goal (default once per day) * @return true if updated */ public boolean updateGoal(boolean force) { log.config("Force=" + force); MMeasure measure = MMeasure.get(getCtx(), getPA_Measure_ID()); if (force || getDateLastRun() == null || !TimeUtil.isSameHour(getDateLastRun(), null)) { if (measure.updateGoals()) // saves { load(get_ID(), get_Trx()); return true; } } return false; } // updateGoal
public static boolean isAvailable(Entity entity, String name) { Ability abilityComponent = EntityUtil.getComponent(entity, Ability.class); if (abilityComponent == null) { return false; } AbilityInfo ability = abilityComponent.getAbility(name); if (ability == null) { return false; } long lastCast = ability.getLastCast(); return lastCast == -1 || (TimeUtil.getGameTime() - lastCast > ability.getCooldown()); }
public static void use(Entity entity, String name) { Ability abilityComponent = EntityUtil.getComponent(entity, Ability.class); if (abilityComponent == null) { return; } AbilityInfo ability = abilityComponent.getAbility(name); if (ability == null) { return; } ability.getAbility().cast(entity); ability.setLastCast(TimeUtil.getGameTime()); }
public static void main(String[] args) { String url = "http://baidu.com"; String KEY = "URIW853F"; System.out.println(KEY.length()); System.out.println("1:" + DesUtil.encrypt("12347", "hellohyy")); System.out.println( "1:" + DesUtil.decrypt(DesUtil.encrypt("http://baidu.com", "HelLOHyY"), "HelLOHyY")); TimeUtil time = TimeUtil.createAndPoint(); TimeUtil time2 = TimeUtil.createAndPoint(); // String k = "12345678"; // String content = // "fghjkzxcvbnm,2222222233333333888888fghjkzxcvbnm,222222223333333388888888999999991234"; // System.out.println(content.length()); // for (int i = 0; i < 1000000; i ++) { // if (i % 5000 == 0) { // time.printMs(""+i); // } // String encode = DesUtil.encrypt(content, k); // DesUtil.decrypt(encode, k); // } time.printMs("total"); time2.printMs("total"); // System.out.println("1:" + DesUtil.encrypt("http://baidu.com", "12345678")); // System.out.println("1:" + DesUtil.encrypt(DesUtil.encrypt("http://baidu.com", "12345678"), // "12345678")); // System.out.println("2:" + DesUtil.encrypt("http://www.baidu.com", "URIW853FACSDQWEZ")); // System.out.println("2:" + DesUtil.encrypt("http://www.baidu.com", "URIW853FACSDQWEZ")); // System.out.println(); // url = // DesUtil.decrypt("AC11168CCE5F7CDF1A26708E9B8B4399845EA9A37066A2604EF77570F171DEC1F7DEA244AE5A9F9279D6F0039CDAA372FEB959B7D4642FCB", "12345678"); // url = DesUtil.decrypt("49D7997FAA52E7F76BD7B9DFBEAD8203FEB959B7D4642FCB", "12345678"); System.out.println(url); }
@Override public View getView(int position, View convertView, ViewGroup parent) { // Log.d("FileBrowser", (convertView==null ? "convertView==null" : "convertView!=null")); File file = getItem(position); String title = file.getName(); if (convertView == null) { /* 使用自定义的list_items作为Layout */ convertView = mInflater.inflate(R.layout.file_list, null); /* 初始化holder的text与icon */ holder = new ViewHolder(); holder.f_title = (TextView) convertView.findViewById(R.id.f_title); holder.f_text = (TextView) convertView.findViewById(R.id.f_text); holder.f_icon = (ImageView) convertView.findViewById(R.id.f_icon); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } String f_type = getMimeType(file.getName()); holder.f_title.setText(title); if (file.isDirectory()) { holder.f_icon.setImageBitmap(mIcon_folder); } else { if ("image".equals(f_type)) { holder.f_icon.setImageBitmap(mIcon_image); } else if ("audio".equals(f_type)) { holder.f_icon.setImageBitmap(mIcon_audio); } else if ("video".equals(f_type)) { holder.f_icon.setImageBitmap(mIcon_video); } else if ("apk".equals(f_type)) { holder.f_icon.setImageBitmap(mIcon_apk); } else { holder.f_icon.setImageBitmap(mIcon_file); } } // 底部内容 最后修改时间及大小 StringBuilder textStringBuilder = new StringBuilder(); // textStringBuilder.append((new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(new // Date(file.lastModified()))) // .append(" "); if (!"..".equals(title)) textStringBuilder.append(TimeUtil.getDate(file.lastModified())).append(" "); // textStringBuilder.append(new Date(file.lastModified()).toLocaleString()).append(" "); if (file.length() > 0) textStringBuilder.append(FileUtil.byteCountToDisplaySize(file.length())); holder.f_text.setText(textStringBuilder.toString()); return convertView; }
/** * Find standard Period of DateAcct based on Client Calendar * * @param ctx context * @param C_Calendar_ID calendar * @param DateAcct date * @return active Period or null */ public static MPeriod getOfCalendar(Ctx ctx, int C_Calendar_ID, Timestamp DateAcct) { if (DateAcct == null) { s_log.warning("No DateAcct"); return null; } if (C_Calendar_ID == 0) { s_log.warning("No Calendar"); return null; } // Search in Cache first Iterator<MPeriod> it = s_cache.values().iterator(); while (it.hasNext()) { MPeriod period = it.next(); if (period.getC_Calendar_ID() == C_Calendar_ID && period.isStandardPeriod() && period.isInPeriod(DateAcct)) return period; } // Get it from DB MPeriod retValue = null; String sql = "SELECT * FROM C_Period " + "WHERE C_Year_ID IN " + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID=?)" + " AND ? BETWEEN TRUNC(StartDate,'DD') AND TRUNC(EndDate,'DD')" + " AND IsActive='Y' AND PeriodType='S'"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, (Trx) null); pstmt.setInt(1, C_Calendar_ID); pstmt.setTimestamp(2, TimeUtil.getDay(DateAcct)); rs = pstmt.executeQuery(); while (rs.next()) { MPeriod period = new MPeriod(ctx, rs, null); Integer key = Integer.valueOf(period.getC_Period_ID()); s_cache.put(key, period); if (period.isStandardPeriod()) retValue = period; } } catch (SQLException e) { s_log.log(Level.SEVERE, "DateAcct=" + DateAcct, e); } finally { DB.closeStatement(pstmt); DB.closeResultSet(rs); } if (retValue == null) s_log.warning( "No Standard Period for " + DateAcct + " (C_Calendar_ID=" + C_Calendar_ID + ")"); return retValue; } // get
/** * @param columnIndex * @param bits * @param offset * @param length * @param conn * @param rs * @param cal * @return * @throws SQLException */ protected java.sql.Date getNativeDate( int columnIndex, byte[] bits, int offset, int length, MySQLConnection conn, ResultSetImpl rs, Calendar cal) throws SQLException { int year = 0; int month = 0; int day = 0; if (length != 0) { year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8); month = bits[offset + 2]; day = bits[offset + 3]; } if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals( conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals( conn.getZeroDateTimeBehavior())) { throw SQLError.createSQLException( "Value '0000-00-00' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } year = 1; month = 1; day = 1; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastDateCreate(year, month, day, cal); } return rs.fastDateCreate( cal == null ? rs.getCalendarInstanceForSessionOrNew() : cal, year, month, day); }
public static void e(@SuppressWarnings("rawtypes") Class cls, String message) { if (message == null) { return; } Log.e(cls.getSimpleName(), message); if (debug) { try { bw.write(cls.getSimpleName() + " "); bw.write(TimeUtil.getCurrentTime() + " "); bw.write(message); bw.write("\n"); bw.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
/** * This will set default on the fields that are marked with a default and are null * * @param entity */ public static void setDefaultsOnFields(Object entity) { Objects.requireNonNull(entity, "Entity must not be NULL"); List<Field> fields = getAllFields(entity.getClass()); for (Field field : fields) { DefaultFieldValue defaultFieldValue = field.getAnnotation(DefaultFieldValue.class); if (defaultFieldValue != null) { field.setAccessible(true); try { if (field.get(entity) == null) { String value = defaultFieldValue.value(); Class fieldClass = field.getType(); if (fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())) { field.set(entity, value); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())) { field.set(entity, value); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())) { field.set(entity, Integer.parseInt(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())) { field.set(entity, Convert.toBoolean(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())) { field.set(entity, Double.parseDouble(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())) { field.set(entity, Float.parseFloat(value)); } else if (fieldClass .getSimpleName() .equalsIgnoreCase(BigDecimal.class.getSimpleName())) { field.set(entity, Convert.toBigDecimal(value)); } else if (fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())) { field.set(entity, TimeUtil.fromString(value)); } else if (fieldClass .getSimpleName() .equalsIgnoreCase(BigInteger.class.getSimpleName())) { field.set(entity, new BigInteger(value)); } } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new OpenStorefrontRuntimeException( "Unable to get value on " + entity.getClass().getName(), "Check entity passed in."); } } } }
public static MusicTrack createMusicTrack( AudioFileItem audioFileItem, String url, long nextId, long parentId) throws InvalidValueException { String creator = audioFileItem.getArtist(); Res res = new Res( new ProtocolInfo( "http-get:*:" + MIMETYPE_AUDIO_MPEG + ":" + DlnaUtil.DLNA_ORG_PN + ";" + DlnaUtil.DLNA_ORG_OP + ";" + DlnaUtil.DLNA_ORG_CI + ";" + DlnaUtil.DLNA_ORG_FLAGS), audioFileItem.getSize(), TimeUtil.convertMillis(audioFileItem.getLengthInMilliseconds()), audioFileItem.getBitrate(), url); MusicTrack result = new MusicTrack( "" + nextId, "" + parentId, audioFileItem.getTitle(), creator, audioFileItem.getAlbum(), creator, res); // Missing: // nrAudioChannels="2" // sampleFrequency="44100" // result.setDate("TODO"); // result.setDescription("TODO"); result.setOriginalTrackNumber(2); result.setGenres(new String[] {audioFileItem.getGenre()}); result.setRestricted(false); return result; }
private boolean updateSnapshot(Metadata metadata) throws MetadataException { final Versioning vs = metadata.getVersioning(); if (operand.getSnapshot() != null) { vs.setSnapshot(operand.getSnapshot()); } List<SnapshotVersion> extras = operand.getSnapshotVersions(); List<SnapshotVersion> currents = vs.getSnapshotVersions(); if (extras != null && extras.size() > 0) { // fix/upgrade the version ModelVersionUtility.setModelVersion(metadata, ModelVersionUtility.LATEST_MODEL_VERSION); for (SnapshotVersion extra : extras) { SnapshotVersion current = MetadataUtil.searchForEquivalent(extra, currents); if (current == null) { currents.add(extra); } else { try { if (TimeUtil.compare(current.getUpdated(), extra.getUpdated()) < 0) { currents.remove(current); currents.add(extra); } } catch (ParseException e) { throw new MetadataException( "Invalid timetamp: " + current.getUpdated() + "-" + extra.getUpdated(), e); } } } } else if (Version.V100 == operand.getOriginModelVersion()) { for (SnapshotVersion current : currents) { current.setUpdated(operand.getTimestamp()); } } vs.setLastUpdated(operand.getTimestamp()); return true; }
/** * Find Period of Date based on Client Calendar, it need not be a standard period (used in MRP) * * @param ctx context * @param C_Calendar_ID calendar * @param Date date * @param trx trx * @return active Period or null */ public static MPeriod getPeriod(Ctx ctx, int C_Calendar_ID, Timestamp Date, Trx trx) { if (Date == null) { s_log.warning("No Date"); return null; } if (C_Calendar_ID == 0) { s_log.warning("No Calendar"); return null; } // Get it from DB PreparedStatement pstmt = null; ResultSet rs = null; MPeriod retValue = null; String sql = "SELECT * FROM C_Period " + "WHERE C_Year_ID IN " + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID=?)" + " AND ? BETWEEN TRUNC(StartDate,'DD') AND TRUNC(EndDate,'DD')" + " AND IsActive='Y' "; try { pstmt = DB.prepareStatement(sql, trx); pstmt.setInt(1, C_Calendar_ID); pstmt.setTimestamp(2, TimeUtil.getDay(Date)); rs = pstmt.executeQuery(); if (rs.next()) { retValue = new MPeriod(ctx, rs, trx); } } catch (SQLException e) { s_log.log(Level.SEVERE, "DateAcct=" + Date, e); } finally { DB.closeResultSet(rs); DB.closeStatement(pstmt); } if (retValue == null) s_log.warning("No Period for " + Date + " (C_Calendar_ID=" + C_Calendar_ID + ")"); return retValue; } // getPeriod
public void testTo12HourClock() throws Exception { assertEquals(0, TimeUtil.to12HourClock(0)); assertEquals(8, TimeUtil.to12HourClock(8)); assertEquals(0, TimeUtil.to12HourClock(12)); assertEquals(8, TimeUtil.to12HourClock(20)); try { TimeUtil.to12HourClock(24); fail(); } catch (AssertionError e) { // ok } try { TimeUtil.to12HourClock(-1); fail(); } catch (AssertionError e) { // ok } }