/**
  * test DST start with offset not fitting interval, e.g. Asia/Kathmandu adding 15min on
  * 1986-01-01T00:00:00 the interval from 1986-01-01T00:15:00+05:45 to 1986-01-01T00:20:00+05:45 to
  * only be 5min long
  */
 public void testTimeInterval_Kathmandu_DST_Start() {
   long interval = TimeUnit.MINUTES.toMillis(20);
   DateTimeZone tz = DateTimeZone.forID("Asia/Kathmandu");
   Rounding rounding = new TimeIntervalRounding(interval, tz);
   assertThat(
       rounding.round(time("1985-12-31T23:55:00+05:30")),
       isDate(time("1985-12-31T23:40:00+05:30"), tz));
   assertThat(
       rounding.round(time("1986-01-01T00:16:00+05:45")),
       isDate(time("1986-01-01T00:15:00+05:45"), tz));
   assertThat(
       time("1986-01-01T00:15:00+05:45") - time("1985-12-31T23:40:00+05:30"),
       equalTo(TimeUnit.MINUTES.toMillis(20)));
   assertThat(
       rounding.round(time("1986-01-01T00:26:00+05:45")),
       isDate(time("1986-01-01T00:20:00+05:45"), tz));
   assertThat(
       time("1986-01-01T00:20:00+05:45") - time("1986-01-01T00:15:00+05:45"),
       equalTo(TimeUnit.MINUTES.toMillis(5)));
   assertThat(
       rounding.round(time("1986-01-01T00:46:00+05:45")),
       isDate(time("1986-01-01T00:40:00+05:45"), tz));
   assertThat(
       time("1986-01-01T00:40:00+05:45") - time("1986-01-01T00:20:00+05:45"),
       equalTo(TimeUnit.MINUTES.toMillis(20)));
 }
        public void run() {
          if (isMediaPlayerBound) {
            int totalDuration = getDuration();
            int currentProgression = getCurrentPosition();

            seekbar.setMax(totalDuration);
            seekbar.setProgress(currentProgression);

            String timeElapsed =
                String.format(
                    "%d:%d",
                    TimeUnit.MILLISECONDS.toMinutes(currentProgression),
                    TimeUnit.MILLISECONDS.toSeconds(currentProgression)
                        - TimeUnit.MINUTES.toSeconds(
                            TimeUnit.MILLISECONDS.toMinutes(currentProgression)));

            String totalTimeFormatted =
                String.format(
                    "%d:%d",
                    TimeUnit.MILLISECONDS.toMinutes(totalDuration),
                    TimeUnit.MILLISECONDS.toSeconds(totalDuration)
                        - TimeUnit.MINUTES.toSeconds(
                            TimeUnit.MILLISECONDS.toMinutes(totalDuration)));

            tvTotalTime.setText(totalTimeFormatted);
            tvCurrentTime.setText(timeElapsed);

            updateMediaPlayerViews();
          }

          // repeat yourself again in 100 miliseconds
          seekHandler.postDelayed(this, 100);
        }
  private String getAvgTimePerTick(SortedMap<Long, Record> records) {
    long sum = 0;
    for (Map.Entry<Long, Record> en : records.entrySet()) {
      sum += en.getValue().getLastCallDiff();
    }

    long globalavg = sum / records.size();

    sum = 0;
    Set<Map.Entry<Long, Record>> subset =
        records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(15)).entrySet();

    for (Map.Entry<Long, Record> en : subset) {
      sum += en.getValue().getLastCallDiff();
    }

    long min15avg = sum / subset.size();

    sum = 0;
    subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(10)).entrySet();
    for (Map.Entry<Long, Record> en : subset) {
      sum += en.getValue().getLastCallDiff();
    }

    long min10avg = sum / subset.size();

    sum = 0;
    subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)).entrySet();

    for (Map.Entry<Long, Record> en : subset) {
      sum += en.getValue().getLastCallDiff();
    }

    long min5avg = sum / subset.size();

    sum = 0;
    subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1)).entrySet();
    for (Map.Entry<Long, Record> en : subset) {
      sum += en.getValue().getLastCallDiff();
    }

    long min1avg = sum / subset.size();

    return globalavg
        + " "
        + ChatColor.GRAY
        + min15avg
        + " "
        + ChatColor.YELLOW
        + min10avg
        + " "
        + ChatColor.GOLD
        + min5avg
        + " "
        + ChatColor.GREEN
        + min1avg;
  }
  // Default config
  static {
    config.setMaxTotal(100);

    config.setMaxTotalPerKey(100);
    config.setMaxIdlePerKey(100);
    config.setMinIdlePerKey(100);

    config.setTestOnBorrow(true);
    config.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(5));
    config.setSoftMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(5));
    config.setJmxEnabled(false);
  }
 private static String formatInterval(final long l) {
   final long hr = TimeUnit.MILLISECONDS.toHours(l);
   final long min = TimeUnit.MILLISECONDS.toMinutes(l - TimeUnit.HOURS.toMillis(hr));
   final long sec =
       TimeUnit.MILLISECONDS.toSeconds(
           l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min));
   final long ms =
       TimeUnit.MILLISECONDS.toMillis(
           l
               - TimeUnit.HOURS.toMillis(hr)
               - TimeUnit.MINUTES.toMillis(min)
               - TimeUnit.SECONDS.toMillis(sec));
   return String.format("%02dh:%02dm:%02d.%03ds", hr, min, sec, ms);
 }
 /*
  * Returns TTL value of ElasticSearch index in milliseconds when TTL
  * specifier is "ms" / "s" / "m" / "h" / "d" / "w". In case of unknown
  * specifier TTL is not set. When specifier is not provided it defaults to
  * days in milliseconds where the number of days is parsed integer from TTL
  * string provided by user. <p> Elasticsearch supports ttl values being
  * provided in the format: 1d / 1w / 1ms / 1s / 1h / 1m specify a time unit
  * like d (days), m (minutes), h (hours), ms (milliseconds) or w (weeks),
  * milliseconds is used as default unit.
  * http://www.elasticsearch.org/guide/reference/mapping/ttl-field/.
  *
  * @param ttl TTL value provided by user in flume configuration file for the
  * sink
  *
  * @return the ttl value in milliseconds
  */
 private long parseTTL(String ttl) {
   matcher = matcher.reset(ttl);
   while (matcher.find()) {
     if (matcher.group(2).equals("ms")) {
       return Long.parseLong(matcher.group(1));
     } else if (matcher.group(2).equals("s")) {
       return TimeUnit.SECONDS.toMillis(Integer.parseInt(matcher.group(1)));
     } else if (matcher.group(2).equals("m")) {
       return TimeUnit.MINUTES.toMillis(Integer.parseInt(matcher.group(1)));
     } else if (matcher.group(2).equals("h")) {
       return TimeUnit.HOURS.toMillis(Integer.parseInt(matcher.group(1)));
     } else if (matcher.group(2).equals("d")) {
       return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1)));
     } else if (matcher.group(2).equals("w")) {
       return TimeUnit.DAYS.toMillis(7 * Integer.parseInt(matcher.group(1)));
     } else if (matcher.group(2).equals("")) {
       logger.info("TTL qualifier is empty. Defaulting to day qualifier.");
       return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1)));
     } else {
       logger.debug("Unknown TTL qualifier provided. Setting TTL to 0.");
       return 0;
     }
   }
   logger.info("TTL not provided. Skipping the TTL config by returning 0.");
   return 0;
 }
 @Provides
 @Singleton
 @Named(TIMEOUT_NAME)
 long getTimeoutMillis(@GerritServerConfig final Config cfg) {
   return ConfigUtil.getTimeUnit(
       cfg, "receive", null, "timeout", TimeUnit.MINUTES.toMillis(2), TimeUnit.MILLISECONDS);
 }
