List of usage examples for java.util.concurrent TimeUnit HOURS
TimeUnit HOURS
To view the source code for java.util.concurrent TimeUnit HOURS.
Click Source Link
From source file:org.wso2.carbon.cloud.gateway.transport.CGTransportSender.java
private static TimeUnit getTimeUnit(String timeUnit) { if (timeUnit.equals(CGConstant.MILLISECOND)) { return TimeUnit.MILLISECONDS; } else if (timeUnit.equals(CGConstant.SECOND)) { return TimeUnit.SECONDS; } else if (timeUnit.equals(CGConstant.MINUTE)) { return TimeUnit.MINUTES; } else if (timeUnit.equals(CGConstant.HOUR)) { return TimeUnit.HOURS; } else if (timeUnit.equals(CGConstant.DAY)) { return TimeUnit.DAYS; } else {// ww w .java2s .c om // the default return TimeUnit.DAYS; } }
From source file:dk.dma.ais.store.FileExportRest.java
/** {@inheritDoc} */ @Override/*www. j a va 2 s . c om*/ protected void run(Injector injector) throws Exception { printAisStoreNL("AIS STORE COMMAND LINE TOOL INITIATED"); printAisStoreLine(); // Hardcoded values // interval = "2015-1-5T14:00:00Z/2015-1-5T14:10:00Z"; // java -jar ais-store-cli-0.3-SNAPSHOT.jar export -area 15,-18,-10,14 -filter // "m.country=DNK & t.pos within bbox(15,-18,-10,14) & (t.lat<-0.3|t.lat>0.3) & (t.lon<-0.3|t.lon>0.3)" -fetchSize 30000 // -interval // java -jar ais-store-cli-0.3-SNAPSHOT.jar export -area 15,-18,-10,14 -filter // "m.country=DNK & t.pos within bbox(15,-18,-10,14) & (t.lat<-0.3|t.lat>0.3) & (t.lon<-0.3|t.lon>0.3)" -fetchSize 30000 // -interval 2015-1-5T14:00:00Z/2015-1-5T14:10:00Z // Create request String request = ""; if (interval == null || interval.equals("")) { printAisStoreNL("No Interval provided, please check your request."); // return; terminateAndPrintHelp(); } try { intervalVar = Interval.parse(interval); } catch (Exception e) { printAisStoreNL("Invalid Interval provided, please check your request."); terminateAndPrintHelp(); } // intervalVar = DateTimeUtil.toInterval(intervalStr); intervalStartTime = intervalVar.getStartMillis(); String intervalStr = interval.toString(); request = request + "?interval=" + interval; // System.out.println("Interval parsed correct " + intervalStr); // Check if interval is valid, throw exception etc // Create task for exception throwing if args are required // If error, throw exception of error description then -help if (mmsis.size() > 0) { request = request + "&mmsi="; for (int i = 0; i < mmsis.size() - 1; i++) { request = request + Integer.toString(mmsis.get(i)) + ","; } request = request + mmsis.get(mmsis.size() - 1); } // filter // Google URL Encoder // "t.name like H* & t.name like HAMLET" // CHeck if url filter is valid, then url encode it and add to request // filter = "t.name like H* & t.name like HAMLET"; // filter = "s.country in (DNK)"; if (filter != null && !filter.equals("")) { String encodedFilter = URLEncoder.encode(filter, "UTF-8"); try { AisPacketFilters.parseExpressionFilter(filter); } catch (Exception e) { printAisStoreNL("Invalid filter expression"); terminateAndPrintHelp(); } request = request + "&filter=" + encodedFilter; } // area // "&box=lat1,lon1,lat2,lon2" // blabla check if valid if (area != null && !area.equals("")) { request = request + "&box=" + area; } // If table, make sure column is added if ((columns == null || columns.equals("")) && (outputFormat.equals("table") || outputFormat.equals("jsonObject"))) { printAisStoreNL("When using outputFormat " + outputFormat + ", columns are required"); terminateAndPrintHelp(); } try { sink = AisPacketOutputSinks.getOutputSink(outputFormat, columns, separator); request = request + "&outputFormat=" + outputFormat; } catch (Exception e) { printAisStoreNL("Invalid output format provided, " + outputFormat + ", please check your request."); terminateAndPrintHelp(); } // if table do shit // columns \/ REQUIRED // "columns=mmsi;time;timestamp" // Check if valid // Split on ";" // "columns=<listElement0>:list1" if (columns != null) { request = request + "&columns=" + columns; } // seperator // "seperator=\t" // Url encode and add if (separator != null || !separator.equals("")) { String encodedSeparator = URLEncoder.encode(separator, "UTF-8"); request = request + "&seperator=" + encodedSeparator; } // fetchSize if (fetchSize != -1) { request = request + "&fetchsize=" + fetchSize; } // Get path from request, if none it will store in root of ais store client // filePath = "C:\\AisStoreData\\"; if (filePath == null) { filePath = ""; } else { filePath = filePath + "/"; } // No filename provided, generate unique based on request parameters if (fileName == null || fileName.equals("")) { MessageDigest md5 = MessageDigest.getInstance("MD5"); String hex = (new HexBinaryAdapter()).marshal(md5.digest(request.getBytes())); fileName = hex; } // Generate unique hashsum based on request metaFileName = fileName + ".aisstore"; // boolean isTryResume = true; // If we are trying to resume, don't override previous file try { fileOutputStream = new FileOutputStream(filePath + fileName, !forceDownload); } catch (Exception e) { printAisStoreNL("Error occuring writing to disk, make sure the folder path exists "); terminateAndPrintHelp(); } outputStream = new BufferedOutputStream(fileOutputStream); // Should we resume anything // We have read the file // If the file exists that means a previous transaction has been done // Do we resume, if we do, we need to find the resume point ie move the start interval /** * System.out.println("Test Compare"); System.out.println(intervalStr); * * DateTime time = new DateTime(interval.getStartMillis(), DateTimeZone.UTC); DateTime time2 = new * DateTime(interval.getEndMillis(), DateTimeZone.UTC); * * String newIntervalStr = dateTimeFormatter.withZoneUTC().print(time) + "/" + dateTimeFormatter.withZoneUTC().print(time2); * System.out.println(newIntervalStr); // DateTime dateTime = * dateTimeFormatter.parseDateTime("15-Oct-2013 11:34:26 AM").withZone(DateTimeZone.UTC); * * // System.out.println(dateTime); * * // Interval var = Interval.parse(intervalStr); // String dateStr = formatter.withZone(DateTimeZone.UTC).print(dateTime1); * // * * System.exit(0); **/ printAisStoreNL("Request generation complete."); printAisStoreNL("AIS Data will be saved to " + filePath + fileName); // System.out.println("--------------------------------------------------------------------------------"); // We are resuming, insert a Carriage Return Line Feed if (!forceDownload) { // Load the meta data in readMeta(); // We have processed some packages already if (packageCount != 0) { String str = "\r\n"; outputStream.write(str.getBytes()); printAisStoreLine(); printAisStoreNL("Resume detected - Updating Request"); // System.out.println("From " + intervalStr); // Update intervalStr DateTime time = new DateTime(lastLoadedTimestamp, DateTimeZone.UTC); DateTime time2 = new DateTime(intervalVar.getEndMillis(), DateTimeZone.UTC); intervalStr = dateTimeFormatter.withZoneUTC().print(time) + "/" + dateTimeFormatter.withZoneUTC().print(time2); // System.out.println("To " + intervalStr); printAisStoreLine(); // System.out.println("The last stored timestamp was \n" + lastLoadedTimestamp); // Interval interval2 = DateTimeUtil.toInterval(intervalStr); // System.out.println(interval2.getStartMillis()); } else { writeMetaInit(intervalVar.getStartMillis()); lastLoadedTimestamp = intervalVar.getStartMillis(); } } else { // We are starting a new request, create a new meta init writeMetaInit(intervalVar.getStartMillis()); lastLoadedTimestamp = intervalVar.getStartMillis(); } // System.out.println("Interval Str is " + intervalStr); // System.exit(0); // Initialize counter = new AtomicLong(packageCount); // Do we need to set a new interval start based on the meta data read? DefaultHttpClient httpClient = new DefaultHttpClient(); HttpHost target = new HttpHost("ais2.e-navigation.net", 443, "https"); request = "/aisview/rest/store/query" + request; HttpGet getRequest = new HttpGet(request); // HttpGet getRequest = new // HttpGet("/aisview/rest/store/query?interval=2015-1-1T10:00:00Z/2015-2-1T10:10:00Z&box=65.145,-5.373,34.450,76.893"); // + "&mmsi=219230000" // + "&mmsi=219230000" printAisStoreNL("Executing request to " + target); printAisStoreNL("Request is: " + request); HttpResponse httpResponse = httpClient.execute(target, getRequest); HttpEntity entity = httpResponse.getEntity(); // Check we have an OK from server etc. printAisStoreLine(); boolean terminateFailure = false; StatusLine reply = httpResponse.getStatusLine(); switch (reply.getStatusCode()) { case HttpStatus.SC_OK: printAisStoreNL("Server Accepted Connection, download will begin shortly"); printAisStoreLine(); break; default: printAisStoreNL("An error occured establishing connection to the server. "); printAisStoreNL( "Server returned Status Code " + reply.getStatusCode() + " with " + reply.getReasonPhrase()); terminateFailure = true; break; } if (terminateFailure) { return; } // System.out.println("Got reply " + reply.getReasonPhrase() + " status code " + reply.getStatusCode()); // String httpServerReply = httpResponse.getStatusLine(); // System.out.println(httpResponse.getStatusLine()); // // Header[] headers = httpResponse.getAllHeaders(); // for (int i = 0; i < headers.length; i++) { // System.out.println(headers[i]); // } // Do we use the footer? AisReader aisReader; if (entity != null) { InputStream inputStream = entity.getContent(); aisReader = aisReadWriter(inputStream); aisReader.start(); aisReader.join(); // Write the remainder still stored in buffer, update the final meta data with the finished data writeMetaUpdate(currentTimeStamp, counter.get()); // Write the footer sink.footer(outputStream, counter.get()); // Closer and flush the buffer outputStream.flush(); outputStream.close(); // Close and flush the file stream fileOutputStream.flush(); fileOutputStream.close(); } // print a new line to move on from previous /r printAisStoreNL( "Downloading AIS Data 100% Estimated Time Left: 00:00:00 "); printAisStoreLine(); printAisStoreNL("DOWNLOAD SUCCESS"); printAisStoreLine(); // We know current time long currentTime = System.currentTimeMillis(); // How long have we been running long millis = currentTime - timeStart; String timeLeftStr = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); printAisStoreNL("Total Time " + timeLeftStr); printAisStoreNL("Finished at: " + new Date()); printAisStoreNL("Messages recieved " + counter); // printAisStore("Query took " + timeLeftStr); }
From source file:desmoj.extensions.grafic.util.Plotter.java
/** * configure domainAxis (label, timeZone, locale, tick labels) * of time-series chart//from w w w.j a v a2s.c o m * @param dateAxis */ private void configureDomainAxis(DateAxis dateAxis) { if (this.begin != null) dateAxis.setMinimumDate(this.begin); if (this.end != null) dateAxis.setMaximumDate(this.end); dateAxis.setTimeZone(this.timeZone); Date dateMin = dateAxis.getMinimumDate(); Date dateMax = dateAxis.getMaximumDate(); //DateFormat formatter = new SimpleDateFormat("d.MM.yyyy HH:mm:ss.SSS");; DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, locale); String label = "Time: " + formatter.format(dateMin) + " .. " + formatter.format(dateMax); formatter = new SimpleDateFormat("z"); label += " " + formatter.format(dateMax); dateAxis.setLabel(label); TimeInstant max = new TimeInstant(dateMax); TimeInstant min = new TimeInstant(dateMin); TimeSpan diff = TimeOperations.diff(max, min); if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.DAYS))) formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); else if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.HOURS))) formatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale); else if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.MINUTES))) formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale); else formatter = new SimpleDateFormat("HH:mm:ss.SSS"); dateAxis.setDateFormatOverride(formatter); dateAxis.setVerticalTickLabels(true); }
From source file:org.carbondata.processing.store.writer.AbstractFactDataWriter.java
/** * Method will be used to close the open file channel * * @throws CarbonDataWriterException//from w w w .ja va2 s . c o m */ public void closeWriter() { if (!this.isNodeHolderRequired) { CarbonUtil.closeStreams(this.fileChannel); // close channel } else { this.executorService.shutdown(); try { this.executorService.awaitTermination(2, TimeUnit.HOURS); } catch (InterruptedException ex) { LOGGER.error(ex); } CarbonUtil.closeStreams(this.fileChannel); this.nodeHolderList = null; } File origFile = new File(this.fileName.substring(0, this.fileName.lastIndexOf('.'))); File curFile = new File(this.fileName); if (!curFile.renameTo(origFile)) { LOGGER.info("Problem while renaming the file"); } if (origFile.length() < 1) { if (!origFile.delete()) { LOGGER.info("Problem while deleting the empty fact file"); } } }
From source file:eu.tango.energymodeller.energypredictor.AbstractEnergyPredictor.java
/** * This provides a prediction of how much energy is to be used by a VM, over * the next hour.// w w w . ja va 2 s .c om * * @param vm The vm to be deployed * @param virtualMachines The virtual machines giving a workload on the host * machine * @param host The host that the VMs will be running on * @return The prediction of the energy to be used. */ @Override public EnergyUsagePrediction getVMPredictedEnergy(VM vm, Collection<VM> virtualMachines, Host host) { TimePeriod duration = new TimePeriod(new GregorianCalendar(), TimeUnit.HOURS.toSeconds(1)); return getVMPredictedEnergy(vm, virtualMachines, host, duration); }
From source file:com.jivesoftware.os.upena.deployable.UpenaEndpoints.java
public static String humanReadableUptime(long millis) { if (millis < 0) { return String.valueOf(millis); }//w w w. j a va 2 s . c o m long hours = TimeUnit.MILLISECONDS.toHours(millis); millis -= TimeUnit.HOURS.toMillis(hours); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); millis -= TimeUnit.MINUTES.toMillis(minutes); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); millis -= TimeUnit.SECONDS.toMillis(seconds); StringBuilder sb = new StringBuilder(64); if (hours < 10) { sb.append('0'); } sb.append(hours); sb.append(":"); if (minutes < 10) { sb.append('0'); } sb.append(minutes); sb.append(":"); if (seconds < 10) { sb.append('0'); } sb.append(seconds); return (sb.toString()); }
From source file:org.wso2.carbon.cloud.gateway.transport.CGTransportSender.java
private static long getDurationAsMillisecond(TimeUnit timeUnit, long duration) { if (timeUnit == TimeUnit.MILLISECONDS) { return TimeUnit.MILLISECONDS.toMillis(duration); } else if (timeUnit == TimeUnit.SECONDS) { return TimeUnit.SECONDS.toMillis(duration); } else if (timeUnit == TimeUnit.MINUTES) { return TimeUnit.MINUTES.toMillis(duration); } else if (timeUnit == TimeUnit.HOURS) { return TimeUnit.HOURS.toMillis(duration); } else if (timeUnit == TimeUnit.DAYS) { return TimeUnit.DAYS.toMillis(duration); } else {/* ww w .j a v a 2 s.co m*/ log.warn("TimeUnit type '" + timeUnit + "' is not supported. Default TimeUnit will be " + "assumed"); return TimeUnit.DAYS.toMillis(duration); } }
From source file:org.dcache.util.histograms.HistogramModelTest.java
private double getHoursInThePastFromNow(int hours) { Calendar calendar = Calendar.getInstance(); long diff = TimeUnit.HOURS.toMillis(hours); calendar.setTimeInMillis(System.currentTimeMillis() - diff); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return (double) calendar.getTimeInMillis(); }
From source file:cz.maresmar.sfm.view.MainActivity.java
@Override protected void onStart() { super.onStart(); // Update if user opens app without lasted data long lastUpdate = mPrefs.getLong(SettingsContract.LAST_DONE_SYNC, SettingsContract.LAST_DONE_SYNC_DEFAULT); long syncFreq = DAYS.toMillis(Integer.parseInt( mPrefs.getString(SettingsContract.SYNC_FREQUENCY, SettingsContract.SYNC_FREQUENCY_DEFAULT))); if (mPrefs.getBoolean(SettingsContract.SYNC_WHEN_APP_OPENS, SettingsContract.SYNC_WHEN_APP_OPENS_DEFAULT) && ((lastUpdate + TimeUnit.HOURS.toMillis(12)) < System.currentTimeMillis())) { SyncHandler.startFullSync(this); }/*from w w w . ja v a2s. co m*/ }
From source file:eu.tango.energymodeller.energypredictor.AbstractEnergyPredictor.java
/** * This provides a prediction of how much energy is to be used by a host in * the next hour.//from w ww . j av a 2s .c om * * @param host The host to get the energy prediction for * @param workloadSource The virtual machines or apps providing a workload on the host * machine * @return The prediction of the energy to be used. */ @Override public EnergyUsagePrediction getHostPredictedEnergy(Host host, Collection<WorkloadSource> workloadSource) { TimePeriod duration = new TimePeriod(new GregorianCalendar(), 1, TimeUnit.HOURS); return getHostPredictedEnergy(host, workloadSource, duration); }