List of usage examples for java.util Date setTime
public void setTime(long time)
From source file:de.grobox.transportr.departures.DeparturesActivity.java
private synchronized void loadMoreDepartures(boolean later) { Date date = new Date(); int maxDepartures = MAX_DEPARTURES; int count = adapter.getItemCount(); // search from end + safety margin if (later) {// w ww .j a v a2 s . c o m int itemPos; if (count - SAFETY_MARGIN > 0) { itemPos = count - SAFETY_MARGIN; maxDepartures = MAX_DEPARTURES + SAFETY_MARGIN; } else { itemPos = count - 1; } // FIXME for some reason this can crash Log.i(DeparturesActivity.class.getSimpleName(), "Count: " + count + " Get Item: " + itemPos); date = adapter.getItem(itemPos).getTime(); } // search from beginning + safety margin else { Date earliest = adapter.getEarliestDate(); Date latest; int itemPos; if (count >= MAX_DEPARTURES) { itemPos = MAX_DEPARTURES - 1; } else { itemPos = count - 1; } latest = adapter.getItem(itemPos).getTime(); long span = latest.getTime() - earliest.getTime(); date.setTime(earliest.getTime() - span); maxDepartures = MAX_DEPARTURES + SAFETY_MARGIN; } searchState = later ? SearchState.BOTTOM : SearchState.TOP; Bundle args = getBundle(location.getId(), date, maxDepartures); getSupportLoaderManager().restartLoader(LOADER_DEPARTURES, args, this).forceLoad(); }
From source file:info.raack.appliancelabeler.web.MainController.java
@RequestMapping(value = "/energydata", method = RequestMethod.GET) public void getEnergyForUser(@RequestParam(value = "userId") String userId, @RequestParam(value = "start", required = false) Double startMillis, @RequestParam(value = "end", required = false) Double endMillis, HttpServletResponse response) throws IOException { logger.debug("Serving request for user info for " + userId); // get first energy monitor for user List<Ted5000> teds = null; int retry = 3; while (true) { try {/*from w w w . j av a 2s .co m*/ teds = dataService.getTEDIdsForUserId(userId, true); break; } catch (OAuthUnauthorizedException e) { throw new ClientAPIException("User " + userId + " has not authorized use of their Stepgreen data by accessing and logging into " + energyLabelerUrl + "t/controlpanel first", e); } catch (Exception e) { // retry if (retry-- == 0) { throw new RuntimeException( "Could not access energy data for user id " + userId + " after 3 attempts", e); } } } // TODO - allow user to select the Ted / MTU combination that they want to use, put it in the path // right now, just select the first ted and mtu if (teds.size() > 0) { Ted5000 ted = teds.get(0); if (ted.getTed5000Mtu().size() > 0) { Mtu mtu = ted.getTed5000Mtu().get(0); EnergyMonitor energyMonitor = new Ted5000Monitor(-1, userId, ted.getId(), mtu.getId(), "test"); Date start = null; Date end = null; if (startMillis != null && endMillis != null) { start = new Date(startMillis.longValue()); end = new Date(endMillis.longValue()); } else if (startMillis != null && endMillis == null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(startMillis.longValue()); start = new Date(); start.setTime(startMillis.longValue()); c.add(Calendar.DATE, 1); end = c.getTime(); } else if (startMillis == null && endMillis != null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(endMillis.longValue()); end = new Date(); end.setTime(endMillis.longValue()); c.add(Calendar.DATE, -1); start = c.getTime(); } else { // create a one day span if (energyMonitor != null) { end = database.getLastMeasurementTimeForEnergyMonitor(energyMonitor); } if (end == null) { end = new Date(); } Calendar c = new GregorianCalendar(); c.setTime(end); c.add(Calendar.DATE, -1); start = c.getTime(); } Calendar cal = new GregorianCalendar(); cal.setTime(start); Date queryStart = dateUtils.getPreviousFiveMinuteIncrement(cal).getTime(); cal = new GregorianCalendar(); cal.setTime(end); Date queryEnd = dateUtils.getNextFiveMinuteIncrement(cal).getTime(); Map<UserAppliance, List<EnergyTimestep>> predictedEnergyUsage = dataService .getApplianceEnergyConsumptionForMonitor(energyMonitor, algorithm.getId(), queryStart, queryEnd); Map<String, Double> result = new HashMap<String, Double>(); for (UserAppliance app : predictedEnergyUsage.keySet()) { Double total = 0d; for (EnergyTimestep timestep : predictedEnergyUsage.get(app)) { total += timestep.getEnergyConsumed(); } result.put(app.getName(), total); } String dataJS = new GsonBuilder().create().toJson(result); response.getWriter().write(dataJS); // set appropriate JSON response type response.setContentType("application/json"); return; } } throw new ClientAPIException("No ted monitors found for user " + userId); }
From source file:org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceScanner.java
synchronized void printBlockReport(StringBuilder buffer, boolean summaryOnly) { long oneHour = 3600 * 1000; long oneDay = 24 * oneHour; long oneWeek = 7 * oneDay; long fourWeeks = 4 * oneWeek; int inOneHour = 0; int inOneDay = 0; int inOneWeek = 0; int inFourWeeks = 0; int inScanPeriod = 0; int neverScanned = 0; DateFormat dateFormat = new SimpleDateFormat(DATA_FORMAT); int total = blockInfoSet.size(); long now = Time.monotonicNow(); Date date = new Date(); for (Iterator<BlockScanInfo> it = blockInfoSet.iterator(); it.hasNext();) { BlockScanInfo info = it.next();//w w w . java 2 s. c om long scanTime = info.getLastScanTime(); long diff = now - scanTime; if (diff <= oneHour) inOneHour++; if (diff <= oneDay) inOneDay++; if (diff <= oneWeek) inOneWeek++; if (diff <= fourWeeks) inFourWeeks++; if (diff <= scanPeriod) inScanPeriod++; if (scanTime <= 0) neverScanned++; if (!summaryOnly) { date.setTime(scanTime); String scanType = (info.lastScanType == ScanType.VERIFICATION_SCAN) ? "local" : "none"; buffer.append(String.format("%-26s : status : %-6s type : %-6s" + " scan time : " + "%-15d %s%n", info, (info.lastScanOk ? "ok" : "failed"), scanType, scanTime, (scanTime <= 0) ? "not yet verified" : dateFormat.format(date))); } } double pctPeriodLeft = (scanPeriod + currentPeriodStart - now) * 100.0 / scanPeriod; double pctProgress = (totalBytesToScan == 0) ? 100 : (totalBytesToScan - bytesLeft) * 100.0 / totalBytesToScan; buffer.append(String.format("%nTotal Blocks : %6d" + "%nVerified in last hour : %6d" + "%nVerified in last day : %6d" + "%nVerified in last week : %6d" + "%nVerified in last four weeks : %6d" + "%nVerified in SCAN_PERIOD : %6d" + "%nNot yet verified : %6d" + "%nVerified since restart : %6d" + "%nScans since restart : %6d" + "%nScan errors since restart : %6d" + "%nTransient scan errors : %6d" + "%nCurrent scan rate limit KBps : %6d" + "%nProgress this period : %6.0f%%" + "%nTime left in cur period : %6.2f%%" + "%n", total, inOneHour, inOneDay, inOneWeek, inFourWeeks, inScanPeriod, neverScanned, totalScans, totalScans, totalScanErrors, totalTransientErrors, Math.round(throttler.getBandwidth() / 1024.0), pctProgress, pctPeriodLeft)); }
From source file:com.all.login.view.NewAccountFormPanel.java
void validateDate() { Date date = getUser().getBirthday(); if (date == null) { date = new Date(); }//from w ww . ja v a2 s. co m if (month >= 0 && day > 0 && year > 0) { Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.MONTH, month); c.set(Calendar.DAY_OF_MONTH, day); c.set(Calendar.YEAR, year); c.setLenient(false); // this validates the date // TODO manage valid date exception date.setTime(c.getTimeInMillis()); getUser().setBirthday(date); // TODO: remove this comment after we decide to add mediagraphics info // validateAllUserData(); // end TODO } else { getUser().setBirthday(null); } }
From source file:com.example.android.contactslist.ui.eventEntry.EventEntryFragment.java
private void setDateAndTimeViews(Long timeInMills) { // set the default time to now Date date = new Date(); // if the time is not 0, then we should set the date to it if (timeInMills != 0) { date.setTime(timeInMills); }/* w ww . ja va 2 s . c o m*/ mEventDate = date.getTime(); DateFormat formatDate = new SimpleDateFormat(getResources().getString(R.string.date_format)); String formattedDate = formatDate.format(date); mDateViewButton.setText(formattedDate); DateFormat formatTime = new SimpleDateFormat(getResources().getString(R.string.twelve_hour_time_format)); String formattedTime = formatTime.format(date); mTimeViewButton.setText(formattedTime); }
From source file:com.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java
protected String getPhotoFileName(File tempPhotoFile) throws IOException { String prefix = ""; switch (mFoclStructLayerType) { case FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CABLE_POINT: prefix = "Optical_Cable_Laying_"; break;/* w w w . ja v a 2 s.c om*/ case FoclConstants.LAYERTYPE_FOCL_REAL_FOSC: prefix = "FOSC_Mounting_"; break; case FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CROSS: prefix = "Cross_Mounting_"; break; case FoclConstants.LAYERTYPE_FOCL_REAL_ACCESS_POINT: prefix = "Access_Point_Mounting_"; break; case FoclConstants.LAYERTYPE_FOCL_REAL_SPECIAL_TRANSITION_POINT: prefix = "Special_Transition_Point_"; break; } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US); Date date = BitmapUtil.getExifDate(tempPhotoFile); if (null == date) { date = new Date(); date.setTime(System.currentTimeMillis()); } String timeStamp = sdf.format(date); return prefix + timeStamp + ".jpg"; }
From source file:no.abmu.organisationregister.service.hibernate3.OrganisationUnitServiceH3Impl.java
private void updatePostalAddressWithAddressTypeChange(OrganisationUnit organisationUnit, StoreList storeList, AddressSummary addressSummary) { Date changeDate = addressSummary.getNewPostalAddressFrom(); // Check to make sure address change date is in the past. if (changeDate.after(new Date())) { logger.warn("Aborting update. " + "Currently we will not allow change on addresses to a time in the futhure: " + changeDate); return;//from ww w . java2 s . c o m } Date dayBefore = new Date(); dayBefore.setTime((changeDate.getTime() - 1)); ContactInformation postalAddressInfo = organisationUnit.getContactInformation(ContactRole.POSTAL_ADDRESS); String postalAddressType = addressSummary.getPostalAddressType(); // Get all contact relations. Set<ContactRelation> contactRelations = organisationUnit.getContactRelations(); // Setting up list of all existing postal addresses. List<ContactRelation> existingPostalAddresses = new ArrayList<ContactRelation>(); for (ContactRelation cRelation : contactRelations) { if (cRelation.getContactRole().getReference().equals(ContactRole.POSTAL_ADDRESS)) { existingPostalAddresses.add(cRelation); } } if (postalAddressInfo instanceof StreetAddress) { if (postalAddressType.equals(AddressSummary.POSTAL_ADDRESS_TYPE_POB)) { // Changing postal address type to PostBox address. logger.info("Change postal address from StreetAddress to PostBoks address from date." + changeDate); POBoxAddress poBoxAddress = new POBoxAddress(); poBoxAddress.setPoBoxNumber(addressSummary.getPostBoxPostalBoxNumber()); poBoxAddress.setPoBoxOffice(addressSummary.getPostBoxPostalBoxOffice()); poBoxAddress.setPostCodeNumber(addressSummary.getPostBoxPostalCode()); poBoxAddress.setPostCodeName(addressSummary.getPostBoxPostalPlace()); logger.info("New PostBoks befor saving: " + poBoxAddress); // All old postal addresses should no longer have default value. // If active setting end date. for (ContactRelation cRelation : existingPostalAddresses) { cRelation.setDefaultChoice(false); if (cRelation.isActive()) { cRelation.setEndDate(dayBefore); storeList.add(cRelation); } } ContactRole contactRole = getContactRole(ContactRole.POSTAL_ADDRESS); ContactRelation postalAddressContactRelation = new ContactRelation(contactRole, poBoxAddress); postalAddressContactRelation.setStartDate(changeDate); postalAddressContactRelation.setDefaultChoice(true); contactRelations.add(postalAddressContactRelation); storeList.add(postalAddressContactRelation); } else if (postalAddressType.equals(AddressSummary.POSTAL_ADDRESS_TYPE_STREET)) { StreetAddress streetAddress = (StreetAddress) postalAddressInfo; streetAddress.setAddressLine1(addressSummary.getStreetPostalAddress()); streetAddress.setAddressLine2(addressSummary.getStreetPostalAddressLine2()); streetAddress.setPostCodeNumber(addressSummary.getStreetPostalCode()); streetAddress.setPostCodeName(addressSummary.getStreetPostalPlace()); storeList.add(streetAddress); } else { logger.warn("Not known postal address type"); throw new IllegalArgumentException("Not known postal address type"); } } else if (postalAddressInfo instanceof POBoxAddress) { if (postalAddressType.equals(AddressSummary.POSTAL_ADDRESS_TYPE_STREET)) { // Changing address type to street address. logger.info("Change Postal address from PostBoks address to StreetAddress from date." + changeDate); StreetAddress streetAddress = new StreetAddress(); streetAddress.setAddressLine1(addressSummary.getStreetPostalAddress()); streetAddress.setAddressLine2(addressSummary.getStreetPostalAddressLine2()); streetAddress.setPostCodeNumber(addressSummary.getStreetPostalCode()); streetAddress.setPostCodeName(addressSummary.getStreetPostalPlace()); logger.info("New StreetAddress befor saving: " + streetAddress); // All old postal addresses should no longer have default value. // If active setting end date. for (ContactRelation cRelation : existingPostalAddresses) { cRelation.setDefaultChoice(false); if (cRelation.isActive()) { cRelation.setEndDate(dayBefore); storeList.add(cRelation); } } ContactRole contactRole = getContactRole(ContactRole.POSTAL_ADDRESS); ContactRelation postalAddressContactRelation = new ContactRelation(contactRole, streetAddress); postalAddressContactRelation.setStartDate(changeDate); postalAddressContactRelation.setDefaultChoice(true); contactRelations.add(postalAddressContactRelation); storeList.add(postalAddressContactRelation); } else if (postalAddressType.equals(AddressSummary.POSTAL_ADDRESS_TYPE_POB)) { POBoxAddress poBoxAddress = (POBoxAddress) postalAddressInfo; poBoxAddress.setPoBoxNumber(addressSummary.getPostBoxPostalBoxNumber()); poBoxAddress.setPoBoxOffice(addressSummary.getPostBoxPostalBoxOffice()); poBoxAddress.setPostCodeNumber(addressSummary.getPostBoxPostalCode()); poBoxAddress.setPostCodeName(addressSummary.getPostBoxPostalPlace()); storeList.add(poBoxAddress); } else { logger.warn("Not known postal address type"); throw new IllegalArgumentException("Not known postal address type"); } } else { logger.warn("Not known postal address type" + postalAddressInfo); throw new IllegalArgumentException("Not known postal address type" + postalAddressInfo); } }
From source file:org.apache.hadoop.dfs.DataBlockScanner.java
synchronized void printBlockReport(StringBuilder buffer, boolean summaryOnly) { long oneHour = 3600 * 1000; long oneDay = 24 * oneHour; long oneWeek = 7 * oneDay; long fourWeeks = 4 * oneWeek; int inOneHour = 0; int inOneDay = 0; int inOneWeek = 0; int inFourWeeks = 0; int inScanPeriod = 0; int neverScanned = 0; int total = blockInfoSet.size(); long now = System.currentTimeMillis(); Date date = new Date(); for (Iterator<BlockScanInfo> it = blockInfoSet.iterator(); it.hasNext();) { BlockScanInfo info = it.next();//from w ww .j a va 2 s.co m long scanTime = info.getLastScanTime(); long diff = now - scanTime; if (diff <= oneHour) inOneHour++; if (diff <= oneDay) inOneDay++; if (diff <= oneWeek) inOneWeek++; if (diff <= fourWeeks) inFourWeeks++; if (diff <= scanPeriod) inScanPeriod++; if (scanTime <= 0) neverScanned++; if (!summaryOnly) { date.setTime(scanTime); String scanType = (info.lastScanType == ScanType.REMOTE_READ) ? "remote" : ((info.lastScanType == ScanType.VERIFICATION_SCAN) ? "local" : "none"); buffer.append(String.format("%-26s : status : %-6s type : %-6s" + " scan time : " + "%-15d %s\n", info.block, (info.lastScanOk ? "ok" : "failed"), scanType, scanTime, (scanTime <= 0) ? "not yet verified" : dateFormat.format(date))); } } double pctPeriodLeft = (scanPeriod + currentPeriodStart - now) * 100.0 / scanPeriod; double pctProgress = (totalBytesToScan == 0) ? 100 : (totalBytesToScan - bytesLeft) * 10000.0 / totalBytesToScan / (100 - pctPeriodLeft + 1e-10); buffer.append(String.format("\nTotal Blocks : %6d" + "\nVerified in last hour : %6d" + "\nVerified in last day : %6d" + "\nVerified in last week : %6d" + "\nVerified in last four weeks : %6d" + "\nVerified in SCAN_PERIOD : %6d" + "\nNot yet verified : %6d" + "\nVerified since restart : %6d" + "\nScans since restart : %6d" + "\nScan errors since restart : %6d" + "\nTransient scan errors : %6d" + "\nCurrent scan rate limit KBps : %6d" + "\nProgress this period : %6.0f%%" + "\nTime left in cur period : %6.2f%%" + "\n", total, inOneHour, inOneDay, inOneWeek, inFourWeeks, inScanPeriod, neverScanned, totalVerifications, totalScans, totalScanErrors, totalTransientErrors, Math.round(throttler.getBandwidth() / 1024.0), pctProgress, pctPeriodLeft)); }
From source file:ch.systemsx.cisd.openbis.plugin.generic.client.web.server.GenericClientService.java
public Date updateSample(final SampleUpdates updates) throws ch.systemsx.cisd.openbis.generic.client.web.client.exception.UserFailureException { final String sessionToken = getSessionToken(); final Date modificationDate = new Date(); new AttachmentRegistrationHelper() { @Override/* ww w . j av a 2s . c o m*/ public void register(Collection<NewAttachment> attachments) { ExperimentIdentifier convExperimentIdentifierOrNull = null; SampleIdentifier sampleOwner = null; if (updates.getExperimentIdentifierOrNull() != null) { convExperimentIdentifierOrNull = new ExperimentIdentifierFactory( updates.getExperimentIdentifierOrNull().getIdentifier()).createIdentifier(); } if (StringUtils.isBlank(updates.getSampleIdentifier()) == false) { sampleOwner = new SampleIdentifierFactory(updates.getSampleIdentifier()).createIdentifier(); } Date date = genericServer.updateSample(sessionToken, new SampleUpdatesDTO(updates.getSampleId(), updates.getProperties(), convExperimentIdentifierOrNull, attachments, updates.getVersion(), sampleOwner, updates.getParentIdentifierOrNull(), updates.getContainerIdentifierOrNull())); modificationDate.setTime(date.getTime()); } }.process(updates.getSessionKey(), getHttpSession(), updates.getAttachments()); return modificationDate; }
From source file:org.apache.openjpa.util.ProxyManagerImpl.java
public Proxy newCustomProxy(Object orig, boolean autoOff) { if (orig == null) return null; if (orig instanceof Proxy) return (Proxy) orig; if (ImplHelper.isManageable(orig)) return null; if (!isProxyable(orig.getClass())) return null; if (orig instanceof Collection) { Comparator comp = (orig instanceof SortedSet) ? ((SortedSet) orig).comparator() : null; Collection c = (Collection) newCollectionProxy(orig.getClass(), null, comp, autoOff); c.addAll((Collection) orig); return (Proxy) c; }//from ww w . ja v a 2s.c om if (orig instanceof Map) { Comparator comp = (orig instanceof SortedMap) ? ((SortedMap) orig).comparator() : null; Map m = (Map) newMapProxy(orig.getClass(), null, null, comp, autoOff); m.putAll((Map) orig); return (Proxy) m; } if (orig instanceof Date) { Date d = (Date) newDateProxy(orig.getClass()); d.setTime(((Date) orig).getTime()); if (orig instanceof Timestamp) ((Timestamp) d).setNanos(((Timestamp) orig).getNanos()); return (Proxy) d; } if (orig instanceof Calendar) { Calendar c = (Calendar) newCalendarProxy(orig.getClass(), ((Calendar) orig).getTimeZone()); c.setTimeInMillis(((Calendar) orig).getTimeInMillis()); return (Proxy) c; } ProxyBean proxy = getFactoryProxyBean(orig); return (proxy == null) ? null : proxy.newInstance(orig); }