Пример #8
0
  private void updateRuntime(int currentTime) {

    if (mRunTime == null) {
      // this view can be null if the user
      // does not want to use it. Don't throw
      // an exception.
      return;
    }

    if (currentTime < 0) {
      throw new IllegalArgumentException(ERROR_PLAYTIME_CURRENT_NEGATIVE);
    }

    StringBuilder playbackStr = new StringBuilder();

    // set the current time
    // its ok to show 00:00 in the UI
    playbackStr.append(
        String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes((long) currentTime),
            TimeUnit.MILLISECONDS.toSeconds((long) currentTime)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) currentTime))));

    mRunTime.setText(playbackStr);

    // DebugLog.i(currentTime + " / " + totalDuration);
  }
Пример #9
0
  @Deprecated
  private void updatePlaytime(int currentTime) {
    StringBuilder playbackStr = new StringBuilder();

    long totalDuration = 0;

    if (getMediaPlayer() != null) {
      try {
        totalDuration = getMediaPlayer().getDuration();
      } catch (Exception e) {
        app2 mapp = (app2) context.getApplicationContext();
        mapp.getInstance().trackException(e);
        e.printStackTrace();
      }
    }

    // set total time as the audio is being played
    if (totalDuration != 0) {
      playbackStr.append(
          String.format(
              "%02d:%02d",
              TimeUnit.MILLISECONDS.toMinutes((long) totalDuration),
              TimeUnit.MILLISECONDS.toSeconds((long) totalDuration)
                  - TimeUnit.MINUTES.toSeconds(
                      TimeUnit.MILLISECONDS.toMinutes((long) totalDuration))));
    } else {
      Log.w(TAG, "Something strage this audio track duration in zero");
    }

    mTotalTime.setText(playbackStr);

    // DebugLog.i(currentTime + " / " + totalDuration);
  }
  /**
   * test DST end with interval rounding CET: 25 October 2015, 03:00:00 clocks were turned backward
   * 1 hour to 25 October 2015, 02:00:00 local standard time
   */
  public void testTimeIntervalCET_DST_End() {
    long interval = TimeUnit.MINUTES.toMillis(20);
    DateTimeZone tz = DateTimeZone.forID("CET");
    Rounding rounding = new TimeIntervalRounding(interval, tz);

    assertThat(
        rounding.round(time("2015-10-25T01:55:00+02:00")),
        isDate(time("2015-10-25T01:40:00+02:00"), tz));
    assertThat(
        rounding.round(time("2015-10-25T02:15:00+02:00")),
        isDate(time("2015-10-25T02:00:00+02:00"), tz));
    assertThat(
        rounding.round(time("2015-10-25T02:35:00+02:00")),
        isDate(time("2015-10-25T02:20:00+02:00"), tz));
    assertThat(
        rounding.round(time("2015-10-25T02:55:00+02:00")),
        isDate(time("2015-10-25T02:40:00+02:00"), tz));
    // after DST shift
    assertThat(
        rounding.round(time("2015-10-25T02:15:00+01:00")),
        isDate(time("2015-10-25T02:00:00+01:00"), tz));
    assertThat(
        rounding.round(time("2015-10-25T02:35:00+01:00")),
        isDate(time("2015-10-25T02:20:00+01:00"), tz));
    assertThat(
        rounding.round(time("2015-10-25T02:55:00+01:00")),
        isDate(time("2015-10-25T02:40:00+01:00"), tz));
    assertThat(
        rounding.round(time("2015-10-25T03:15:00+01:00")),
        isDate(time("2015-10-25T03:00:00+01:00"), tz));
  }
