@Test public void testReadBandRasterData() { Date startDate = Calendar.getInstance().getTime(); // Product product = new Product("name", "desc", 100, 200); File file = TestUtil.getTestFile( productsFolder + "SP04_HRI1_X__1O_20050605T090007_20050605T090016_DLR_70_PREU.BIL.ZIP"); // File rasterFile = TestUtil.getTestFile(productsFolder + "mediumImage.tif"); System.setProperty("snap.dataio.reader.tileWidth", "100"); System.setProperty("snap.dataio.reader.tileHeight", "200"); try { Product finalProduct = reader.readProductNodes(file, null); ProductData data = ProductData.createInstance(ProductData.TYPE_UINT16, 20000); data.setElemFloatAt(3, 5); reader.readBandRasterData( finalProduct.getBandAt(0), 2000, 2000, 100, 200, data, new NullProgressMonitor()); assertNotEquals(0, data.getElemFloatAt(0)); assertNotEquals(-1000, data.getElemFloatAt(0)); assertNotEquals(0, data.getElemFloatAt(1999)); assertNotEquals(-1000, data.getElemFloatAt(1999)); assertNotEquals(5, data.getElemFloatAt(3)); Date endDate = Calendar.getInstance().getTime(); assertTrue( "The load time for the product is too big!", (endDate.getTime() - startDate.getTime()) / (60 * 1000) < 30); } catch (IOException e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } }
/** * Returns all Weight Reading objects that fall within the time range specified (inclusive) * * @param leftBound The Date object specifying the earliest date boundary * @param rightBound The Date object specifying the latest date boundary * @param c The application context * @note Recreates only the new objects, since Identity Map is no longer applied: the reason for * this is because whenever data is fetched, we know its usage right away and will not need to * keep it in proximity for later usage, but rather direct usage * @return The ArrayList of all weighteReading in the database that fall within range * @throws MapperException Thrown when there is either a problem with mapping or if the * Persistence layer returns an error */ public static ArrayList<WeightReading> findAllWithinRangeInclusive( Date iLeftBound, Date iRightBound, Context iC) throws MapperException { try { ArrayList<ArrayList<String>> resultTable = WeightTDG.selectBetweenDatesInclusive( String.valueOf(iLeftBound.getTime()), String.valueOf(iRightBound.getTime()), iC); ArrayList<WeightReading> resultReadings = new ArrayList<WeightReading>(resultTable.size()); for (int i = 0; i < resultTable.size(); ++i) { ArrayList<String> values = resultTable.get(i); WeightReading r; Long id = Long.valueOf(values.get(0)); Date date = new Date(Long.valueOf(values.get(1))); /** Converts from Unix time to Java Date */ int sourceInt = Integer.valueOf(values.get(2)); ReadingSource source = sourceFromInt(sourceInt); float weight = Float.valueOf(values.get(3)); r = new WeightReading(id, date, source, weight); resultReadings.add(r); } return resultReadings; } catch (PersistenceException iE) { throw new MapperException( "The Mapper failed to obtain the Weight Readings from the persistence layer. The TDG returned the following error: " + iE.getMessage()); } catch (Exception iE) { throw new MapperException( "The mapper failed to complete an operation for the following unforeseen reason: " + iE.getMessage()); } }
/** * using the time from the adapter to reset the time list * * @param realDateTimes _more_ * @param times _more_ * @return _more_ */ private List resetTimesList(DateTime[] realDateTimes, List<DateTime> times) { List results = new ArrayList(); int len = realDateTimes.length; HashSet seenTimes = new HashSet(); try { for (DateTime dateTime : times) { Date dttm = ucar.visad.Util.makeDate(dateTime); long minTimeDiff = -1; Date minDate = null; for (int i = 0; i < len; i++) { Date sourceDate = ucar.visad.Util.makeDate(realDateTimes[i]); long timeDiff = Math.abs(sourceDate.getTime() - dttm.getTime()); if ((minTimeDiff < 0) || (timeDiff < minTimeDiff)) { minTimeDiff = timeDiff; minDate = sourceDate; } } if ((minDate != null) && !seenTimes.contains(minDate)) { results.add(new DateTime(minDate)); seenTimes.add(minDate); } } } catch (Exception e) { } return results; }
@Test public void testGetKBFoldersAndKBArticlesOrderedByDescendingModifiedDate() throws Exception { Date date = new Date(); KBArticle kbArticle1 = addKBArticle( KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, new Date(date.getTime() + Time.SECOND)); KBArticle kbArticle2 = addKBArticle( KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, new Date(date.getTime() + Time.SECOND * 3)); KBArticle kbArticle3 = addKBArticle( KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, new Date(date.getTime() + Time.SECOND * 2)); List<Object> kbFolderAndKBArticles = KBFolderLocalServiceUtil.getKBFoldersAndKBArticles( _group.getGroupId(), KBFolderConstants.DEFAULT_PARENT_FOLDER_ID, WorkflowConstants.STATUS_ANY, QueryUtil.ALL_POS, QueryUtil.ALL_POS, new KBObjectsModifiedDateComparator(false, true)); KBFolder currentKBFolder = (KBFolder) kbFolderAndKBArticles.get(0); KBArticle currentKBArticle1 = (KBArticle) kbFolderAndKBArticles.get(3); KBArticle currentKBArticle2 = (KBArticle) kbFolderAndKBArticles.get(1); KBArticle currentKBArticle3 = (KBArticle) kbFolderAndKBArticles.get(2); Assert.assertEquals(_kbFolder.getKbFolderId(), currentKBFolder.getKbFolderId()); Assert.assertEquals(kbArticle1.getKbArticleId(), currentKBArticle1.getKbArticleId()); Assert.assertEquals(kbArticle2.getKbArticleId(), currentKBArticle2.getKbArticleId()); Assert.assertEquals(kbArticle3.getKbArticleId(), currentKBArticle3.getKbArticleId()); }
@Test public void testReadProductNodes() { Date startDate = Calendar.getInstance().getTime(); Product product = new Product("name", "desc", 100, 100); File file = TestUtil.getTestFile( productsFolder + "SP04_HRI1_X__1O_20050605T090007_20050605T090016_DLR_70_PREU.BIL.ZIP"); System.setProperty("snap.dataio.reader.tileWidth", "100"); System.setProperty("snap.dataio.reader.tileHeight", "100"); try { Product finalProduct = reader.readProductNodes(file, null); assertEquals(4, finalProduct.getBands().length); assertEquals("WGS84(DD)", finalProduct.getSceneGeoCoding().getGeoCRS().getName().toString()); assertEquals("SPOTView", finalProduct.getProductType()); assertEquals(0, finalProduct.getMaskGroup().getNodeCount()); assertEquals(2713, finalProduct.getSceneRasterWidth()); assertEquals(2568, finalProduct.getSceneRasterHeight()); Date endDate = Calendar.getInstance().getTime(); assertTrue( "The load time for the product is too big!", (endDate.getTime() - startDate.getTime()) / (60 * 1000) < 30); } catch (IOException e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } }
public void messageReceived(int to, Message message) { Date date = Calendar.getInstance().getTime(); if (message instanceof RadioSignalResultsMsg) { RadioSignalResultsMsg resultMsg = (RadioSignalResultsMsg) message; log( date + "\t" + date.getTime() + "\t" + "RADIO15.4_RESULT_MSG" + "\t" + resultMsg.get_idReceiver() + "\t" + resultMsg.get_idSender() + "\t" + resultMsg.get_seqno() + "\t" + resultMsg.get_rssi() + "\t" + resultMsg.get_lqi() + "\t" + resultMsg.get_timestamp()); } else { log(date + "\t" + date.getTime() + "\t UNKNOWN_MSG" + "\t" + message.toString()); } }
public static int driver( String inputMaf, String outputMaf, boolean useCache, boolean sort, boolean addMissing) { Date start = new Date(); int oncoResult = 0; Oncotator tool = new Oncotator(useCache); tool.setSortColumns(sort); tool.setAddMissingCols(addMissing); try { oncoResult = tool.oncotateMaf(new File(inputMaf), new File(outputMaf)); } catch (IOException e) { System.out.println("IO error occurred: " + e.getMessage()); e.printStackTrace(); } catch (OncotatorServiceException e) { System.out.println("Service error occurred: " + e.getMessage()); e.printStackTrace(); } finally { Date end = new Date(); double timeElapsed = (end.getTime() - start.getTime()) / 1000.0; System.out.println("Total number of records processed: " + tool.getNumRecordsProcessed()); if (tool.getBuildNumErrors() > 0) { System.out.println( "Number of records skipped due to incompatible build no: " + tool.getBuildNumErrors()); } System.out.println("Total time: " + timeElapsed + " seconds."); } return oncoResult; }
public static boolean isSpam(User poster, String body, String ip) { Date lastPost = poster.getLastPost(); Date curTime = new Date(); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US); Date joinDate; if (poster.getIsMod()) return false; try { joinDate = formatter.parse(poster.getJoinDate()); } catch (Exception e) { joinDate = new Date(); } if (lastPost != null) { long diff = curTime.getTime() - lastPost.getTime(); long userLen = curTime.getTime() - joinDate.getTime(); long minInterval = (userLen < (Config.spamProbationPeriodDays * 1000 * 60 * 60 * 24)) ? Config.spamPostIntervalMinsProbation : Config.spamPostIntervalMinsStandard; minInterval *= 1000 * 60; if (diff < minInterval) { Log.log("Filtered post from " + poster.getUsername(), Log.DEBUG); return true; } } poster.setLastPost(curTime); return false; }
@Test public void testCronTriggerJob() throws Exception { SessionConfiguration config = new SessionConfiguration(); config.setClockType(ClockType.PSEUDO_CLOCK); PseudoClockScheduler timeService = (PseudoClockScheduler) TimerServiceFactory.getTimerService(config); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Date date = df.parse("2009-01-01T00:00:00.000-0000"); timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS); CronTrigger trigger = new CronTrigger(date.getTime(), null, null, -1, "15 * * * * ?", null, null); HelloWorldJobContext ctx = new HelloWorldJobContext("hello world", timeService); timeService.scheduleJob(new HelloWorldJob(), ctx, trigger); assertEquals(0, ctx.getList().size()); timeService.advanceTime(10, TimeUnit.SECONDS); assertEquals(0, ctx.getList().size()); timeService.advanceTime(10, TimeUnit.SECONDS); assertEquals(1, ctx.getList().size()); timeService.advanceTime(30, TimeUnit.SECONDS); assertEquals(1, ctx.getList().size()); timeService.advanceTime(30, TimeUnit.SECONDS); assertEquals(2, ctx.getList().size()); }
@Test public void do_not_update_already_removed_rules() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().selectAll(dbTester.getSession())).hasSize(2); RuleDto rule2 = dbClient.ruleDao().getByKey(dbTester.getSession(), RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.READY); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV2()); // On MySQL, need to update a rule otherwise rule2 will be seen as READY, but why ??? dbClient .ruleDao() .update( dbTester.getSession(), dbClient.ruleDao().getByKey(dbTester.getSession(), RuleKey.of("fake", "rule1"))); dbTester.getSession().commit(); // rule2 is removed rule2 = dbClient.ruleDao().getNullableByKey(dbTester.getSession(), RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); when(system.now()).thenReturn(DATE3.getTime()); execute(new FakeRepositoryV2()); dbTester.getSession().commit(); // -> rule2 is still removed, but not update at DATE3 rule2 = dbClient.ruleDao().getNullableByKey(dbTester.getSession(), RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2); }
/** * Retorna la diferencia en minutos entre dos horas * * @param fechaInicio * @param fechaFin * @return */ public double getDiferenciaMinutos(Date fechaInicio, Date fechaFin) { double tiempoInicial = fechaInicio.getTime(); double tiempoFinal = fechaFin.getTime(); double dou_resta = tiempoFinal - tiempoInicial; dou_resta = dou_resta / (1000 * 60); return dou_resta; }
/** * @param date * @param vipType 黄钻为0,红钻为1 * @param type 活跃用户为0,新增用户为1 * @param list * @throws SQLException */ private void saveRecord(Date date, int vipType, int type, int[][] list) throws SQLException { PreparedStatement pstmt; for (int isYearVip = 0; isYearVip < 2; isYearVip++) { for (int vipLevel = 0; vipLevel < 8; vipLevel++) { pstmt = con.prepareStatement( "delete from vip_level where date=? and type=? and is_year_vip=? and vip_level=? and vip_type=?"); pstmt.setDate(1, new java.sql.Date(date.getTime())); pstmt.setInt(2, type); pstmt.setInt(3, isYearVip); pstmt.setInt(4, vipLevel); pstmt.setInt(5, vipType); pstmt.execute(); pstmt.close(); pstmt = con.prepareStatement( "insert into vip_level(date,type,is_year_vip,vip_level,vip_type,count) values(?,?,?,?,?,?)"); pstmt.setDate(1, new java.sql.Date(date.getTime())); pstmt.setInt(2, type); pstmt.setInt(3, isYearVip); pstmt.setInt(4, vipLevel); pstmt.setInt(5, vipType); pstmt.setInt(6, list[isYearVip][vipLevel]); pstmt.execute(); pstmt.close(); } } }
/** REST API call to sentiment 140 */ @Override public void execute(Tuple tuple, BasicOutputCollector collector) { startTime = System.currentTimeMillis(); List<Object> otherFields = Lists.newArrayList(tuple.getValues()); int currentCounter = (Integer) otherFields.get(0); int currentSentiment = (Integer) otherFields.get(1); Date tempDate = (Date) otherFields.get(2); // 0: counter, 1: // // sentement_Id, // // 2:Date_object Integer isAnomalous = (Integer) otherFields.get(3); List<TweetTransferEntity> tweetList = (List<TweetTransferEntity>) otherFields.get(4); int aggregation_factor = 123; TweetJDBCTemplate tweetJdbcTemplate = TweetJDBCTemplateConnectionPool.getTweetJDBCTemplate("test", configFile); List<AnomalyTableObject> anomalies = new ArrayList<AnomalyTableObject>(0); if (isAnomalous == 1 || isAnomalous == 2) { // for (TweetTransferEntity tweetTransferEntity : tweetList) { // AnomalyTableObject anomaly = new AnomalyTableObject(); // anomaly.setQuery_id(2); // anomaly.setSentiment(currentSentiment); // anomaly.setTimestamp(tweetTransferEntity.getTimestamp() ); // // anomaly.setTweet_id(tweetTransferEntity.getTimestamp()); // anomaly.setValue(currentCounter); // anomaly.setWindow_length(0); // anomaly.setAggregation(aggregation_factor); // anomaly.setNote(tempDate.toString()); // // anomalies.add(anomaly); // } // tweetJdbcTemplate.insertAnomalies(anomalies); long current_timestamp = tempDate.getTime() / 1000; long previousAggregated_timestamp = AggregateUtilityFunctions.minusMinutesToDate(15, tempDate).getTime() / 1000; AnomalyTableObject anomaly = new AnomalyTableObject(); anomaly.setQuery_id(2); anomaly.setSentiment(currentSentiment); anomaly.setTimestamp(tempDate.getTime() / 1000); anomaly.setTweet_id(current_timestamp); anomaly.setValue(currentCounter); anomaly.setWindow_length(0); anomaly.setAggregation(aggregation_factor); anomaly.setNote(tempDate.toString()); tweetJdbcTemplate.insertAnomaly_test( anomaly, previousAggregated_timestamp, current_timestamp); } long elapsedTime = System.currentTimeMillis() - startTime; LOG.info("Time to process is::" + elapsedTime / 1000 + " for size:: " + tweetList.size()); }
/** ************ Helper stuff ***************** */ private void createAndFillUserTable() { int rowCount = 10000; sql2o .createQuery( "create table User(\n" + "id int identity primary key,\n" + "name varchar(20),\n" + "email varchar(255),\n" + "text varchar(100))") .executeUpdate(); Query insQuery = sql2o.createQuery("insert into User(name, email, text) values (:name, :email, :text)"); Date before = new Date(); for (int idx = 0; idx < rowCount; idx++) { insQuery .addParameter("name", "a name " + idx) .addParameter("email", String.format("*****@*****.**", idx)) .addParameter("text", "some text") .addToBatch(); } insQuery.executeBatch(); Date after = new Date(); Long span = after.getTime() - before.getTime(); System.out.println( String.format("inserted %d rows into User table. Time used: %s ms", rowCount, span)); insertIntoUsers += rowCount; }
public static String dscr(Date date1, Date date2) { SimpleDateFormat fmt1 = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy"); StringBuilder description = new StringBuilder(); if (fmt1.format(date1).equals(fmt1.format(date2))) { long difference = date2.getTime() - date1.getTime(); if (difference >= 2 * ahour) { description.append(difference / ahour).append(" hours ago"); } else if (difference >= ahour) { description.append("1 hour ago"); } else if (difference >= 2 * amin) { description.append(difference / amin).append(" mins ago"); } else if (difference >= amin) { description.append("1 min ago"); } else if (difference >= 2 * asec) { description.append(difference / asec).append(" secs ago"); } else { description.append(" just now"); } } else if (fmt2.format(date1).equals(fmt2.format(date2))) { SimpleDateFormat fmt3 = new SimpleDateFormat("MMM dd 'at' hh:mm"); description.append(fmt3.format(date1)); } else { SimpleDateFormat fmt4 = new SimpleDateFormat("yyyy-MM-dd"); description.append(fmt4.format(date1)); } return description.toString(); }
public String dateDifference(Date d1, Date d2) { // in milliseconds long diff = d2.getTime() - d1.getTime(); return dateDifToString(diff); }
public void retrieve10MaxTradesStockList( ErrorObject error, DatabaseClass db, Date start, Date end) { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; String sql = "select ticker, name, isin, currency, " + "marketplace, listname, sum(trades) as tradeSum " + "from stock_information " + "where information_date <= ? and information_date >= ? " + "group by ticker, name, isin, currency, marketplace, listname " + "order by tradeSum desc "; this.clear(); try { conn = DriverManager.getConnection(db.getUrl(), db.getUsr(), db.getPwd()); conn.setAutoCommit(false); pst = conn.prepareStatement(sql); long date1 = end.getTime(); java.sql.Date sqlDate1 = new java.sql.Date(date1); pst.setDate(1, sqlDate1); long date2 = start.getTime(); java.sql.Date sqlDate2 = new java.sql.Date(date2); pst.setDate(2, sqlDate2); rs = pst.executeQuery(); int i = 0; while (rs.next()) { if (i < 10) { StockInformation si = new StockInformation(); si.setTicker(rs.getString(1)); si.setName(rs.getString(2)); si.setIsin(rs.getString(3)); si.setCurrency(rs.getString(4)); si.setMarketplace(rs.getString(5)); si.setListname(rs.getString(6)); si.setPeriodSumTrades(new Integer(rs.getInt(7))); this.add(si); i++; } } rs.close(); conn.commit(); pst.close(); conn.close(); } catch (SQLException e) { System.out.println("DB Error: " + e.getMessage()); error.setError(true); error.setMessage(e.getMessage()); if (conn != null) { try { conn.close(); } catch (SQLException e2) { } } } }
private static void collectAccountTransactions( Client client, Date start, Date end, List<Transaction> transactions) { for (Account account : client.getAccounts()) { for (AccountTransaction t : account.getTransactions()) { if (t.getDate().getTime() > start.getTime() && t.getDate().getTime() <= end.getTime()) { switch (t.getType()) { case DEPOSIT: case REMOVAL: case TRANSFER_IN: case TRANSFER_OUT: transactions.add(t); break; case BUY: case SELL: case FEES: case TAXES: case DIVIDENDS: case INTEREST: case TAX_REFUND: break; default: throw new UnsupportedOperationException(); } } } } }
public String lastEvent() { if (revoked != null) { return lastRevoked; } if (getState().startsWith("finished")) { return lastVotingEnded; } if (issue_closed != null) { return lastClosed; } if (issue_fully_frozen != null) { return lastVotingStarted; } if (issue_half_frozen != null) { return lastFrozen; } try { if ((Math.abs((created.getTime() - current_draft_created.getTime())) < 2000)) { return lastErzeugt; } else { return lastNeuerEntwurf; } } catch (NullPointerException e) { return lastNeuerEntwurf; } }
@Override public void removeValuesUnusedLongerThan(long minimumAge, TimeUnit unit) throws BinaryStoreException { try { Date deadline = new Date(new Date().getTime() - unit.toMillis(minimumAge)); // When querying using 2nd indexes, Cassandra // (it's not CQL specific) requires that you use an '=' for at least one of // the indexed column in the where clause. This is a limitation of Cassandra. // So we have to do some tricks here ResultSet rs = session.execute( "SELECT cid from modeshape.binary where usage=0 and usage_time < " + deadline.getTime() + " allow filtering;"); Iterator<Row> rows = rs.iterator(); while (rows.hasNext()) { session.execute( "DELETE from modeshape.binary where cid = '" + rows.next().getString("cid") + "';"); } rs = session.execute( "SELECT cid from modeshape.binary where usage=1 and usage_time < " + deadline.getTime() + " allow filtering;"); rows = rs.iterator(); while (rows.hasNext()) { session.execute( "DELETE from modeshape.binary where cid = '" + rows.next().getString("cid") + "';"); } } catch (RuntimeException e) { throw new BinaryStoreException(e); } }
/** * Issue SAML 2 token with a near future Created Lifetime. This should pass as we allow a future * dated Lifetime up to 60 seconds to avoid clock skew problems. */ @org.junit.Test public void testSaml2NearFutureCreatedLifetime() throws Exception { int requestedLifetime = 60; SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider(); DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider(); conditionsProvider.setAcceptClientLifetime(true); samlTokenProvider.setConditionsProvider(conditionsProvider); TokenProviderParameters providerParameters = createProviderParameters(WSConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE); // Set expected lifetime to 1 minute Date creationTime = new Date(); Date expirationTime = new Date(); expirationTime.setTime(creationTime.getTime() + (requestedLifetime * 1000L)); creationTime.setTime(creationTime.getTime() + (10 * 1000L)); Lifetime lifetime = new Lifetime(); XmlSchemaDateFormat fmt = new XmlSchemaDateFormat(); lifetime.setCreated(fmt.format(creationTime)); lifetime.setExpires(fmt.format(expirationTime)); providerParameters.getTokenRequirements().setLifetime(lifetime); assertTrue(samlTokenProvider.canHandleToken(WSConstants.WSS_SAML2_TOKEN_TYPE)); TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters); assertTrue(providerResponse != null); assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null); assertEquals( 50L * 1000L, providerResponse.getExpires().getTime() - providerResponse.getCreated().getTime()); Element token = (Element) providerResponse.getToken(); String tokenString = DOM2Writer.nodeToString(token); assertTrue(tokenString.contains(providerResponse.getTokenId())); }
public Long durationLeft() { Date timeNow = new Date(); Long min_left = ((start_time.getTime() + duration * 60000) - timeNow.getTime()) / 60000; // Time left to run in Mins return min_left; }
/** * 根据微吼url创建直播信息 * * @param url * @param groupList * @return * @throws Exception */ private Live createVhLive(String url, List<JSONObject> groupList, User user) throws Exception { int i = url.lastIndexOf("/"); String num = url.substring(i + 1); if (!StringUtil.isBlank(num)) { Pattern p = Pattern.compile("^\\d{9}$"); if (p.matcher(num).matches()) { VhallWebinar vh = vhallWebinarService.getVhLiveInfo(num); if (vh != null) { // 2015-07-11 13:30:00 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start = sdf.parse(vh.getT_start()); Date end = sdf.parse(vh.getT_end()); String image = getVhPicUrl(url); List<Images> images = this.changePicUrlToImage(image); return liveRepo.save( new Live( vh.getSubject(), start.getTime(), end.getTime(), Config.LIVE_TYPE_VH, vh.getWebinar_desc(), images, groupList, num, url, user.getId(), user.getNickName(), user.getLogoURL())); } } } throw new Exception("创建直播失败"); }
/** 实现歌词的滚动显示 */ public void scroll() { Date startTime = new Date(); for (int i = 0; i < lrcAnalyst.getLrcTimeValAndIndex().size(); i++) { while (true) { try { Thread.currentThread().sleep(50); Date currentTime = new Date(); LrcTimeAndIndexNum fl = (LrcTimeAndIndexNum) (lrcAnalyst.getLrcTimeValAndIndex().get(i)); float diffTime = currentTime.getTime() - startTime.getTime(); lrcIndex = fl.getLrcIndex() - lrcAnalyst.getRealLrcStartOffset(); if (fl.getLrcTime() - (float) diffTime / 1000 < 0.0) { scrollPoint.y--; // System.out.println((String) lrcAnalyst.getLrcContent().get( // fl.getLrcIndex()- lrcAnalyst.getRealLrcStartOffset())); repaint(); break; } } catch (Exception e) { e.printStackTrace(); } } } }
@Test public void testCompareToDate() throws Exception { Date date = new Date(); Date before = new Date(date.getTime() - 20); Date after = new Date(date.getTime() + 20); ParseObject object = new ParseObject("TestObject"); object.put("date", date); ParseQuery.State<ParseObject> query; OfflineQueryLogic logic = new OfflineQueryLogic(null); query = new ParseQuery.State.Builder<>("TestObject").whereEqualTo("date", date).build(); assertTrue(matches(logic, query, object)); object.put("date", after); assertFalse(matches(logic, query, object)); object.put("date", date); query = new ParseQuery.State.Builder<>("TestObject").addCondition("date", "$lt", after).build(); assertTrue(matches(logic, query, object)); object.put("date", after); assertFalse(matches(logic, query, object)); object.put("date", date); query = new ParseQuery.State.Builder<>("TestObject").addCondition("date", "$gt", before).build(); assertTrue(matches(logic, query, object)); object.put("date", before); assertFalse(matches(logic, query, object)); object.put("date", after); }
protected long getTimestamp(Element packet) { long now = System.currentTimeMillis(); ArrayList<String> stamps = new ArrayList<>(); for (Element child : packet.getChildren()) { if (child.getName().equals("delay")) { stamps.add(child.getAttribute("stamp").replace("Z", "+0000")); } } Collections.sort(stamps); if (stamps.size() >= 1) { try { String stamp = stamps.get(stamps.size() - 1); if (stamp.contains(".")) { Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US).parse(stamp); if (now < date.getTime()) { return now; } else { return date.getTime(); } } else { Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US).parse(stamp); if (now < date.getTime()) { return now; } else { return date.getTime(); } } } catch (ParseException e) { return now; } } else { return now; } }
@Test public void testAddAndGetApproval() { String userName = "******"; String clientId = "client"; String scope = "uaa.user"; long expiresIn = 1000l; Date lastUpdatedAt = new Date(); ApprovalStatus status = APPROVED; Date expiresAt = new Timestamp(new Date().getTime() + expiresIn); Approval newApproval = new Approval() .setUserId(userName) .setClientId(clientId) .setScope(scope) .setExpiresAt(expiresAt) .setStatus(status) .setLastUpdatedAt(lastUpdatedAt); dao.addApproval(newApproval); List<Approval> approvals = dao.getApprovals(userName, clientId); assertEquals(clientId, approvals.get(0).getClientId()); assertEquals(userName, approvals.get(0).getUserId()); assertEquals( Math.round(expiresAt.getTime() / 1000), Math.round(approvals.get(0).getExpiresAt().getTime() / 1000)); assertEquals( Math.round(lastUpdatedAt.getTime() / 1000), Math.round(approvals.get(0).getLastUpdatedAt().getTime() / 1000)); assertEquals(scope, approvals.get(0).getScope()); assertEquals(status, approvals.get(0).getStatus()); }
@Override public CacheModel<TransitionHistory> toCacheModel() { TransitionHistoryCacheModel transitionHistoryCacheModel = new TransitionHistoryCacheModel(); transitionHistoryCacheModel.transitionHistoryId = getTransitionHistoryId(); transitionHistoryCacheModel.userId = getUserId(); transitionHistoryCacheModel.groupId = getGroupId(); transitionHistoryCacheModel.companyId = getCompanyId(); Date createDate = getCreateDate(); if (createDate != null) { transitionHistoryCacheModel.createDate = createDate.getTime(); } else { transitionHistoryCacheModel.createDate = Long.MIN_VALUE; } transitionHistoryCacheModel.dossierId = getDossierId(); transitionHistoryCacheModel.processOrderId = getProcessOrderId(); transitionHistoryCacheModel.daysDoing = getDaysDoing(); transitionHistoryCacheModel.daysDelay = getDaysDelay(); Date startDate = getStartDate(); if (startDate != null) { transitionHistoryCacheModel.startDate = startDate.getTime(); } else { transitionHistoryCacheModel.startDate = Long.MIN_VALUE; } transitionHistoryCacheModel.stepTransitionId = getStepTransitionId(); transitionHistoryCacheModel.preDossierStepId = getPreDossierStepId(); transitionHistoryCacheModel.postDossierStepId = getPostDossierStepId(); transitionHistoryCacheModel.transitionName = getTransitionName(); String transitionName = transitionHistoryCacheModel.transitionName; if ((transitionName != null) && (transitionName.length() == 0)) { transitionHistoryCacheModel.transitionName = null; } transitionHistoryCacheModel.note = getNote(); String note = transitionHistoryCacheModel.note; if ((note != null) && (note.length() == 0)) { transitionHistoryCacheModel.note = null; } return transitionHistoryCacheModel; }
/** @tests java.util.Date#getTime() */ public void test_getTime() { // Test for method long java.util.Date.getTime() Date d1 = new Date(0); Date d2 = new Date(1900000); assertEquals("Returned incorrect time", 1900000, d2.getTime()); assertEquals("Returned incorrect time", 0, d1.getTime()); }
public static List<CalendarBooking> getCalendarBookings( PermissionChecker permissionChecker, Calendar calendar, Date startDate, Date endDate) throws PortalException, SystemException { ClassLoader classLoader = ClassLoaderPool.getClassLoader("calendar-portlet"); DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(CalendarBooking.class, classLoader); dynamicQuery.add(RestrictionsFactoryUtil.eq("calendarId", calendar.getCalendarId())); List<Integer> calendarStatus = new ArrayList<Integer>(); calendarStatus.add(WorkflowConstants.STATUS_APPROVED); calendarStatus.add(WorkflowConstants.STATUS_PENDING); calendarStatus.add(WorkflowConstants.STATUS_DRAFT_FROM_APPROVED); dynamicQuery.add(RestrictionsFactoryUtil.in("status", calendarStatus)); if (startDate != null) { dynamicQuery.add(RestrictionsFactoryUtil.ge("startTime", new Long(startDate.getTime()))); } if (endDate != null) { dynamicQuery.add(RestrictionsFactoryUtil.le("endTime", new Long(endDate.getTime()))); } List<CalendarBooking> allCalendarBookings = CalendarBookingLocalServiceUtil.dynamicQuery(dynamicQuery); return filterCalendarBookings(allCalendarBookings, permissionChecker, ActionKeys.VIEW); }