List of usage examples for org.joda.time DateTime getMillis
public long getMillis()
From source file:com.metamx.druid.realtime.firehose.WikipediaIrcDecoder.java
License:Open Source License
@Override public InputRow decodeMessage(final DateTime timestamp, String channel, String msg) { final Map<String, String> dimensions = Maps.newHashMap(); final Map<String, Float> metrics = Maps.newHashMap(); Matcher m = pattern.matcher(msg); if (!m.matches()) { throw new IllegalArgumentException("Invalid input format"); }//from www . ja v a 2s . c om Matcher shortname = shortnamePattern.matcher(channel); if (shortname.matches()) { dimensions.put("language", shortname.group(1)); } String page = m.group(1); String pageUrl = page.replaceAll("\\s", "_"); dimensions.put("page", pageUrl); String user = m.group(4); Matcher ipMatch = ipPattern.matcher(user); boolean anonymous = ipMatch.matches(); if (anonymous) { try { final InetAddress ip = InetAddress.getByName(ipMatch.group()); final Omni lookup = geoLookup.omni(ip); dimensions.put("continent", lookup.getContinent().getName()); dimensions.put("country", lookup.getCountry().getName()); dimensions.put("region", lookup.getMostSpecificSubdivision().getName()); dimensions.put("city", lookup.getCity().getName()); } catch (UnknownHostException e) { log.error(e, "invalid ip [%s]", ipMatch.group()); } catch (IOException e) { log.error(e, "error looking up geo ip"); } catch (GeoIp2Exception e) { log.error(e, "error looking up geo ip"); } } dimensions.put("user", user); final String flags = m.group(2); dimensions.put("unpatrolled", Boolean.toString(flags.contains("!"))); dimensions.put("newPage", Boolean.toString(flags.contains("N"))); dimensions.put("robot", Boolean.toString(flags.contains("B"))); dimensions.put("anonymous", Boolean.toString(anonymous)); String[] parts = page.split(":"); if (parts.length > 1 && !parts[1].startsWith(" ")) { Map<String, String> channelNamespaces = namespaces.get(channel); if (channelNamespaces != null && channelNamespaces.containsKey(parts[0])) { dimensions.put("namespace", channelNamespaces.get(parts[0])); } else { dimensions.put("namespace", "wikipedia"); } } else { dimensions.put("namespace", "article"); } float delta = m.group(6) != null ? Float.parseFloat(m.group(6)) : 0; metrics.put("delta", delta); metrics.put("added", Math.max(delta, 0)); metrics.put("deleted", Math.min(delta, 0)); return new InputRow() { @Override public List<String> getDimensions() { return dimensionList; } @Override public long getTimestampFromEpoch() { return timestamp.getMillis(); } @Override public List<String> getDimension(String dimension) { final String value = dimensions.get(dimension); if (value != null) { return ImmutableList.of(value); } else { return ImmutableList.of(); } } @Override public float getFloatMetric(String metric) { return metrics.get(metric); } @Override public String toString() { return "WikipediaRow{" + "timestamp=" + timestamp + ", dimensions=" + dimensions + ", metrics=" + metrics + '}'; } }; }
From source file:com.metinkale.prayerapp.vakit.fragments.MainFragment.java
License:Apache License
@Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.notification: Fragment frag = getActivity().getSupportFragmentManager().findFragmentByTag("notPrefs"); if (frag == null) { ((Main) getActivity()).setFooterText("", false); getActivity().getSupportFragmentManager().beginTransaction() .add(R.id.fragContainer, NotificationPrefs.create(mTimes), "notPrefs") .commitAllowingStateLoss(); } else {/*from ww w.j a va 2s. com*/ ((Main) getActivity()).setFooterText(getString(R.string.monthly), true); getActivity().getSupportFragmentManager().beginTransaction().remove(frag).commitAllowingStateLoss(); } AppRatingDialog.addToOpenedMenus("notPrefs"); break; case R.id.export: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.export).setItems(new CharSequence[] { "CSV", "PDF" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, final int which) { long minDate = 0; long maxDate = Long.MAX_VALUE; if (mTimes instanceof WebTimes) { minDate = ((WebTimes) mTimes).getFirstSyncedDay().toDateTimeAtCurrentTime() .getMillis(); maxDate = ((WebTimes) mTimes).getLastSyncedDay().toDateTimeAtCurrentTime() .getMillis(); } final LocalDate ld = LocalDate.now(); final long finalMaxDate = maxDate; DatePickerDialog dlg = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int y, int m, int d) { final LocalDate from = new LocalDate(y, m + 1, d); DatePickerDialog dlg1 = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int y1, int m1, int d1) { final LocalDate to = new LocalDate(y1, m1 + 1, d1); try { export(which, from, to); } catch (IOException e) { e.printStackTrace(); Crashlytics.logException(e); Toast.makeText(getActivity(), R.string.error, Toast.LENGTH_SHORT).show(); } } }, ld.getYear(), ld.getMonthOfYear() - 1, ld.getDayOfMonth()); DateTime startDate = DateTime.now().withDate(y, m + 1, d); long start = startDate.getMillis(); if (which == 1) dlg1.getDatePicker().setMaxDate( Math.min(finalMaxDate, startDate.plusDays(31).getMillis())); else dlg1.getDatePicker().setMaxDate(finalMaxDate); dlg1.getDatePicker().setMinDate( Math.min(start, dlg1.getDatePicker().getMaxDate()) - 1); dlg1.setTitle(R.string.to); dlg1.show(); } }, ld.getYear(), ld.getMonthOfYear() - 1, ld.getDayOfMonth()); dlg.getDatePicker().setMinDate(minDate); dlg.getDatePicker().setMaxDate(maxDate); dlg.setTitle(R.string.from); dlg.show(); } }); builder.show(); break; case R.id.refresh: if (mTimes instanceof WebTimes) { ((WebTimes) mTimes).syncAsync(); } break; case R.id.share: String txt = getString(R.string.shareTimes, mTimes.getName()) + ":"; LocalDate date = LocalDate.now(); String[] times = { mTimes.getTime(date, 0), mTimes.getTime(date, 1), mTimes.getTime(date, 2), mTimes.getTime(date, 3), mTimes.getTime(date, 4), mTimes.getTime(date, 5) }; for (int i = 0; i < times.length; i++) { txt += "\n " + Vakit.getByIndex(i).getString() + ": " + times[i]; } Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name)); sharingIntent.putExtra(Intent.EXTRA_TEXT, txt); startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share))); } return super.onOptionsItemSelected(item); }
From source file:com.metinkale.prayerapp.vakit.times.Times.java
License:Apache License
@NonNull private Collection<Alarm> getAlarms() { Collection<Alarm> alarms = new ArrayList<>(); LocalDate cal = LocalDate.now(); for (int ii = 0; ii <= 1/* next day */; ii++) { for (Vakit v : Vakit.values()) { if (isNotificationActive(v)) { if (v != Vakit.SABAH) { int vakit = v.ordinal(); if (vakit != 0) { vakit--;//from w ww. jav a 2 s. co m } long mills = getTimeCal(cal, vakit).toDateTime().getMillis(); if (System.currentTimeMillis() < mills) { Alarm a = new Alarm(); a.city = getID(); a.early = false; a.cuma = false; a.time = mills; a.vakit = v; a.dayOffset = ii; alarms.add(a); } } else { long mills; if (isAfterImsak()) { mills = getTimeCal(cal, 0).toDateTime().getMillis() + getSabahTime() * 60 * 1000; } else { mills = getTimeCal(cal, 1).toDateTime().getMillis() - getSabahTime() * 60 * 1000; } if (System.currentTimeMillis() < mills) { Alarm a = new Alarm(); a.city = getID(); a.cuma = false; a.early = false; a.time = mills; a.vakit = v; a.dayOffset = ii; alarms.add(a); } } } if (isEarlyNotificationActive(v)) { if (v != Vakit.SABAH) { int vakit = v.ordinal(); if (vakit != 0) { vakit--; } int early = getEarlyTime(v); long mills = getTimeCal(cal, vakit).toDateTime().getMillis() - early * 60 * 1000; if (System.currentTimeMillis() < mills) { Alarm a = new Alarm(); a.city = getID(); a.early = true; a.cuma = false; a.time = mills; a.vakit = v; a.dayOffset = ii; alarms.add(a); } } } } cal = cal.plusDays(1); } if (isCumaActive()) { int early = getCumaTime(); DateTime c = DateTime.now().withDayOfWeek(DateTimeConstants.FRIDAY); if ((c.getMillis() + 1000) < System.currentTimeMillis()) { c = c.plusWeeks(1); } long mills = getTimeCal(c.toLocalDate(), 2).toDateTime().getMillis(); mills -= early * 60 * 1000; if (System.currentTimeMillis() < mills) { Alarm a = new Alarm(); a.city = getID(); a.cuma = true; a.early = false; a.time = mills; a.vakit = Vakit.OGLE; a.dayOffset = 0; alarms.add(a); } } return alarms; }
From source file:com.microsoft.azure.management.graphrbac.implementation.CertificateCredentialImpl.java
License:Open Source License
@Override public CertificateCredentialImpl<T> withStartDate(DateTime startDate) { DateTime original = startDate(); inner().withStartDate(startDate);/* ww w. j av a 2 s.co m*/ // Adjust end time withDuration(Duration.millis(endDate().getMillis() - original.getMillis())); return this; }
From source file:com.microsoft.azure.management.graphrbac.implementation.PasswordCredentialImpl.java
License:Open Source License
@Override public PasswordCredentialImpl<T> withStartDate(DateTime startDate) { DateTime original = startDate(); inner().withStartDate(startDate);/*from ww w .j av a 2s. co m*/ // Adjust end time withDuration(Duration.millis(endDate().getMillis() - original.getMillis())); return this; }
From source file:com.microsoft.azure.vmagent.AzureVMAgentCleanUpTask.java
License:Apache License
public void cleanDeployments(final long successTimeoutInMinutes, final long failTimeoutInMinutes) { LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Cleaning deployments"); // Walk the queue, popping and pushing until we reach an item that we've already // dealt with or the queue is empty. DeploymentInfo firstBackInQueue = null; while (!deploymentsToClean.isEmpty() && firstBackInQueue != deploymentsToClean.peek()) { DeploymentInfo info = deploymentsToClean.remove(); LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Checking deployment {0}", info.getDeploymentName()); AzureVMCloud cloud = getCloud(info.getCloudName()); if (cloud == null) { // Cloud could have been deleted, skip continue; }// w w w . j av a2 s. c om try { final Azure azureClient = TokenCache.getInstance(cloud.getServicePrincipal()).getAzureClient(); // This will throw if the deployment can't be found. This could happen in a couple instances // 1) The deployment has already been deleted // 2) The deployment doesn't exist yet (race between creating the deployment and it // being accepted by Azure. // To avoid this, we implement a retry. If we hit an exception, we will decrement the number // of retries. If we hit 0, we remove the deployment from our list. Deployment deployment = azureClient.deployments().getByGroup(info.getResourceGroupName(), info.getDeploymentName()); if (deployment == null) { LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Deployment not found, skipping"); continue; } DateTime deploymentTime = deployment.timestamp(); LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Deployment created on {0}", deploymentTime.toDate()); long deploymentTimeInMillis = deploymentTime.getMillis(); // Compare to now Calendar nowTime = Calendar.getInstance(deploymentTime.getZone().toTimeZone()); long nowTimeInMillis = nowTime.getTimeInMillis(); long diffTime = nowTimeInMillis - deploymentTimeInMillis; long diffTimeInMinutes = (diffTime / 1000) / 60; String state = deployment.provisioningState(); if (!state.equalsIgnoreCase("succeeded") && diffTimeInMinutes > failTimeoutInMinutes) { LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Failed deployment older than {0} minutes, deleting", failTimeoutInMinutes); // Delete the deployment azureClient.deployments().deleteByGroup(info.getResourceGroupName(), info.getDeploymentName()); } else if (state.equalsIgnoreCase("succeeded") && diffTimeInMinutes > successTimeoutInMinutes) { LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Succesfull deployment older than {0} minutes, deleting", successTimeoutInMinutes); // Delete the deployment azureClient.deployments().deleteByGroup(info.getResourceGroupName(), info.getDeploymentName()); } else { LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Deployment newer than timeout, keeping"); if (firstBackInQueue == null) { firstBackInQueue = info; } // Put it back deploymentsToClean.add(info); } } catch (Exception e) { LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Failed to get/delete deployment: {0}", e.toString()); // Check the number of attempts remaining. If greater than 0, decrement // and add back into the queue. if (info.hasAttemptsRemaining()) { info.decrementAttemptsRemaining(); if (firstBackInQueue == null) { firstBackInQueue = info; } // Put it back in the queue for another attempt deploymentsToClean.add(info); } } } LOGGER.log(Level.INFO, "AzureVMAgentCleanUpTask: cleanDeployments: Done cleaning deployments"); }
From source file:com.microsoft.azurebatch.jenkins.azurebatch.AzureBatchHelper.java
License:Open Source License
/** * Extend pool job's timeout//w ww . j av a 2 s . c o m * @param extraTimeoutInMin Extra timeout in minutes * @throws BatchErrorException * @throws IOException */ private void extendPoolJobTimeout(int extraTimeoutInMin) throws BatchErrorException, IOException { CloudJob job = client.jobOperations().getJob(poolJobId); DateTime jobCreatedTime = job.creationTime(); DateTime now = new DateTime(DateTimeZone.UTC); // Add some safe buffer timeout to the new job timeout final int safeMoreTimeoutInMin = 15; int newJobTimeoutInMin = (int) ((now.getMillis() - jobCreatedTime.getMillis()) / 1000 / 60) + extraTimeoutInMin + safeMoreTimeoutInMin; JobConstraints jobConstraints = new JobConstraints(); jobConstraints.withMaxWallClockTime(Period.minutes(newJobTimeoutInMin)); JobPatchParameter jpp = new JobPatchParameter(); jpp.withConstraints(jobConstraints); client.jobOperations().patchJob(poolJobId, jpp); Logger.log(listener, "Set poolJob %s new timeout to %d minutes.", poolJobId, newJobTimeoutInMin); }
From source file:com.microsoft.rest.serializer.DateTimeSerializer.java
License:Open Source License
@Override public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException { if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) { jgen.writeNumber(value.getMillis()); } else {//from w ww . j a v a 2 s. c o m value = value.withZone(DateTimeZone.UTC); jgen.writeString(value.toString(ISODateTimeFormat.dateTime())); } }
From source file:com.mobiaware.auction.event.AuctionResource.java
License:Apache License
@GET @Path("/{auction}/start") public Auction startAuction(@PathParam("auction") final int auctionUid) { Auction auction = _dataService.getAuction(auctionUid); if (auction == null) { throw new NotFoundException(); }// www . j av a 2 s. c om DateTime today = new DateTime(); DateTime tomorrow = today.plusDays(30); // +30 days auction = auction.toBuilder().setStartDate(today.getMillis()).setEndDate(tomorrow.getMillis()).build(); int uid = _dataService.editAuction(auction); if (uid < 0) { throw new InternalServerErrorException(); } return auction; }
From source file:com.mobiaware.auction.event.AuctionResource.java
License:Apache License
@GET @Path("/{auction}/stop") public Auction stopAuction(@PathParam("auction") final int auctionUid) { Auction auction = _dataService.getAuction(auctionUid); if (auction == null) { throw new NotFoundException(); }//from w w w. ja va2s . co m DateTime today = new DateTime(); DateTime yesterday = today.minusDays(1); // -1 days auction = auction.toBuilder().setStartDate(today.getMillis()).setEndDate(yesterday.getMillis()).build(); int uid = _dataService.editAuction(auction); if (uid < 0) { throw new InternalServerErrorException(); } return auction; }