Пример #11
0
  @Override
  public List<Bulletin> findBulletinsForGroupBySource(
      final String groupId, final int maxPerComponent) {
    final long fiveMinutesAgo = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5);

    final ConcurrentMap<String, RingBuffer<Bulletin>> componentMap = bulletinStoreMap.get(groupId);
    if (componentMap == null) {
      return Collections.<Bulletin>emptyList();
    }

    final List<Bulletin> allComponentBulletins = new ArrayList<>();
    for (final RingBuffer<Bulletin> ringBuffer : componentMap.values()) {
      allComponentBulletins.addAll(
          ringBuffer.getSelectedElements(
              new Filter<Bulletin>() {
                @Override
                public boolean select(final Bulletin bulletin) {
                  return bulletin.getTimestamp().getTime() >= fiveMinutesAgo;
                }
              },
              maxPerComponent));
    }

    return allComponentBulletins;
  }
Пример #12
0
  private <T extends Source> T waitForSource(String id, Class<T> type)
      throws InterruptedException, InvalidSyntaxException {
    T source = null;
    long timeoutLimit = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5);
    boolean available = false;

    while (!available) {
      if (source == null) {
        source =
            serviceManager
                .getServiceReferences(type, null)
                .stream()
                .map(serviceManager::getService)
                .filter(src -> id.equals(src.getId()))
                .findFirst()
                .orElse(null);
      }
      if (source != null) {
        available = source.isAvailable();
      }
      if (!available) {
        if (System.currentTimeMillis() > timeoutLimit) {
          fail("Source (" + id + ") was not created in a timely manner.");
        }
        Thread.sleep(100);
      }
    }
    LOGGER.info("Source {} is available.", id);
    return source;
  }
Пример #13
0
/** Created by RETRO on 23/08/2015. */
public class LocationManager {

  private static final int NUM_UPDATES_INTERVAL = 1;
  private static final long INTERVAL = TimeUnit.MINUTES.toMillis(5);
  private static final int LOCATION_TIMEOUT = 2;

