List of usage examples for java.sql Timestamp getTime
public long getTime()
From source file:uk.org.funcube.fcdw.server.extract.csv.HighResCsvExtractor.java
@Transactional(readOnly = true, propagation = Propagation.REQUIRED) public void extract(long satelliteId) { Timestamp latestSatelliteTime = highResolutionDao.getLatestSatelliteTime(satelliteId); Timestamp since = new Timestamp(latestSatelliteTime.getTime() - (60 * 60 * 1000)); List<HighResolutionEntity> highResOneHour = highResolutionDao.getSinceSatelliteTime(satelliteId, since); if (highResOneHour.size() == 0) { return;//from ww w. ja v a 2s .c o m } File fileLocation = new File(System.getProperty("csv.hires")); if (fileLocation.exists()) { fileLocation.delete(); } try { // use FileWriter constructor that specifies open for appending CsvWriter csvOutput = new CsvWriter(new FileWriter(fileLocation, true), ','); // write out the headers csvOutput.write("Satellite Date/Time UTC"); csvOutput.write("Sun Sensor +X log Lux"); csvOutput.write("Sun Sensor +Y log Lux"); csvOutput.write("Sun Sensor -Y log Lux"); csvOutput.write("Sun Sensor +Z log Lux"); csvOutput.write("Sun Sensor -Z log Lux"); csvOutput.write("Tot. Photo Curr. mA"); csvOutput.write("Battery mV"); csvOutput.endRecord(); long tsLong = 0; String c1 = ""; String c2 = ""; String c3 = ""; String c4 = ""; String c5 = ""; String c6 = ""; String c7 = ""; for (HighResolutionEntity entity : highResOneHour) { Timestamp satelliteTime = entity.getSatelliteTime(); if (tsLong == 0) { tsLong = satelliteTime.getTime(); c1 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC1().intValue()])); c2 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC2().intValue()])); c3 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC3().intValue()])); c4 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC4().intValue()])); c5 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC5().intValue()])); c6 = String.format("%4.0f", new Double(entity.getC6() * 2.0)); c7 = String.format("%3.0f", new Double(entity.getC7() * 2.0)); writeRecord(csvOutput, satelliteTime, c1, c2, c3, c4, c5, c6, c7); } else { final long timeDiff = satelliteTime.getTime() - tsLong; if (timeDiff > 1000) { // fill in the gaps long gaps = (timeDiff / 1000); for (long i = 1; i < gaps; i++) { Timestamp intervalTime = new Timestamp(tsLong + (1000 * i)); writeRecord(csvOutput, intervalTime, c1, c2, c3, c4, c5, c6, c7); } } c1 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC1().intValue()])); c2 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC2().intValue()])); c3 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC3().intValue()])); c4 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC4().intValue()])); c5 = String.format("%5.3f", new Double(SOL_ILLUMINATION[entity.getC5().intValue()])); c6 = String.format("%4.0f", new Double(entity.getC6() * 2.0)); c7 = String.format("%3.0f", new Double(entity.getC7() * 2.0)); writeRecord(csvOutput, satelliteTime, c1, c2, c3, c4, c5, c6, c7); tsLong = satelliteTime.getTime(); } } csvOutput.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:gov.nih.nci.cadsrapi.dao.orm.CleanerDAO.java
public void clean() { if (sessionFactory == null) { setFactory();//w w w .jav a2s. co m this.setSessionFactory(sessionFactory); } Session session = getSession(); Transaction tx = session.beginTransaction(); //Check for unexpired carts that have been active within the expiration interval and reset expiration time. int expirationInterval = 4 * 24 * 60; //Four days, in minutes int sleepTime = 60; //One hour, in minutes //Defaults int publicEmptyExpirationDays = 4 * 24 * 60; String emptyExpirationSQL = " (SYSDATE + INTERVAL '" + publicEmptyExpirationDays + "' MINUTE)"; int publicFullExpirationDays = 30 * 24 * 60; //30 days, in minutes String fullExpirationSQL = " (SYSDATE + INTERVAL '" + publicFullExpirationDays + "' MINUTE)"; try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.time.expiration.minutes")); expirationInterval = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.cleaner.sleep.minutes")); sleepTime = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.public.empty.expiration.minutes")); publicEmptyExpirationDays = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.public.full.expiration.minutes")); publicFullExpirationDays = temp; } catch (Exception e) { log.error(e); } //Timestamps are in milliseconds Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp nowMinusTwiceSleep = new Timestamp(now.getTime() - sleepTime * 60 * 1000 * 2); //Converting minutes to milliseconds Timestamp nowPlusExpirationInterval = new Timestamp(now.getTime() + expirationInterval * 60 * 1000); //Converting minutes to milliseconds Query updateActiveCarts = session.createQuery( "update gov.nih.nci.cadsr.objectcart.domain.Cart set expirationDate = :nowPlusExpirationInterval" + " where (lastWriteDate > :nowMinusTwiceSleep or lastReadDate > :nowMinusTwiceSleep) and expirationDate > :now and expirationDate < :nowPlusExpirationInterval"); updateActiveCarts.setTimestamp("nowPlusExpirationInterval", nowPlusExpirationInterval); updateActiveCarts.setTimestamp("nowMinusTwiceSleep", nowMinusTwiceSleep); updateActiveCarts.setTimestamp("now", now); if (publicEmptyExpirationDays > 0 && publicEmptyExpirationDays < 365 * 24 * 60) //Check expiration is within a year emptyExpirationSQL = " (SYSDATE + INTERVAL '" + publicEmptyExpirationDays + "' MINUTE)"; else if (publicEmptyExpirationDays == 0) emptyExpirationSQL = "SYSDATE"; if (publicFullExpirationDays > 0 && publicFullExpirationDays < 365) //Check expiration is within a year fullExpirationSQL = " (SYSDATE + INTERVAL '" + publicFullExpirationDays + "' MINUTE)"; else if (publicFullExpirationDays == 0) fullExpirationSQL = "SYSDATE"; //Set expiration date to emptyExpirationSQL if the user starts with 'PublicUser' and the current expiration date is null String initializeSessionCartSql = "UPDATE cart c" + " set expiration_Date = " + emptyExpirationSQL + " where" + " (c.user_Id like 'PublicUser%') and " + " (c.expiration_Date is null)"; Query initPublicCarts = session.createSQLQuery(initializeSessionCartSql); //Set expiration date to fullExpiration if the user starts with 'PublicUser', the cart has been active (read or written to) in the last day and the cart has items //String nonEmptyCartSql = "UPDATE cart c left join cart_object co on c.id = co.cart_id " + //" set expiration_Date = "+fullExpirationSQL+" where" + //" (c.user_Id like 'PublicUser%') and " + //" (c.last_write_date > DATE_SUB(SYSDATE, INTERVAL "+ (sleepTime * 2)+" MINUTE) OR c.last_read_date > DATE_SUB(SYSDATE, INTERVAL "+ (sleepTime * 2) +" MINUTE)) and" + //" (co.id is not null)"; String nonEmptyCartSql = "UPDATE cart c " + " set expiration_Date = " + fullExpirationSQL + " where" + " (c.user_Id like 'PublicUser%') and " + " (c.last_write_date > (SYSDATE - INTERVAL '" + (sleepTime * 2) + "' MINUTE) OR c.last_read_date > (SYSDATE - INTERVAL '" + (sleepTime * 2) + "' MINUTE)) and" + " EXISTS (select id from cart_object co where co.id is not null and co.cart_id = c.id)"; Query expNonEmptyPublicCarts = session.createSQLQuery(nonEmptyCartSql); //Now delete expired carts (carts where expiration date is in the past) //REQUIRES ON-DELETE Cascade support in underlying database on the //CartObject cart_id FK constraint Query deleteCartQuery = session.createQuery( "delete from gov.nih.nci.cadsr.objectcart.domain.Cart " + "where expirationDate <=:now"); deleteCartQuery.setTimestamp("now", now); try { int resetResults = updateActiveCarts.executeUpdate(); if (resetResults > 0) log.debug("Reset expiration date for " + resetResults + "active carts"); log.debug("Reset expiration date for " + resetResults + "active carts"); /* GF 28500 */ int expResults = initPublicCarts.executeUpdate(); if (expResults > 0) log.debug("Expiration date set for " + expResults + " PublicUser carts"); int expNEPCResults = expNonEmptyPublicCarts.executeUpdate(); if (expNEPCResults > 0) log.debug("Expiration date set for " + expNEPCResults + " PublicUser carts"); /* GF 28500 */ int results = deleteCartQuery.executeUpdate(); if (results > 0) log.debug("Deleted " + results + " carts at " + now.toString()); } catch (JDBCException ex) { log.error("JDBC Exception in ORMDAOImpl ", ex); ex.printStackTrace(); } catch (org.hibernate.HibernateException hbmEx) { log.error(hbmEx.getMessage()); hbmEx.printStackTrace(); } catch (Exception e) { log.error("Exception ", e); e.printStackTrace(); } finally { try { tx.commit(); session.close(); } catch (Exception eSession) { log.error("Could not close the session - " + eSession.getMessage()); eSession.printStackTrace(); } } }
From source file:gemlite.shell.commands.Import.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @CliCommand(value = "describe job", help = "describe job by id") public String describeJob(@CliOption(key = { "id" }, mandatory = true, optionContext = "disable-string-converter param.context.job.id") String jobExecutionId) { BatchService batchService = JpaContext.getService(BatchService.class); Map jobExecution = batchService.getJobExecution(NumberUtils.createLong(jobExecutionId)); //duration/* w w w. ja v a 2 s.c o m*/ Timestamp t1 = (Timestamp) jobExecution.get("start_time"); Timestamp t2 = (Timestamp) jobExecution.get("last_updated"); String duration = ""; if (t2 != null) duration = DateUtil.format(new Date(t2.getTime() - t1.getTime()), "mm:ss.SSS"); jobExecution.put("duration", duration); List<Map> steps = batchService.getStepExecutions(NumberUtils.createLong(jobExecutionId)); jobExecution.put("steps", steps); //?ws put(CommandMeta.DESCRIBE_JOB, jobExecution); //?? StringBuilder sb = new StringBuilder(); sb.append("JobName:").append(jobExecution.get("job_name")).append("\n"); sb.append("Status:").append(jobExecution.get("status")).append("\n"); sb.append("StartTime:").append(jobExecution.get("start_time")).append("\n"); sb.append("LastUpdateTime:").append(jobExecution.get("last_updated")).append("\n"); sb.append("Duration:").append(jobExecution.get("duration")).append("\n"); sb.append("StepDetails:\n"); for (Map step : steps) { sb.append("StepName:").append(step.get("step_name")); sb.append(" Status:").append(step.get("status")); sb.append(" ReadCount:").append(step.get("read_count")); sb.append(" WriteCount:").append(step.get("write_count")); sb.append(" CommitCount:").append(step.get("commit_count")); sb.append("\n"); String exit_message = (String) step.get("exit_message"); if (!StringUtils.isEmpty(exit_message)) { sb.append("EXIT_MESSAGE:\n"); sb.append(exit_message); sb.append("\n"); } } return sb.toString(); }
From source file:info.pancancer.arch3.reporting.Arch3ReportImpl.java
@Override public Map<String, Map<String, String>> getJobInfo() { Map<String, Map<String, String>> map = new TreeMap<>(); for (JobState state : JobState.values()) { List<Job> jobs = db.getJobs(state); Date now = new Date(); Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime()); long time = currentTimestamp.getTime(); DecimalFormat df = new DecimalFormat("#.00"); for (Job job : jobs) { Map<String, String> jobMap = new TreeMap<>(); jobMap.put("status", job.getState().toString()); jobMap.put("workflow", job.getWorkflow()); jobMap.put("workflow_version", job.getWorkflowVersion()); long lastSeen = job.getUpdateTs().getTime(); double secondsAgo = (time - lastSeen) / MILLISECONDS_IN_SECOND; jobMap.put("last seen (seconds)", df.format(secondsAgo)); long firstSeen = job.getCreateTs().getTime(); double hoursAgo = (time - firstSeen) / (MILLISECONDS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR); jobMap.put("first seen(hours)", df.format(hoursAgo)); map.put(job.getUuid(), jobMap); }/* ww w .j a v a2 s . c o m*/ } return map; }
From source file:uk.org.funcube.fcdw.server.extract.csv.WodCsvExtractor.java
@Transactional(readOnly = true, propagation = Propagation.REQUIRED) public void extract(long satelliteId) { Date currentDate = clock.currentDate(); Timestamp latestSatelliteTime = wholeOrbitDataDao.getLatestSatelliteTime(satelliteId); Timestamp since = new Timestamp(latestSatelliteTime.getTime() - (24 * 60 * 60 * 1000)); List<WholeOrbitDataEntity> wod24 = wholeOrbitDataDao.getSinceSatelliteTime(satelliteId, since); if (wod24.size() == 0) { return;/*from w w w. j a va 2 s . c o m*/ } File fileLocation = new File(System.getProperty("csv.wod")); if (fileLocation.exists()) { fileLocation.delete(); } writeFile(wod24, fileLocation); }
From source file:org.apache.roller.weblogger.ui.rendering.pagers.MediaFilesPager.java
/** Get last updated time from items in pager */ public Date getLastUpdated() { if (lastUpdated == null) { // feeds are sorted by pubtime, so first might not be last updated List<MediaFile> items = (List<MediaFile>) getItems(); if (items != null && items.size() > 0) { Timestamp newest = ((MediaFile) items.get(0)).getLastUpdated(); for (MediaFile file : items) { if (file.getLastUpdated().after(newest)) { newest = file.getLastUpdated(); }/*www. jav a2 s. c om*/ } lastUpdated = new Date(newest.getTime()); } else { // no update so we assume it's brand new lastUpdated = new Date(); } } return lastUpdated; }
From source file:info.pancancer.arch3.reporting.Arch3ReportImpl.java
@Override public Map<String, Map<String, String>> getVMInfo(ProvisionState... states) { Map<String, AbstractInstanceListing.InstanceDescriptor> youxiaInstances = this.getYouxiaInstances(); Set<String> activeIPAddresses = new HashSet<>(); // curate set of ip addresses for active instances for (Entry<String, AbstractInstanceListing.InstanceDescriptor> entry : youxiaInstances.entrySet()) { activeIPAddresses.add(entry.getValue().getIpAddress()); activeIPAddresses.add(entry.getValue().getPrivateIpAddress()); }/*from w w w.ja v a2 s . co m*/ System.out.println("Set of active addresses: " + activeIPAddresses.toString()); // this map is provision_uuid -> keys -> values Map<String, Map<String, String>> map = new TreeMap<>(); for (ProvisionState state : states) { List<Provision> provisions = db.getProvisions(state); Date now = new Date(); Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime()); long time = currentTimestamp.getTime(); DecimalFormat df = new DecimalFormat("#.00"); for (Provision provision : provisions) { System.out.println("Checking " + provision.getIpAddress()); if (!activeIPAddresses.contains(provision.getIpAddress())) { System.out.println("Excluding " + provision.getIpAddress() + " due to youxia filter"); continue; } Map<String, String> jobMap = new TreeMap<>(); jobMap.put("ip_address", provision.getIpAddress()); jobMap.put("status", provision.getState().toString()); long lastSeen = provision.getUpdateTimestamp().getTime(); double secondsAgo = (time - lastSeen) / MILLISECONDS_IN_SECOND; jobMap.put("last seen with live heartbeat (seconds)", df.format(secondsAgo)); long firstSeen = provision.getCreateTimestamp().getTime(); double hoursAgo = (time - firstSeen) / (MILLISECONDS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR); jobMap.put("first seen in submission queue (hours)", df.format(hoursAgo)); map.put(provision.getProvisionUUID(), jobMap); } } return map; }
From source file:org.freebxml.omar.server.persistence.rdb.SubscriptionDAO.java
protected void loadObject(Object obj, ResultSet rs) throws RegistryException { try {/* w w w . ja va 2s . c om*/ if (!(obj instanceof org.oasis.ebxml.registry.bindings.rim.Subscription)) { throw new RegistryException(ServerResourceBundle.getInstance() .getString("message.SubscriptionTypeExpected", new Object[] { obj })); } Subscription subscription = (Subscription) obj; super.loadObject(obj, rs); String selector = rs.getString("selector"); subscription.setSelector(selector); //Need to work around a bug in PostgreSQL and loading of ClassificationScheme data from NIST tests try { Timestamp endTime = rs.getTimestamp("endTime"); if (endTime != null) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(endTime.getTime()); subscription.setEndTime(calendar); } } catch (StringIndexOutOfBoundsException e) { String id = rs.getString("id"); log.error(ServerResourceBundle.getInstance().getString("message.SubscriptionDAOId", new Object[] { id }), e); } String notificationInterval = rs.getString("notificationInterval"); if (notificationInterval != null) { subscription.setNotificationInterval(notificationInterval); } //Need to work around a bug in PostgreSQL and loading of ClassificationScheme data from NIST tests try { Timestamp startTime = rs.getTimestamp("startTime"); if (startTime != null) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(startTime.getTime()); subscription.setStartTime(calendar); } } catch (StringIndexOutOfBoundsException e) { String id = rs.getString("id"); log.error(ServerResourceBundle.getInstance().getString("message.SubscriptionDAOId", new Object[] { id }), e); } NotifyActionDAO notifyActionDAO = new NotifyActionDAO(context); notifyActionDAO.setParent(subscription); List notifyActions = notifyActionDAO.getByParent(); if (notifyActions != null) { subscription.getAction().addAll(notifyActions); } } catch (SQLException e) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e); throw new RegistryException(e); } }
From source file:mydropbox.Client.java
public boolean deleteFile(String fileName) throws IOException { Timestamp temp_timestamp = new Timestamp(System.currentTimeMillis()); long timestamp = temp_timestamp.getTime(); HttpGet httpGet = new HttpGet(this.host + "delete/" + fileName + '/' + timestamp); httpGet.setHeader("User-Agent", USER_AGENT); httpGet.setHeader("MyDropBox", "MyDropBox"); HttpResponse response;/* w w w .j a v a 2s.com*/ try { response = httpClient.execute(httpGet); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); int status = response.getStatusLine().getStatusCode(); System.out.println("Response Code : " + status); System.out.println(EntityUtils.toString(resEntity)); if (status >= 200 && status < 300) { httpGet.releaseConnection(); return true; } else { httpGet.releaseConnection(); return false; } } catch (Exception ex) { httpGet.releaseConnection(); return false; } finally { setTimeStamp(timestamp); } }
From source file:mydropbox.Client.java
public boolean sendFile(String fileName) throws IOException { int status = 0; Timestamp temp_timestamp = new Timestamp(System.currentTimeMillis()); long timestamp = temp_timestamp.getTime(); File file = new File("./files/" + fileName); HttpPost httpPost = new HttpPost(this.host + "upload" + '/' + timestamp); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart(file.getName(), cbFile); httpPost.setEntity(mpEntity);/*from w ww .jav a 2 s . c o m*/ System.out.println("executing request " + httpPost.getRequestLine()); HttpResponse response; try { httpPost.setHeader("User-Agent", USER_AGENT); httpPost.setHeader("MyDropBox", "MyDropBox"); response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); status = response.getStatusLine().getStatusCode(); System.out.println("Response Code : " + status); System.out.println(EntityUtils.toString(resEntity)); } catch (Exception ex) { ex.printStackTrace(); } finally { setTimeStamp(timestamp); } if (status >= 200 && status < 300) return true; else return false; }