  public static Observable<Location> checkLocation(Context mContext) {
    ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(mContext);

    LocationRequest locationRequest =
        LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setNumUpdates(NUM_UPDATES_INTERVAL)
            .setInterval(INTERVAL);

    Observable<Location> locationObservable =
        locationProvider
            .getLastKnownLocation()
            .timeout(LOCATION_TIMEOUT, TimeUnit.SECONDS, Observable.just((Location) null))
            .concatWith(locationProvider.getUpdatedLocation(locationRequest))
            .distinctUntilChanged()
            .observeOn(AndroidSchedulers.mainThread());

    return locationObservable;
  }
}
        @Override
        public void onReceive(Context context, Intent intent) {
          // Get Bundles
          Bundle extras = intent.getExtras();
          // Unwrap bundle object
          runTemp = extras.getDouble(TempService.TEMPKEY); // Hopfully get the temp.
          double runRoc = extras.getDouble(TempService.ROCKEY); // Hopfully get the RoC.
          long currentTime = extras.getLong(TempService.TIMEKEY); // Hopfully get the time.
          int currentPower = extras.getInt(TempService.POWERKEY); // Hopfully get the Power.
          double wantedRoC = extras.getDouble(TempService.WROCKEY); // Desired RoC

          if (currentPower != tempBar.getProgress()) {
            tempBar.setProgress(currentPower);
            sendMessage("A" + String.format("%04d", currentPower));
          }

          if (runTemp > maxTempValue) {
            maxTempValue = runTemp;
            dispMaxT.setText("Max Temp: " + String.format("%5.2f", runTemp));
          }
          liveGraphXYSeries.add(currentTime / 10000, runTemp);
          mChartView.repaint();

          dispRunTime.setText(
              "Time: "
                  + String.format(
                      "%d:%02d",
                      TimeUnit.MILLISECONDS.toMinutes(currentTime),
                      TimeUnit.MILLISECONDS.toSeconds(currentTime)
                          - TimeUnit.MINUTES.toSeconds(
                              TimeUnit.MILLISECONDS.toMinutes(currentTime))));
          dispTemp.setText("Temp: " + String.format("%5.2f", runTemp));
          dispRoc.setText("Roc: " + String.format("%5.2f", runRoc) + "/min");
          dispWRoC.setText("Target RoC: " + String.format("%5.2f", wantedRoC));
        }
Пример #15
0
  @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  @Override
  public void onTick(long millisUntilFinished) {

    // Change milliseconds into MM:SS
    String timeLeft =
        String.format(
            "%d : %02d",
            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

    // Display the countdown
    countdown.setText(timeLeft);

    // Check to see if it's time to change the sprite
    if (!sprite.omelette) {
      if (((millisUntilFinished <= 0.8 * duration) && sprite.eggStatus == 1)
          || // 80% done
          ((millisUntilFinished <= 0.6 * duration) && sprite.eggStatus == 2)
          || // 60% done
          ((millisUntilFinished <= 0.4 * duration) && sprite.eggStatus == 3)
          || // 40% done
          ((millisUntilFinished <= 0.2 * duration) && sprite.eggStatus == 4)) { // 20% done

        sprite.nextStatus();
      }
    }
  }
 /**
  * Format the time the current crawl run has taken into a more readable format.
  *
  * @param timeCrawlCalc the time to display
  * @return the formatted time in X min, X sec layout.
  */
 private String formatRunningTime(long timeCrawlCalc) {
   return String.format(
       "%d min, %d sec",
       TimeUnit.MILLISECONDS.toMinutes(timeCrawlCalc),
       TimeUnit.MILLISECONDS.toSeconds(timeCrawlCalc)
           - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeCrawlCalc)));
 }
Пример #17
0
  @Test
  public void executeTests() throws IOException {
    String testBase = server.whereIs("/selenium-server/tests");
    Path outputFile =
        Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value())
            .resolve("core-test-suite" + browser.replace('*', '-') + ".html");
    if (Files.exists(outputFile)) {
      Files.delete(outputFile);
    }
    Files.createDirectories(outputFile.getParent());

    String result =
        new HTMLLauncher()
            .runHTMLSuite(
                browser,
                // We need to do this because the path relativizing code in java.net.URL is
                // clearly having a bad day. "/selenium-server/tests" appended to "../tests/"
                // ends up as "/tests" rather than "/selenium-server/tests" as you'd expect.
                testBase + "/TestSuite.html",
                testBase + "/TestSuite.html",
                outputFile.toFile(),
                TimeUnit.MINUTES.toSeconds(5),
                null);

    assertEquals("PASSED", result);
  }
 private void initializeThreads() {
   int startdelay = (int) (SettingUtil.getSettingDouble("start_delay_seconds") * 20);
   int savefrequency = SettingUtil.getSettingInt("save_interval_seconds") * 20;
   if (startdelay <= 0) startdelay = 1;
   if (savefrequency <= 0) savefrequency = 300;
   // data
   getServer()
       .getScheduler()
       .scheduleAsyncRepeatingTask(
           this,
           new Runnable() {
             @Override
             public void run() {
               DataManager.saveAllData();
             }
           },
           startdelay,
           savefrequency);
   getServer()
       .getScheduler()
       .scheduleAsyncRepeatingTask(
           this,
           new AsyncIPMatcherTask(),
           50,
           TimeUnit.MINUTES.toMillis(getConfig().getInt("cache_interval_seconds", 10)));
 }
Пример #19
0
  /*
  Fast but not so readable. From here: http://stackoverflow.com/questions/9027317/how-to-convert-milliseconds-to-hhmmss-format
   */
  public static String msToString(final long millis) {
    long seconds =
        TimeUnit.MILLISECONDS.toSeconds(millis)
            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
    long minutes =
        TimeUnit.MILLISECONDS.toMinutes(millis)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
    long hours = TimeUnit.MILLISECONDS.toHours(millis);

    StringBuilder b = new StringBuilder();

    if (hours > 0) {
      b.append(hours < 10 ? String.valueOf("" + hours) : String.valueOf(hours));
      b.append(":");
    }

    b.append(
        minutes == 0
            ? "00"
            : minutes < 10 ? String.valueOf("0" + minutes) : String.valueOf(minutes));
    b.append(":");
    b.append(
        seconds == 0
            ? "00"
            : seconds < 10 ? String.valueOf("0" + seconds) : String.valueOf(seconds));
    return b.toString();
  }
Пример #20
0
  // DATABASE
  static void DataBaseExample() {

    // send cluster client and name of the bucket
    CouchbaseLogger db = new CouchbaseLogger(CouchbaseCluster.create(), "logger");

    // naming the fields as you like , if you not mention names they wont apper in logs
    db.date("date")
        .method("method")
        .exception("exception")
        .file("file")
        .level("level")
        .line("line")
        .thread("thread")
        .message("message")
        .className("class")
        .setExpire((int) TimeUnit.MINUTES.toSeconds(1));
    // create handler
    Handler dbHandler = new DatabaseHandler(db);

    // add handler
    GlobLoggerPool.getLogger("log1").addHandler(dbHandler);

    // send LOG
    GlobLoggerPool.getLogger("log1")
        .publish(new NullPointerException(), "This is gonna do alot of problems!", "WARNING");
  }
Пример #21
0
/**
 * Formats time-of-day using FIX UTCTimeOnly format (HH:mm:ss or HH:mm:ss.SSS). For example,
 * "23:59:59.999". This class is thread safe.
 */
public final class TimeOfDayParser {

  private static final int MILLIS_PER_HOUR = (int) TimeUnit.HOURS.toMillis(1);
  private static final int MILLIS_PER_MINUTE = (int) TimeUnit.MINUTES.toMillis(1);

  /** @return number of milliseconds since midnight */
  public static int parseTimeOfDay(byte[] buffer, int valueOffset, int valueLength) {
    // HH:mm:ss.SSS
    // 012345678901

    int hours = NumbersParser.parsePositiveInt(buffer, valueOffset + 0, 2);
    int minutes = NumbersParser.parsePositiveInt(buffer, valueOffset + 3, 2);
    int seconds = NumbersParser.parsePositiveInt(buffer, valueOffset + 6, 2);
    int millis = (valueLength > 8) ? NumbersParser.parsePositiveInt(buffer, valueOffset + 9, 3) : 0;

    if (hours >= 24 || minutes >= 60 || seconds >= 60)
      throw new FixParserException("Invalid time of day");
    return hours * MILLIS_PER_HOUR + minutes * MILLIS_PER_MINUTE + seconds * 1000 + millis;
  }

  /** Parses HH:MM:SS into array containing H,M,S elements */
  public static int[] parseTimeOfDay(byte[] buffer) {
    int[] result = new int[3];
    result[0] = NumbersParser.parsePositiveInt(buffer, 0, 2);
    result[1] = NumbersParser.parsePositiveInt(buffer, 3, 2);
    result[2] = NumbersParser.parsePositiveInt(buffer, 6, 2);

    if (result[0] >= 24 || result[1] >= 60 || result[2] >= 60)
      throw new FixParserException("Invalid time of day");
    return result;
  }
}
Пример #22
0
  public SerialMain(CommandLine cmd, MoteList motelist) {
    this.cmd = cmd;
    this.motelist = motelist;

    // get value of time, if not set, use default 15
    time = TimeUnit.MINUTES.toMillis(Integer.parseInt(cmd.getOptionValue("T")));
  }
 @PostConstruct
 private void init() {
   objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
   client = HttpClients.createDefault();
   this.url = telegramUrl + telegramToken + "/sendMessage";
   TimerTask timerTask =
       new TimerTask() {
         @Override
         public void run() {
           SendMessage sendMessage = null;
           try {
             if (!outQueue.isEmpty()) {
               sendMessage = outQueue.take();
               deliverMessage(sendMessage);
             }
           } catch (InterruptedException e) {
             logger.error("error in reading outQueue", e);
           } catch (Exception e) {
             logger.error("error sending message " + sendMessage, e);
           }
         }
       };
   Timer timer = new Timer();
   timer.schedule(timerTask, TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS.toMillis(200));
 }
Пример #24
0
  @Override
  public void elaborate(Configuration config, Results results, long timeTaken) {
    super.elaborate(config, results, timeTaken);
    // saving results
    System.out.println("Saving results...");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
    String dateFormatted = sdf.format(new Date());
    String pathOfFile =
        config.getOutputFolder().getAbsolutePath()
            + File.separator
            + "results-"
            + dateFormatted
            + ".json";
    saveToJson(results, pathOfFile);

    String time =
        String.format(
            "%d h, %d m, %d s",
            TimeUnit.MILLISECONDS.toHours(timeTaken),
            TimeUnit.MILLISECONDS.toMinutes(timeTaken)
                - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeTaken)),
            TimeUnit.MILLISECONDS.toSeconds(timeTaken)
                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeTaken)));
    System.out.println("Time taken: " + time);
  }
Пример #25
0
  /** Entry point for a streaming Fizz Buzz! */
  public static void main(String[] args) throws Exception {
    Topology topology = new Topology();

    // Declare an infinite stream of Long values
    TStream<Long> counting = BeaconStreams.longBeacon(topology);

    // Throttle the rate to allow the output to be seen easier
    counting = counting.throttle(100, TimeUnit.MILLISECONDS);

    // Print the tuples to standard output
    playFizzBuzz(counting).print();

    // At this point the streaming topology (streaming) is
    // declared, but no data is flowing. The topology
    // must be submitted to a StreamsContext to be executed.

    // Since this is an streaming graph with an endless
    // data source it will run for ever
    Future<?> runningTopology = StreamsContextFactory.getEmbedded().submit(topology);

    // Run for one minute before canceling.
    Thread.sleep(TimeUnit.MINUTES.toMillis(1));

    runningTopology.cancel(true);
  }
  /**
   * Creates a new Cluster based on the specified configuration.
   *
   * @param stormConf the storm configuration.
   * @return a new a new {@link Cluster} instance.
   */
  @Override
  protected Cluster make(Map<String, Object> stormConf) {
    CassandraConf cassandraConf = new CassandraConf(stormConf);

    Cluster.Builder cluster =
        Cluster.builder()
            .withoutJMXReporting()
            .withoutMetrics()
            .addContactPoints(cassandraConf.getNodes())
            .withPort(cassandraConf.getPort())
            .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
            .withReconnectionPolicy(
                new ExponentialReconnectionPolicy(100L, TimeUnit.MINUTES.toMillis(1)))
            .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));

    final String username = cassandraConf.getUsername();
    final String password = cassandraConf.getPassword();

    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
      cluster.withAuthProvider(new PlainTextAuthProvider(username, password));
    }

    QueryOptions options =
        new QueryOptions().setConsistencyLevel(cassandraConf.getConsistencyLevel());
    cluster.withQueryOptions(options);

    return cluster.build();
  }
  /**
   * Special test for intervals that don't fit evenly into rounding interval. In this case, when
   * interval crosses DST transition point, rounding in local time can land in a DST gap which
   * results in wrong UTC rounding values.
   */
  public void testIntervalRounding_NotDivisibleInteval() {
    DateTimeZone tz = DateTimeZone.forID("CET");
    long interval = TimeUnit.MINUTES.toMillis(14);
    Rounding rounding = new Rounding.TimeIntervalRounding(interval, tz);

    assertThat(
        rounding.round(time("2016-03-27T01:41:00+01:00")),
        isDate(time("2016-03-27T01:30:00+01:00"), tz));
    assertThat(
        rounding.round(time("2016-03-27T01:51:00+01:00")),
        isDate(time("2016-03-27T01:44:00+01:00"), tz));
    assertThat(
        rounding.round(time("2016-03-27T01:59:00+01:00")),
        isDate(time("2016-03-27T01:58:00+01:00"), tz));
    assertThat(
        rounding.round(time("2016-03-27T03:05:00+02:00")),
        isDate(time("2016-03-27T03:00:00+02:00"), tz));
    assertThat(
        rounding.round(time("2016-03-27T03:12:00+02:00")),
        isDate(time("2016-03-27T03:08:00+02:00"), tz));
    assertThat(
        rounding.round(time("2016-03-27T03:25:00+02:00")),
        isDate(time("2016-03-27T03:22:00+02:00"), tz));
    assertThat(
        rounding.round(time("2016-03-27T03:39:00+02:00")),
        isDate(time("2016-03-27T03:36:00+02:00"), tz));
  }
  private Properties getDefaultProperties() {
    Properties defaultProps = new Properties();

    // testing params, DONT TOUCH !!!
    defaultProps.setProperty("openkad.keyfactory.keysize", "50");
    defaultProps.setProperty("openkad.keyfactory.hashalgo", "SHA-256");
    defaultProps.setProperty("openkad.bucket.kbuckets.maxsize", "16");
    defaultProps.setProperty("openkad.color.nrcolors", "19");
    defaultProps.setProperty("openkad.scheme.name", "openkad.udp");

    // performance params

    // handling incoming messages
    defaultProps.setProperty("openkad.executors.server.nrthreads", "8");
    defaultProps.setProperty("openkad.executors.server.max_pending", "512");
    // handling registered callback
    defaultProps.setProperty("openkad.executors.client.nrthreads", "1");
    defaultProps.setProperty("openkad.executors.client.max_pending", "20");
    // forwarding find node requests
    defaultProps.setProperty("openkad.executors.forward.nrthreads", "2");
    defaultProps.setProperty("openkad.executors.forward.max_pending", "2");
    // executing the long find node operations
    defaultProps.setProperty("openkad.executors.op.nrthreads", "1");
    defaultProps.setProperty("openkad.executors.op.max_pending", "2");
    // sending back pings
    defaultProps.setProperty("openkad.executors.ping.nrthreads", "1");
    defaultProps.setProperty("openkad.executors.ping.max_pending", "16");
    // cache settings
    defaultProps.setProperty("openkad.cache.validtime", TimeUnit.HOURS.toMillis(10) + "");
    defaultProps.setProperty("openkad.cache.size", "100");
    defaultProps.setProperty("openkad.cache.share", "1");
    // minimum time between successive pings
    defaultProps.setProperty("openkad.bucket.valid_timespan", TimeUnit.MINUTES.toMillis(1) + "");
    // network timeouts and concurrency level
    defaultProps.setProperty("openkad.net.concurrency", "1");
    defaultProps.setProperty("openkad.net.timeout", TimeUnit.SECONDS.toMillis(1000) + "");
    defaultProps.setProperty("openkad.net.forwarded.timeout", TimeUnit.SECONDS.toMillis(1200) + "");

    defaultProps.setProperty("openkad.color.candidates", "1");
    defaultProps.setProperty("openkad.color.slack.size", "1");
    defaultProps.setProperty("openkad.color.allcolors", "95");
    // interval between successive find node operations for refresh buckets
    defaultProps.setProperty("openkad.refresh.interval", TimeUnit.SECONDS.toMillis(30000) + "");

    // local configuration, please touch
    defaultProps.setProperty("openkad.net.udp.port", "-1");
    defaultProps.setProperty("openkad.local.key", "");
    defaultProps.setProperty("openkad.file.nodes.path", "nodes");

    // misc
    defaultProps.setProperty("openkad.seed", "0");

    // shani Skademia

    defaultProps.setProperty("skademlia.siblinglist.size", "8");
    defaultProps.setProperty("dht.storage.checkInterval", "" + TimeUnit.SECONDS.toMillis(30000));

    return defaultProps;
  }
Пример #29
0
  @Test
  @Ignore
  public void runCanalInstanceTest() {
    ActionFactory<TableAction> actionFactory =
        new SingleSchemaActionFactory<>(
            Schemas.buildSchema("autoparts", TableAction.class)
                .addTable(
                    Schemas.buildTable("db_goods_stock")
                        .action(
                            new AbstractTableAction(
                                new SingleThreadCurrentHandleTable<TableAction>()) {
                              @Override
                              public void onAction(List<? extends RowChangedData> changedData) {
                                System.out.println("currentTable: " + getCurrentTable());
                                System.out.println(changedData);
                              }
                            })
                        .columns("id", "goods_id", "goods_number")
                        .columnCondition(Schemas.DEFAULT_DELETE_COLUMN_CONDITION))
                .create());
    CANAL_EXECUTOR.addInstanceHandle(new TableSectionHandle(LOCAL_ADDRESS, "shop", actionFactory));
    ActionFactory<EventTypeAction> eventTypeFactory =
        new SingleSchemaActionFactory<>(
            Schemas.buildSchema("autoparts", EventTypeAction.class)
                .addTable(
                    Schemas.buildTable("db_goods")
                        .action(
                            new EventTypeAction() {
                              @Override
                              public void onUpdateAction(List<RowChangedData.Update> updatedData) {
                                System.out.println("db_goods.onUpdateAction: " + updatedData);
                              }

                              @Override
                              public void onInsertAction(List<RowChangedData.Insert> insertedData) {
                                System.out.println("db_goods.onInsertAction: " + insertedData);
                              }

                              @Override
                              public void onDeleteAction(List<RowChangedData.Delete> deletedData) {
                                System.out.println("db_goods.onDeleteAction: " + deletedData);
                              }
                            })
                        .columns("goods_id", "goods_name", "cat_id", "new_goods_sn")
                        .columnCondition(
                            Conditions.unmodifiableContainer()
                                .mustCondition(Conditions.equal("is_delete", false))
                                .mustCondition(Conditions.equal("seller_id", 1))
                                .create()))
                .create());
    CANAL_EXECUTOR.addInstanceHandle(
        new EventTypeSectionHandle(LOCAL_ADDRESS, "shop_goods", eventTypeFactory));
    CANAL_EXECUTOR.startAllInstance(0L);
    try {
      TimeUnit.MINUTES.sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Пример #30
0
 /**
  * Return the timeout in seconds for the given TimeoutType.
  *
  * <p>It doesn't make sense to pass in the DEFAULT timeout type, because that is a
  * context-sensitive timeout.
  *
  * @param timeout - the TimeoutType (other than DEFAULT) to get the timeout in seconds for.
  * @return - the timeout in seconds
  */
 public int getTimeoutInSeconds(TimeoutType timeout) {
   Preconditions.checkNotNull(timeout, "Cannot get timeout for null timeout.");
   Preconditions.checkArgument(
       timeout != TimeoutType.DEFAULT,
       "Can only get the standard timeout for timeout types other than DEFAULT");
   switch (timeout) {
     case CLICK_TIMEOUT:
       return getClickTimeoutSeconds();
     case WEB_ELEMENT_PRESENCE_TIMEOUT:
       return getWebElementPresenceTimeoutSeconds();
     case POLLING_WITH_REFRESH_TIMEOUT:
       return getPollingWithRefreshTimeoutSeconds();
     case PAGE_REFRESH_TIMEOUT:
       return getPageRefreshTimeoutSeconds();
     case PAGE_LOAD_TIMEOUT:
       return getPageLoadTimeoutSeconds();
     case SHORT:
       return getShortTimeoutSeconds();
     case MEDIUM:
       return getMediumTimeoutSeconds();
     case LONG:
       return getLongTimeoutSeconds();
     case ONE_SECOND:
       return 1;
     case TWO_SECONDS:
       return 2;
     case FIVE_SECONDS:
       return 5;
     case TEN_SECONDS:
       return 10;
     case TWENTY_SECONDS:
       return 20;
     case SIXTY_SECONDS:
       return 60;
     case THIRTY_MINUTES:
       return (int) TimeUnit.MINUTES.toSeconds(30);
     case SIXTY_MINUTES:
       return (int) TimeUnit.MINUTES.toSeconds(60);
     case NINETY_MINUTES:
       return (int) TimeUnit.MINUTES.toSeconds(90);
     case TWO_HOURS:
       return (int) TimeUnit.HOURS.toSeconds(2);
     default:
       return getWebElementPresenceTimeoutSeconds();
   }
 }