How to use start method of org.mockito.internal.util.Timer class

Best Mockito code snippet using org.mockito.internal.util.Timer.start

Source:TimerServiceBean2Test.java Github

copy

Full Screen

...146 assertEquals("Wrong exec date for specified billing timer",147 calNow.get(Calendar.DAY_OF_YEAR),148 calExec.get(Calendar.DAY_OF_YEAR));149 } else {150 // should be started for the next day151 assertEquals("Wrong exec date for specified billing timer",152 calNow.get(Calendar.DAY_OF_YEAR) + 1,153 calExec.get(Calendar.DAY_OF_YEAR));154 }155 // ensure that the execution time is ahead from now156 assertTrue("Wrong execution time for timer", timer157 .getExecDate().getTime() >= now);158 } else {159 if (timerType == TimerType.DISCOUNT_END_CHECK) {160 assertEquals("Wrong interval specified for timer", 0,161 timer.getIntervalDuration());162 } else if (timerType == TimerType.USER_NUM_CHECK) {163 assertEquals("Wrong interval specified for timer",164 43200000, timer.getIntervalDuration());165 } else {166 assertEquals("Wrong interval specified for timer", 10000,167 timer.getIntervalDuration());168 }169 }170 }171 }172 private TimerStub getTimerForType(TimerType timerType) {173 for (TimerStub timer : ParameterizedTypes.iterable(tss.getTimers(),174 TimerStub.class)) {175 Calendar cal = Calendar.getInstance();176 cal.setTime(timer.getExecDate());177 TimerType tType = (TimerType) timer.getInfo();178 if (tType == timerType) {179 return timer;180 }181 }182 return null;183 }184 @Test185 public void initTimers_billingNegativeOffset() throws Exception {186 // given187 cfs.setConfigurationSetting(188 ConfigurationKey.TIMER_INTERVAL_BILLING_OFFSET, "-123156100215");189 // when190 tm.initTimers();191 // then192 TimerStub timer = getTimerForType(TimerType.BILLING_INVOCATION);193 Calendar cal = Calendar.getInstance();194 cal.setTime(timer.getExecDate());195 Calendar calNow = Calendar.getInstance();196 calNow.setTimeInMillis(now);197 // although the initialization data is invalid (negative198 // offset), the timer must be initialized with offset 0199 // (that means timer starts next day at 00:00:00.0000)200 assertEquals(calNow.get(Calendar.DAY_OF_YEAR) + 1,201 cal.get(Calendar.DAY_OF_YEAR));202 // ensure that the execution time is ahead from now203 assertTrue(timer.getExecDate().getTime() >= now);204 }205 // related to bug 7482206 @Test207 public void initTimers_withinNextOffset() throws ValidationException {208 TimeZone.setDefault(TimeZone.getTimeZone("GMT"));209 long interval = 1000L * 60L * 60L; // every hour210 Date current = new Date();211 current.setTime(interval);212 long offset = 1000L * 60L * 60L * 24L; // one day offset213 cfs.setConfigurationSetting(214 ConfigurationKey.TIMER_INTERVAL_ORGANIZATION,215 String.valueOf(current.getTime()));216 cfs.setConfigurationSetting(217 ConfigurationKey.TIMER_INTERVAL_ORGANIZATION_OFFSET,218 String.valueOf(offset));219 tm.initTimers();220 TimerStub timer = getTimerForType(TimerType.ORGANIZATION_UNCONFIRMED);221 Calendar cal = Calendar.getInstance();222 cal.setTime(timer.getExecDate());223 assertTrue(224 "TIMER SHOULD BE EXECUTED WITHIN THE NEXT OFFSET\ncurrent time= "225 + (new Date()) + "\nnext execution= "226 + (new Date(timer.getExecDate().getTime()))227 + "\ncurrent + offset= "228 + (new Date((new Date().getTime()) + offset)), timer229 .getExecDate().getTime() <= (new Date()).getTime()230 + offset);231 }232 // related to bug 7482233 @Test234 public void initTimers_offsetTooSmall() throws InterruptedException,235 ValidationException {236 TimeZone.setDefault(TimeZone.getTimeZone("GMT"));237 long interval = 1000L * 60L * 60L; // every hour238 Date current = new Date();239 current.setTime(interval);240 long offset = 10L;241 cfs.setConfigurationSetting(242 ConfigurationKey.TIMER_INTERVAL_ORGANIZATION,243 String.valueOf(current.getTime()));244 cfs.setConfigurationSetting(245 ConfigurationKey.TIMER_INTERVAL_ORGANIZATION_OFFSET,246 String.valueOf(offset));247 Thread.sleep(offset);248 tm.initTimers();249 TimerStub timer = getTimerForType(TimerType.ORGANIZATION_UNCONFIRMED);250 Calendar cal = Calendar.getInstance();251 cal.setTime(timer.getExecDate());252 assertTrue((timer.getExecDate().getTime() > (new Date()).getTime()253 + offset)254 && (timer.getExecDate().getTime() < (new Date()).getTime()255 + interval + offset));256 }257 @Test258 public void getTimerDetailsForTimerType() {259 // given260 ConfigurationServiceLocal cfs_mock = Mockito261 .mock(ConfigurationServiceLocal.class);262 tm.cfgMgmt = cfs_mock;263 // when264 tm.getTimerDetailsForTimerType(TimerType.USER_NUM_CHECK);265 // then266 Mockito.verify(cfs_mock, Mockito.never()).getBillingRunStartTimeInMs();267 Mockito.verify(cfs_mock, Mockito.times(1)).getLongConfigurationSetting(268 Mockito.any(ConfigurationKey.class), Mockito.anyString());269 tm.cfgMgmt = cfs;270 }271 @Test272 public void handleTimer_billing() throws Exception {273 // given274 TimerStub timer = new TimerStub();275 timer.setInfo(TimerType.BILLING_INVOCATION);276 // when277 tm.handleTimer(timer);278 // then279 verify(bss, times(1)).startBillingRun(Matchers.anyLong());280 }281 @Test282 public void handleTimer_userNum() throws Exception {283 // given284 TimerStub timer = new TimerStub();285 timer.setInfo(TimerType.USER_NUM_CHECK);286 // when287 tm.handleTimer(timer);288 // then289 Mockito.verify(as, Mockito.times(1)).checkUserNum();290 }291 @Test292 public void handleTimer_billingNotHandledCheckReinitOfTimer()293 throws Exception {294 // given295 TimerStub timer = new TimerStub();296 timer.setInfo(TimerType.BILLING_INVOCATION);297 when(query.getResultList()).thenReturn(298 Arrays.asList(new TimerProcessing()));299 // when300 tm.handleTimer(timer);301 // then302 verifyZeroInteractions(bss);303 assertEquals("wrong number of timers", 0, tss.getTimers().size());304 }305 @Test306 public void handleTimer_handleTimerPeriodicVerifyNoReinitialization()307 throws Exception {308 TimerStub timer = new TimerStub();309 TimerType timerType = TimerType.ORGANIZATION_UNCONFIRMED;310 timer.setInfo(timerType);311 tss.createTimer(new Date(), timerType);312 tm.handleTimer(timer);313 Iterable<Timer> timers = ParameterizedTypes.iterable(tss.getTimers(),314 Timer.class);315 List<Timer> timerList = new ArrayList<Timer>();316 for (Timer t : timers) {317 timerList.add(t);318 }319 assertEquals(320 "No additional timer must have been initialized, as the present one is already periodid with a fix interval",321 1, timerList.size());322 }323 @Test324 public void initTimers_getCurrentTimerExpirationDates()325 throws ValidationException {326 tss = new TimerServiceStub() {327 @Override328 public Timer createTimer(Date arg0, Serializable arg1)329 throws IllegalArgumentException, IllegalStateException,330 EJBException {331 initTimer((TimerType) arg1, arg0);332 getTimers().add(timer);333 return null;334 }335 };336 when(ctx.getTimerService()).thenReturn(tss);337 List<VOTimerInfo> expirationDates;338 tm.initTimers();339 expirationDates = tm.getCurrentTimerExpirationDates();340 tm.initTimers();341 assertEquals(7, expirationDates.size());342 }343 @Test(expected = ValidationException.class)344 public void initTimers_nextExpirationDateNegative()345 throws ValidationException {346 tss = new TimerServiceStub() {347 @Override348 public Timer createTimer(Date arg0, Serializable arg1)349 throws IllegalArgumentException, IllegalStateException,350 EJBException {351 initTimer((TimerType) arg1, arg0);352 getTimers().add(timer);353 return null;354 }355 };356 when(ctx.getTimerService()).thenReturn(tss);357 cfs.setConfigurationSetting(358 ConfigurationKey.TIMER_INTERVAL_ORGANIZATION,359 "9223372036854775807");360 tm.initTimers();361 }362 @Test(expected = ValidationException.class)363 public void initTimers_nextExpirationDateNegative_userCount()364 throws ValidationException {365 // given366 tss = new TimerServiceStub() {367 @Override368 public Timer createTimer(Date arg0, Serializable arg1)369 throws IllegalArgumentException, IllegalStateException,370 EJBException {371 initTimer((TimerType) arg1, arg0);372 getTimers().add(timer);373 return null;374 }375 };376 when(ctx.getTimerService()).thenReturn(tss);377 cfs.setConfigurationSetting(ConfigurationKey.TIMER_INTERVAL_USER_COUNT,378 "9223372036854775807");379 // when380 tm.initTimers();381 }382 @Test383 public void createTimerWithPeriod_discountEndCheckTimerCreated() {384 // when385 tm.createTimerWithPeriod(tss, TimerType.DISCOUNT_END_CHECK, 0L,386 Period.DAY);387 // then388 assertEquals(1, tss.getTimers().size());389 }390 @Test391 public void createTimerWithPeriod_discountEndCheckTimerNotCreated() {392 // given393 prepareTimerList(TimerType.DISCOUNT_END_CHECK,394 new Date(System.currentTimeMillis() + 10000));395 // when396 tm.createTimerWithPeriod(tss, TimerType.DISCOUNT_END_CHECK, 0L,397 Period.DAY);398 // then399 assertEquals(1, tss.getTimers().size());400 }401 @Test402 public void createTimerWithPeriod_billingInvocationCreated() {403 // when404 tm.createTimerWithPeriod(tss, TimerType.BILLING_INVOCATION, 0L,405 Period.DAY);406 // then407 assertEquals(1, tss.getTimers().size());408 }409 @Test410 public void createTimerWithPeriod_billingInvocationNotCreated() {411 // given412 prepareTimerList(TimerType.BILLING_INVOCATION,413 new Date(System.currentTimeMillis() + 10000));414 // when415 tm.createTimerWithPeriod(tss, TimerType.BILLING_INVOCATION, 0L,416 Period.DAY);417 // then418 assertEquals(1, tss.getTimers().size());419 }420 @Test421 public void isTimerCreated_noTypeMatch() {422 // given423 prepareTimerList(TimerType.BILLING_INVOCATION,424 new Date(System.currentTimeMillis()));425 prepareTimerList(TimerType.DISCOUNT_END_CHECK,426 new Date(System.currentTimeMillis()));427 // when428 boolean result = tm.isTimerCreated(TimerType.ORGANIZATION_UNCONFIRMED,429 tss);430 // then431 assertEquals(Boolean.FALSE, Boolean.valueOf(result));432 }433 @Test434 public void isTimerCreated_timerInvalid() {435 // given436 prepareTimerList(TimerType.BILLING_INVOCATION,437 new Date(System.currentTimeMillis()));438 // when439 boolean result = tm.isTimerCreated(TimerType.BILLING_INVOCATION, tss);440 // then441 assertEquals(Boolean.FALSE, Boolean.valueOf(result));442 }443 @Test444 public void isTimerCreated() {445 // given446 prepareTimerList(TimerType.DISCOUNT_END_CHECK,447 new Date(System.currentTimeMillis() + 10000));448 // when449 boolean result = tm.isTimerCreated(TimerType.DISCOUNT_END_CHECK, tss);450 // then451 assertEquals(Boolean.TRUE, Boolean.valueOf(result));452 }453 @Test454 public void isTimerCreated_cancelTimer() {455 // given456 prepareTimerList(TimerType.BILLING_INVOCATION,457 new Date(System.currentTimeMillis() - 10000));458 // when459 tm.isTimerCreated(TimerType.BILLING_INVOCATION, tss);460 // then461 assertEquals(Boolean.TRUE, Boolean.valueOf(timer.isCanceled()));462 }463 @SuppressWarnings({ "deprecation" })464 @Test465 public void getExpressionForPeriod_dayPeriod() {466 // given467 Date startDate = new Date(System.currentTimeMillis() + 10000);468 // when469 ScheduleExpression result = tm.getExpressionForPeriod(Period.DAY,470 startDate);471 // then472 assertEquals(startDate.getTime(), result.getStart().getTime());473 assertEquals(String.valueOf(startDate.getSeconds()), result.getSecond());474 assertEquals(String.valueOf(startDate.getMinutes()), result.getMinute());475 assertEquals(String.valueOf(startDate.getHours()), result.getHour());476 }477 @Test478 public void getExpressionForPeriod_dayPeriod_midnight() {479 // given480 Calendar cal = Calendar.getInstance();481 cal.add(Calendar.DAY_OF_YEAR, 1);482 cal.set(Calendar.HOUR_OF_DAY, 0);483 cal.set(Calendar.MINUTE, 0);484 cal.set(Calendar.SECOND, 0);485 cal.set(Calendar.MILLISECOND, 0);486 Date startDate = cal.getTime();487 // when488 ScheduleExpression result = tm.getExpressionForPeriod(Period.DAY,489 startDate);490 // then491 assertEquals(startDate.getTime(), result.getStart().getTime());492 assertEquals("0", result.getSecond());493 assertEquals("0", result.getMinute());494 assertEquals("0", result.getHour());495 }496 @SuppressWarnings({ "deprecation" })497 @Test498 public void getExpressionForPeriod_monthPeriod() {499 // given500 Date startDate = new Date(System.currentTimeMillis() + 10000);501 // when502 ScheduleExpression result = tm.getExpressionForPeriod(Period.MONTH,503 startDate);504 // then505 assertEquals(startDate.getTime(), result.getStart().getTime());506 assertEquals(String.valueOf(startDate.getSeconds()), result.getSecond());507 assertEquals(String.valueOf(startDate.getMinutes()), result.getMinute());508 assertEquals(String.valueOf(startDate.getHours()), result.getHour());509 assertEquals(String.valueOf(startDate.getDate()),510 result.getDayOfMonth());511 }512 @SuppressWarnings({ "deprecation" })513 @Test514 public void getExpressionForPeriod_monthPeriod_midnightOfFirstDay() {515 // given516 Calendar cal = Calendar.getInstance();517 cal.set(Calendar.DAY_OF_MONTH, 0);518 cal.set(Calendar.HOUR_OF_DAY, 0);519 cal.set(Calendar.MINUTE, 0);520 cal.set(Calendar.SECOND, 0);521 cal.set(Calendar.MILLISECOND, 0);522 Date startDate = cal.getTime();523 // when524 ScheduleExpression result = tm.getExpressionForPeriod(Period.MONTH,525 startDate);526 // then527 assertEquals(startDate.getTime(), result.getStart().getTime());528 assertEquals("0", result.getSecond());529 assertEquals("0", result.getMinute());530 assertEquals("0", result.getHour());531 assertEquals(String.valueOf(startDate.getDate()),532 result.getDayOfMonth());533 }534 private void prepareTimerList(TimerType timerType, Date date) {535 initTimer(timerType, date);536 tss.getTimers().add(timer);537 }538 private void initTimer(TimerType timerType, Date date) {539 timer = new TimerStub(0, timerType, date, false) {540 @Override541 public Date getNextTimeout() throws EJBException,542 IllegalStateException, NoSuchObjectLocalException {543 return getExecDate();544 }545 };...

Full Screen

Full Screen

Source:TestLogin.java Github

copy

Full Screen

...87 private Subject subject;88 private KerberosTicket ticket;89 private Set<KerberosTicket> tickets;90 private KerberosPrincipal server;91 private Date start_time;92 private Date end_time;93 94 @SuppressWarnings("unchecked")95 @Before96 public void before() throws Exception {97 // always make sure to start the unit tests off by setting the login to null98 // since we can't gaurantee order.99 Whitebox.setInternalState(Login.class, "current_login", (Login)null);100 101 start_time = new Date(1388534400000L);102 end_time = new Date(1388538000000L);103 104 config = new Config();105 timer = mock(HashedWheelTimer.class);106 callback = mock(CallbackHandler.class);107 app_config_entry = mock(AppConfigurationEntry.class);108 app_config = new AppConfigurationEntry[] { app_config_entry };109 app_config_options = new HashMap<String, Object>(2);110 app_config_options.put("useTicketCache", "true");111 app_config_options.put("principal", "Vetinari");112 login_context = mock(LoginContext.class);113 subject = mock(Subject.class);114 ticket = PowerMockito.mock(KerberosTicket.class);115 server = mock(KerberosPrincipal.class);116 117 final Configuration app_conf = mock(Configuration.class);118 when(app_conf.getAppConfigurationEntry(anyString())).thenReturn(app_config);119 120 PowerMockito.mockStatic(Configuration.class);121 PowerMockito.when(Configuration.getConfiguration()).thenReturn(app_conf);122 123 PowerMockito.mockStatic(LoginContext.class);124 PowerMockito.whenNew(LoginContext.class)125 .withAnyArguments().thenReturn(login_context);126 when(login_context.getSubject()).thenReturn(subject);127 128 tickets = new HashSet<KerberosTicket>();129 tickets.add(ticket);130 when(subject.getPrivateCredentials(any(Class.class))).thenReturn(tickets);131 132 when(ticket.getServer()).thenReturn(server);133 when(ticket.getStartTime()).thenReturn(start_time);134 when(ticket.getEndTime()).thenReturn(end_time);135 136 when(server.getName()).thenReturn("krbtgt/Lancre@Lancre");137 when(server.getRealm()).thenReturn("Lancre");138 139 // do NOT shell out during a unit test!140 PowerMockito.mockStatic(Shell.class);141 PowerMockito.mockStatic(System.class);142 PowerMockito.when(System.currentTimeMillis()).thenReturn(1388534460000L);143 }144 145 @Test146 public void initUserIfNeeded() throws Exception {147 Login.initUserIfNeeded(config, timer, CONTEXT_NAME, callback);148 // no-ops149 Login.initUserIfNeeded(config, timer, CONTEXT_NAME, callback);150 Login.initUserIfNeeded(config, timer, CONTEXT_NAME, callback);151 Login.initUserIfNeeded(config, timer, CONTEXT_NAME, callback);152 153 verify(login_context, never()).logout();154 verify(login_context, times(1)).login();155 verify(timer, times(1)).newTimeout((TimerTask)any(), anyLong(), 156 eq(TimeUnit.MILLISECONDS));157 }158 159 @Test160 public void ctorWithKerberos() throws Exception {161 final Login login = new Login(config, timer, CONTEXT_NAME, callback);162 assertEquals(subject, login.getSubject());163 verify(login_context, never()).logout();164 verify(login_context, times(1)).login();165 verify(timer, times(1)).newTimeout((TimerTask)any(), anyLong(), 166 eq(TimeUnit.MILLISECONDS));167 }168 169 @Test170 public void ctorNotKerberos() throws Exception {171 when(subject.getPrivateCredentials(KerberosTicket.class))172 .thenReturn(Collections.<KerberosTicket>emptySet());173 final Login login = new Login(config, timer, CONTEXT_NAME, callback);174 assertEquals(subject, login.getSubject());175 verify(login_context, never()).logout();176 verify(login_context, times(1)).login();177 verify(timer, never()).newTimeout((TimerTask)any(), anyLong(), 178 eq(TimeUnit.MILLISECONDS));179 }180 181 @Test (expected = LoginException.class)182 public void ctorNullContextName() throws Exception {183 new Login(config, timer, null, callback);184 }185 186 @Test (expected = LoginException.class)187 public void ctorEmptyContextName() throws Exception {188 new Login(config, timer, "", callback);189 }190 191 @Test (expected = LoginException.class)192 public void ctorFailed() throws Exception {193 doThrow(new LoginException("Boo!")).when(login_context).login();194 new Login(config, timer, CONTEXT_NAME, callback);195 }196 197 @Test198 public void getRefreshDelay() throws Exception {199 final Login login = new Login(config, timer, CONTEXT_NAME, callback);200 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);201 // should be within 80% of the end time202 assertTrue(delay < end_time.getTime());203 assertTrue(delay >= (end_time.getTime() - start_time.getTime()) * 0.80);204 }205 206 @Test207 public void getRefreshDelayNoTicket() throws Exception {208 final Login login = new Login(config, timer, CONTEXT_NAME, callback);209 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", 210 (KerberosTicket)null);211 assertEquals(Login.MIN_TIME_BEFORE_RELOGIN, delay);212 }213 214 @Test215 public void getRefreshDelayCantRenew() throws Exception {216 when(ticket.getRenewTill()).thenReturn(end_time);217 final Login login = new Login(config, timer, CONTEXT_NAME, callback);218 Whitebox.setInternalState(login, "using_ticket_cache", true);219 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);220 assertEquals(Login.MIN_TIME_BEFORE_RELOGIN, delay);221 }222 223 @Test224 public void getRefreshPastExpiration() throws Exception {225 final Login login = new Login(config, timer, CONTEXT_NAME, callback);226 PowerMockito.when(System.currentTimeMillis()).thenReturn(1388538060000L);227 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);228 assertEquals(Login.MIN_TIME_BEFORE_RELOGIN, delay);229 }230 231 @Test232 public void getRefreshWithinMinTime() throws Exception {233 final Login login = new Login(config, timer, CONTEXT_NAME, callback);234 PowerMockito.when(System.currentTimeMillis()).thenReturn(1388537942000L);235 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);236 assertEquals(0, delay);237 }238 239 @Test240 public void getRefreshSuperShortExpiration() throws Exception {241 // I guess this prevents possible dos attacks if someone set the lifetime to242 // be less than a minute243 final Login login = new Login(config, timer, CONTEXT_NAME, callback);244 start_time.setTime(1388537942000L);245 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);246 assertEquals(Login.MIN_TIME_BEFORE_RELOGIN, delay);247 }248 249 @Test250 public void getRefreshFlippedTicketTimes() throws Exception {251 final Login login = new Login(config, timer, CONTEXT_NAME, callback);252 // Friends don't let friend's KDC issue funky tickets like this253 end_time.setTime(1388534400000L);254 start_time.setTime(1388538000000L);255 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);256 assertEquals(Login.MIN_TIME_BEFORE_RELOGIN, delay);257 }258 259 @Test260 public void getRefreshSameTicketTimes() throws Exception {261 final Login login = new Login(config, timer, CONTEXT_NAME, callback);262 end_time.setTime(1388534400000L);263 final long delay = (Long)Whitebox.invokeMethod(login, "getRefreshDelay", ticket);264 assertEquals(Login.MIN_TIME_BEFORE_RELOGIN, delay);265 }266 @Test267 public void getTGT() throws Exception {268 final Login login = new Login(config, timer, CONTEXT_NAME, callback);...

Full Screen

Full Screen

Source:BaseTestHBaseClient.java Github

copy

Full Screen

...220 }221 /**222 * Creates a fake {@code .META.} row.223 * The row contains a single entry for {@link #TABLE}.224 * @param start_key The start key of the region in this entry.225 * @param stop_key The stop key of the region in this entry.226 */227 protected static ArrayList<KeyValue> metaRow(final byte[] start_key,228 final byte[] stop_key) {229 final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2);230 row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE));231 row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes()));232 return row;233 }234 235 protected static KeyValue metaRegionInfo( final byte[] start_key, 236 final byte[] stop_key, final boolean offline, final boolean splitting, 237 final byte[] table) {238 final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP);239 final byte is_splitting = (byte) (splitting ? 1 : 0);240 final byte[] regioninfo = concat(241 new byte[] {242 0, // version243 (byte) stop_key.length, // vint: stop key length244 },245 stop_key,246 offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline247 Bytes.fromLong(name.hashCode()), // long: region ID (make it random)248 new byte[] { (byte) name.length }, // vint: region name length249 name, // region name250 new byte[] {251 is_splitting, // boolean: splitting252 (byte) start_key.length, // vint: start key length253 },254 start_key255 );256 return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo);257 }258 protected static RegionInfo mkregion(final String table, final String name) {259 return new RegionInfo(table.getBytes(), name.getBytes(),260 HBaseClient.EMPTY_ARRAY);261 }262 protected static byte[] anyBytes() {263 return any(byte[].class);264 }265 /** Concatenates byte arrays together. */266 protected static byte[] concat(final byte[]... arrays) {267 int len = 0;268 for (final byte[] array : arrays) {269 len += array.length;270 }271 final byte[] result = new byte[len];272 len = 0;273 for (final byte[] array : arrays) {274 System.arraycopy(array, 0, result, len, array.length);275 len += array.length;276 }277 return result;278 }279 /** Creates a new Deferred that's already called back. */280 protected static <T> Answer<Deferred<T>> newDeferred(final T result) {281 return new Answer<Deferred<T>>() {282 public Deferred<T> answer(final InvocationOnMock invocation) {283 return Deferred.fromResult(result);284 }285 };286 }287 /**288 * A fake {@link Timer} implementation that fires up tasks immediately.289 * Tasks are called immediately from the current thread and a history of the290 * various tasks is logged.291 */292 static final class FakeTimer extends HashedWheelTimer {293 final List<Map.Entry<TimerTask, Long>> tasks = 294 new ArrayList<Map.Entry<TimerTask, Long>>();295 final ArrayList<Timeout> timeouts = new ArrayList<Timeout>();296 boolean run = true;297 298 @Override299 public Timeout newTimeout(final TimerTask task,300 final long delay,301 final TimeUnit unit) {302 try {303 tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay));304 if (run) {305 task.run(null); // Argument never used in this code base.306 }307 final Timeout timeout = mock(Timeout.class);308 timeouts.add(timeout);309 return timeout; // Return value never used in this code base.310 } catch (RuntimeException e) {311 throw e;312 } catch (Exception e) {313 throw new RuntimeException("Timer task failed: " + task, e);314 }315 }316 @Override317 public Set<Timeout> stop() {318 run = false;319 return new HashSet<Timeout>(timeouts);320 }321 }322 /**323 * A fake {@link org.jboss.netty.util.Timer} implementation.324 * Instead of executing the task it will store that task in a internal state325 * and provides a function to start the execution of the stored task.326 * This implementation thus allows the flexibility of simulating the327 * things that will be going on during the time out period of a TimerTask.328 * This was mainly return to simulate the timeout period for329 * alreadyNSREdRegion test, where the region will be in the NSREd mode only330 * during this timeout period, which was difficult to simulate using the331 * above {@link FakeTimer} implementation, as we don't get back the control332 * during the timeout period333 *334 * Here it will hold at most two Tasks. We have two tasks here because when335 * one is being executed, it may call for newTimeOut for another task.336 */337 static final class FakeTaskTimer extends HashedWheelTimer {338 protected TimerTask newPausedTask = null;339 protected TimerTask pausedTask = null;...

Full Screen

Full Screen

Source:WorkflowTestBase.java Github

copy

Full Screen

1package de.ascendro.f4m.service.workflow.utils;2import static org.hamcrest.Matchers.containsInAnyOrder;3import static org.junit.Assert.assertEquals;4import static org.junit.Assert.assertThat;5import static org.mockito.ArgumentMatchers.any;6import static org.mockito.ArgumentMatchers.anyString;7import static org.mockito.Mockito.doAnswer;8import static org.mockito.Mockito.when;9import java.util.ArrayList;10import java.util.Date;11import java.util.List;12import java.util.concurrent.Callable;13import java.util.concurrent.ConcurrentHashMap;14import java.util.concurrent.ScheduledFuture;15import java.util.concurrent.ScheduledThreadPoolExecutor;16import java.util.concurrent.TimeUnit;17import java.util.concurrent.atomic.AtomicBoolean;18import java.util.concurrent.atomic.AtomicLong;19import org.drools.core.time.InternalSchedulerService;20import org.drools.core.time.Job;21import org.drools.core.time.JobContext;22import org.drools.core.time.JobHandle;23import org.drools.core.time.SelfRemovalJobContext;24import org.drools.core.time.TimerService;25import org.drools.core.time.Trigger;26import org.drools.core.time.impl.TimerJobInstance;27import org.jbpm.process.core.timer.SchedulerServiceInterceptor;28import org.jbpm.process.core.timer.impl.DelegateSchedulerServiceInterceptor;29import org.jbpm.process.core.timer.impl.ThreadPoolSchedulerService;30import org.jbpm.process.instance.timer.TimerManager.ProcessJobContext;31import org.jbpm.process.instance.timer.TimerManager.StartProcessJobContext;32import org.junit.After;33import org.junit.Before;34import org.kie.api.io.Resource;35import org.mockito.Mock;36import org.mockito.MockitoAnnotations;37import org.mockito.invocation.InvocationOnMock;38import org.mockito.stubbing.Answer;39import com.google.gson.JsonArray;40import com.google.gson.JsonElement;41import com.google.gson.JsonObject;42import de.ascendro.f4m.server.profile.CommonProfileAerospikeDao;43import de.ascendro.f4m.service.json.JsonMessageUtil;44import de.ascendro.f4m.service.profile.model.Profile;45import de.ascendro.f4m.service.util.EventServiceClient;46import de.ascendro.f4m.service.util.TestJsonMessageUtil;47import de.ascendro.f4m.service.workflow.config.WorkflowConfig;48public abstract class WorkflowTestBase {49 protected static final String ACTION_PUBLISH = "Publish";50 protected static final String ACTION_UNPUBLISH = "Unpublish";51 protected static final String ACTION_INTERNAL_REVIEW = "InternalReview";52 protected static final String ACTION_EXTERNAL_REVIEW = "ExternalReview";53 protected static final String ACTION_COMMUNITY_REVIEW = "CommunityReview";54 protected static final String ACTION_AUTOMATIC_TRANSLATION = "AutomaticTranslation";55 protected static final String ACTION_SET_PRIORITY_HIGH = "SetPriority(High)";56 protected static final String ACTION_SET_STATUS_REVIEW = "SetStatus(Review)";57 protected static final String ACTION_SET_STATUS_AUTOMATIC_TRANSLATION = "SetStatus(AutomaticTranslation)";58 protected static final String ACTION_SET_STATUS_APPROVED = "SetStatus(Approved)";59 protected static final String ACTION_SET_STATUS_REJECTED = "SetStatus(Rejected)";60 protected static final String ACTION_SET_STATUS_PUBLISHED = "SetStatus(Published)";61 protected static final String ACTION_SET_STATUS_UNPUBLISHED = "SetStatus(Unpublished)";62 protected static final String ACTION_SET_STATUS_ARCHIVED = "SetStatus(Archived)";63 protected static final String ACTION_SEND_EMAIL_AUTHOR = "SendEmail(Author)";64 protected static final String ACTION_SEND_EMAIL_ADMIN = "SendEmail(Admin)";65 protected static final String ACTION_EDIT_QUESTION = "EditQuestion";66 protected static final String ACTION_ARCHIVE = "Archive";67 protected static final String PARAM_REVIEW_OUTCOME = "reviewOutcome";68 protected static final String VALUE_APPROVED = "Approved";69 protected static final String VALUE_REJECTED = "Rejected";70 71 protected static final String PARAM_EDIT_OUTCOME = "editOutcome";72 protected static final String VALUE_EDITED = "Edited";73 protected static final String VALUE_ARCHIVED = "Archived";74 75 protected static final String PARAM_REVIEW_TYPE = "reviewType";76 protected static final String VALUE_COMMUNITY = "COMMUNITY";77 protected static final String VALUE_INTERNAL = "INTERNAL";78 protected static final String VALUE_EXTERNAL = "EXTERNAL";79 protected static final String PARAM_TRANSLATION_TYPE = "translationType";80 protected static final String VALUE_AUTOMATIC = "AUTOMATIC";81 82 protected static final String PARAM_RESULT = "result";83 protected static final String VALUE_SUCCESS = "Success";84 protected static final String VALUE_FAILURE = "Failure";85 86 protected static final String PARAM_ARCHIVE = "archive";87 protected static final boolean VALUE_TRUE = true;88 protected static final boolean VALUE_FALSE = false;89 protected static final String PARAM_ITEM_STATUS = "itemStatus";90 protected static final String VALUE_PUBLISHED = "Published";91 protected static final String VALUE_UNPUBLISHED = "Unpublished";92 93 protected static final String ROLE_COMMUNITY = "COMMUNITY";94 protected static final String ROLE_INTERNAL = "INTERNAL";95 protected static final String ROLE_EXTERNAL = "EXTERNAL";96 protected static final String ROLE_ADMIN = "ADMIN";97 98 protected static final String USER_ID = "user";99 protected static final String USER_ID_2 = "anotheruser";100 protected static final String TENANT_ID = "tenantId";101 102 protected static final String TASK_ID = "task1";103 104 protected WorkflowWrapper workflowWrapper;105 106 @Mock107 private CommonProfileAerospikeDao profileDao;108 109 private JsonMessageUtil jsonMessageUtil = new TestJsonMessageUtil();110 111 @Mock112 private EventServiceClient eventServiceClient;113 private AtomicBoolean fireTimersImmediately = new AtomicBoolean(false);114 protected final List<String> receivedEvents = new ArrayList<>();115 116 @Before117 public void setUp() {118 MockitoAnnotations.initMocks(this);119 doAnswer(new Answer<Void>() {120 @Override121 public Void answer(InvocationOnMock invocation) throws Throwable {122 JsonObject evt = (JsonObject) invocation.getArgument(1);123 receivedEvents.add(evt.get("triggeredAction").getAsString()); // 2nd argument - published content124 return null;125 }126 }).when(eventServiceClient).publish(anyString(), any(JsonElement.class));127 128 WorkflowConfig config = new WorkflowConfig();129 workflowWrapper = new WorkflowWrapper(config, new WorkflowResourceProvider() {130 @Override131 public List<Resource> getResources() {132 return getResourceList();133 }134 }, profileDao, jsonMessageUtil, eventServiceClient) {135 @Override136 protected ThreadPoolSchedulerService prepareScheduler() {137 // Prepare customized scheduler service allowing to change scheduled interval and minimizing shutdown time138 return new ThreadPoolSchedulerService(3) {139 private AtomicLong idCounter = new AtomicLong();140 private ScheduledThreadPoolExecutor scheduler;141 private TimerService globalTimerService;142 private SchedulerServiceInterceptor interceptor = new DelegateSchedulerServiceInterceptor(this);143 private ConcurrentHashMap<String, JobHandle> activeTimer = new ConcurrentHashMap<String, JobHandle>();144 @Override145 public void initScheduler(TimerService globalTimerService) {146 this.globalTimerService = globalTimerService;147 this.scheduler = new ScheduledThreadPoolExecutor(1);148 }149 @Override150 public void shutdown() {151 this.scheduler.shutdownNow();152 }153 @Override154 public JobHandle scheduleJob(Job job, JobContext ctx, Trigger trigger) {155 Date date = trigger.hasNextFireTime();156 if (date != null) {157 String jobname = null;158 if (ctx instanceof ProcessJobContext) {159 ProcessJobContext processCtx = (ProcessJobContext) ctx;160 jobname = processCtx.getSessionId() + "-" + processCtx.getProcessInstanceId() + "-"161 + processCtx.getTimer().getId();162 if (processCtx instanceof StartProcessJobContext) {163 jobname = "StartProcess-" + ((StartProcessJobContext) processCtx).getProcessId()164 + "-" + processCtx.getTimer().getId();165 }166 if (activeTimer.containsKey(jobname)) {167 return activeTimer.get(jobname);168 }169 }170 GlobalJDKJobHandle jobHandle = new GlobalJDKJobHandle(idCounter.getAndIncrement());171 TimerJobInstance jobInstance = globalTimerService.getTimerJobFactoryManager()172 .createTimerJobInstance(job, ctx, trigger, jobHandle,173 (InternalSchedulerService) globalTimerService);174 jobHandle.setTimerJobInstance((TimerJobInstance) jobInstance);175 interceptor.internalSchedule((TimerJobInstance) jobInstance);176 if (jobname != null) {177 activeTimer.put(jobname, jobHandle);178 }179 return jobHandle;180 } else {181 return null;182 }183 }184 @Override185 public boolean removeJob(JobHandle jobHandle) {186 if (jobHandle == null) {187 return false;188 }189 jobHandle.setCancel(true);190 JobContext jobContext = ((GlobalJDKJobHandle) jobHandle).getTimerJobInstance().getJobContext();191 try {192 ProcessJobContext processCtx = null;193 if (jobContext instanceof SelfRemovalJobContext) {194 processCtx = (ProcessJobContext) ((SelfRemovalJobContext) jobContext).getJobContext();195 } else {196 processCtx = (ProcessJobContext) jobContext;197 }198 String jobname = processCtx.getSessionId() + "-" + processCtx.getProcessInstanceId() + "-"199 + processCtx.getTimer().getId();200 if (processCtx instanceof StartProcessJobContext) {201 jobname = "StartProcess-" + ((StartProcessJobContext) processCtx).getProcessId() + "-"202 + processCtx.getTimer().getId();203 }204 activeTimer.remove(jobname);205 globalTimerService.getTimerJobFactoryManager()206 .removeTimerJobInstance(((GlobalJDKJobHandle) jobHandle).getTimerJobInstance());207 } catch (ClassCastException e) {208 // do nothing in case ProcessJobContext was not given209 }210 boolean removed = this.scheduler211 .remove((Runnable) ((GlobalJDKJobHandle) jobHandle).getFuture());212 return removed;213 }214 @Override215 public void internalSchedule(TimerJobInstance timerJobInstance) {216 if (scheduler.isShutdown()) {217 return;218 }219 Date date = timerJobInstance.getTrigger().hasNextFireTime();220 @SuppressWarnings("unchecked")221 Callable<Void> item = (Callable<Void>) timerJobInstance;222 GlobalJDKJobHandle jobHandle = (GlobalJDKJobHandle) timerJobInstance.getJobHandle();223 long then = date.getTime();224 long now = System.currentTimeMillis();225 ScheduledFuture<Void> future = null;226 if (then >= now && ! fireTimersImmediately.get()) {227 future = scheduler.schedule(item, then - now, TimeUnit.MILLISECONDS);228 } else {229 future = scheduler.schedule(item, 1, TimeUnit.SECONDS);230 }231 jobHandle.setFuture(future);232 globalTimerService.getTimerJobFactoryManager().addTimerJobInstance(timerJobInstance);233 }234 };235 }236 };237 }238 239 @After240 public void tearDown() {241 if (workflowWrapper != null) {242 workflowWrapper.close();243 }244 }245 246 protected abstract List<Resource> getResourceList();247 protected void assertResult(ActionResult result, boolean processFinished, String previousState, 248 List<String> newStatesTriggered, List<String> availableStates) {249 assertEquals(processFinished, result.isProcessFinished());250 assertEquals(previousState, result.getPreviousState());251 assertThat(result.getNewStatesTriggered(), containsInAnyOrder(newStatesTriggered.toArray()));252 assertThat(result.getAvailableStates(), containsInAnyOrder(availableStates.toArray()));253 }254 protected void prepareProfileRoles(String userId, String... roles) {255 Profile profile = new Profile();256 JsonArray roleArray = new JsonArray();257 for (String role : roles) {258 roleArray.add(Profile.TENANT_ROLE_PREFIX + TENANT_ID + Profile.TENANT_ROLE_SEPARATOR + role);259 }260 profile.setProperty(Profile.ROLES_PROPERTY, roleArray);261 when(profileDao.getProfile(userId)).thenReturn(profile);262 }263 protected void setFireTimersImmediately(boolean fireTimersImmediately) {264 this.fireTimersImmediately.set(fireTimersImmediately);265 }266}...

Full Screen

Full Screen

Source:TestReencryptionHandler.java Github

copy

Full Screen

...94 final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();95 Whitebox.setInternalState(rh, "throttleTimerAll", mockAll);96 Whitebox.setInternalState(rh, "throttleTimerLocked", mockLocked);97 Whitebox.setInternalState(rh, "taskQueue", queue);98 final StopWatch sw = new StopWatch().start();99 rh.getTraverser().throttle();100 sw.stop();101 assertTrue("should have throttled for at least 8 second",102 sw.now(TimeUnit.MILLISECONDS) > 8000);103 assertTrue("should have throttled for at most 12 second",104 sw.now(TimeUnit.MILLISECONDS) < 12000);105 }106 @Test107 public void testThrottleNoOp() throws Exception {108 final Configuration conf = new Configuration();109 conf.setDouble(DFS_NAMENODE_REENCRYPT_THROTTLE_LIMIT_HANDLER_RATIO_KEY,110 0.5);111 final ReencryptionHandler rh = mockReencryptionhandler(conf);112 // mock StopWatches so all = 30s, locked = 10s. With ratio = .5, throttle113 // should not happen.114 StopWatch mockAll = Mockito.mock(StopWatch.class);115 Mockito.when(mockAll.now()).thenReturn(new Long(30000));116 Mockito.when(mockAll.reset()).thenReturn(mockAll);117 StopWatch mockLocked = Mockito.mock(StopWatch.class);118 Mockito.when(mockLocked.now()).thenReturn(new Long(10000));119 Mockito.when(mockLocked.reset()).thenReturn(mockLocked);120 final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();121 Whitebox.setInternalState(rh, "throttleTimerAll", mockAll);122 Whitebox.setInternalState(rh, "throttleTimerLocked", mockLocked);123 Whitebox.setInternalState(rh, "taskQueue", queue);124 final Map<Long, ReencryptionUpdater.ZoneSubmissionTracker>125 submissions = new HashMap<>();126 Whitebox.setInternalState(rh, "submissions", submissions);127 StopWatch sw = new StopWatch().start();128 rh.getTraverser().throttle();129 sw.stop();130 assertTrue("should not have throttled",131 sw.now(TimeUnit.MILLISECONDS) < 1000);132 }133 @Test134 public void testThrottleConfigs() throws Exception {135 final Configuration conf = new Configuration();136 conf.setDouble(DFS_NAMENODE_REENCRYPT_THROTTLE_LIMIT_HANDLER_RATIO_KEY,137 -1.0);138 try {139 mockReencryptionhandler(conf);140 fail("Should not be able to init");141 } catch (IllegalArgumentException e) {142 GenericTestUtils.assertExceptionContains(" is not positive", e);143 }144 conf.setDouble(DFS_NAMENODE_REENCRYPT_THROTTLE_LIMIT_HANDLER_RATIO_KEY,145 0.0);146 try {147 mockReencryptionhandler(conf);148 fail("Should not be able to init");149 } catch (IllegalArgumentException e) {150 GenericTestUtils.assertExceptionContains(" is not positive", e);151 }152 }153 @Test154 public void testThrottleAccumulatingTasks() throws Exception {155 final Configuration conf = new Configuration();156 final ReencryptionHandler rh = mockReencryptionhandler(conf);157 // mock tasks piling up158 final Map<Long, ReencryptionUpdater.ZoneSubmissionTracker>159 submissions = new HashMap<>();160 final ReencryptionUpdater.ZoneSubmissionTracker zst =161 new ReencryptionUpdater.ZoneSubmissionTracker();162 submissions.put(new Long(1), zst);163 Future mock = Mockito.mock(Future.class);164 for (int i = 0; i < Runtime.getRuntime().availableProcessors() * 3; ++i) {165 zst.addTask(mock);166 }167 Thread removeTaskThread = new Thread() {168 public void run() {169 try {170 Thread.sleep(3000);171 } catch (InterruptedException ie) {172 LOG.info("removeTaskThread interrupted.");173 Thread.currentThread().interrupt();174 }175 zst.getTasks().clear();176 }177 };178 Whitebox.setInternalState(rh, "submissions", submissions);179 final StopWatch sw = new StopWatch().start();180 removeTaskThread.start();181 rh.getTraverser().throttle();182 sw.stop();183 LOG.info("Throttle completed, consumed {}", sw.now(TimeUnit.MILLISECONDS));184 assertTrue("should have throttled for at least 3 second",185 sw.now(TimeUnit.MILLISECONDS) >= 3000);186 }187}...

Full Screen

Full Screen

Source:Timer_ESTest_scaffolding.java Github

copy

Full Screen

...38 } 39 @Before 40 public void initTestCase(){ 41 threadStopper.storeCurrentThreads();42 threadStopper.startRecordingTime();43 org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); 44 org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); 45 setSystemProperties(); 46 org.evosuite.runtime.GuiSupport.setHeadless(); 47 org.evosuite.runtime.Runtime.getInstance().resetRuntime(); 48 org.evosuite.runtime.agent.InstrumentingAgent.activate(); 49 } 50 @After 51 public void doneWithTestCase(){ 52 threadStopper.killAndJoinClientThreads();53 org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); 54 org.evosuite.runtime.classhandling.JDKClassResetter.reset(); 55 resetClasses(); 56 org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); ...

Full Screen

Full Screen

Source:TimerServiceTest.java Github

copy

Full Screen

...45 when(scheduledExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))46 .thenReturn(scheduledFuture);47 TimerService<AllocationID> timerService = new TimerService<>(scheduledExecutorService, 100L);48 TimeoutListener<AllocationID> listener = mock(TimeoutListener.class);49 timerService.start(listener);50 // Invoke register and unregister.51 timerService.registerTimeout(new AllocationID(), 10, TimeUnit.SECONDS);52 timerService.registerTimeout(new AllocationID(), 10, TimeUnit.SECONDS);53 timerService.unregisterAllTimeouts();54 // Verify.55 Map<?, ?> timeouts = (Map<?, ?>) Whitebox.getInternalState(timerService, "timeouts");56 assertTrue(timeouts.isEmpty());57 verify(scheduledFuture, times(2)).cancel(true);58 }59}...

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1public class java {2 public static void main(String[] args) {3 Timer timer = new Timer();4 timer.start();5 }6}7public class java {8 public static void main(String[] args) {9 Timer timer = new Timer();10 timer.start();11 }12}13public class java {14 public static void main(String[] args) {15 Timer timer = new Timer();16 timer.start();17 }18}19public class java {20 public static void main(String[] args) {21 Timer timer = new Timer();22 timer.start();23 }24}25public class java {26 public static void main(String[] args) {27 Timer timer = new Timer();28 timer.start();29 }30}31public class java {32 public static void main(String[] args) {33 Timer timer = new Timer();34 timer.start();35 }36}37public class java {38 public static void main(String[] args) {39 Timer timer = new Timer();40 timer.start();41 }42}43public class java {44 public static void main(String[] args) {45 Timer timer = new Timer();46 timer.start();47 }48}49public class java {50 public static void main(String[] args) {51 Timer timer = new Timer();52 timer.start();53 }54}55public class java {56 public static void main(String[] args) {57 Timer timer = new Timer();58 timer.start();59 }60}61public class java {

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.util;2import java.util.concurrent.TimeUnit;3public class TimerTest {4 public static void main(String[] args) throws InterruptedException {5 Timer timer = new Timer();6 timer.start();7 TimeUnit.SECONDS.sleep(5);8 System.out.println("Time elapsed: " + timer.stop());9 }10}11package org.mockito.internal.util;12import java.util.concurrent.TimeUnit;13public class TimerTest {14 public static void main(String[] args) throws InterruptedException {15 Timer timer = new Timer();16 timer.start();17 TimeUnit.SECONDS.sleep(5);18 System.out.println("Time elapsed: " + timer.stop());19 }20}21package org.mockito.internal.util;22import java.util.concurrent.TimeUnit;23public class TimerTest {24 public static void main(String[] args) throws InterruptedException {25 Timer timer = new Timer();26 timer.start();27 TimeUnit.SECONDS.sleep(5);28 System.out.println("Time elapsed: " + timer.stop());29 }30}31package org.mockito.internal.util;32import java.util.concurrent.TimeUnit;33public class TimerTest {34 public static void main(String[] args) throws InterruptedException {35 Timer timer = new Timer();36 timer.start();37 TimeUnit.SECONDS.sleep(5);38 System.out.println("Time elapsed: " + timer.stop());39 }40}41package org.mockito.internal.util;42import java.util.concurrent.TimeUnit;43public class TimerTest {44 public static void main(String[] args) throws InterruptedException {45 Timer timer = new Timer();46 timer.start();47 TimeUnit.SECONDS.sleep(5);48 System.out.println("Time elapsed: " + timer.stop());49 }50}51package org.mockito.internal.util;52import java.util.concurrent.TimeUnit;53public class TimerTest {54 public static void main(String[] args) throws InterruptedException {55 Timer timer = new Timer();56 timer.start();

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.util;2import org.junit.Test;3import static org.junit.Assert.*;4public class TimerTest {5 public void testStart() throws Exception {6 Timer timer = new Timer();7 timer.start();8 long start = timer.start();9 assertEquals(start, timer.start());10 }11}12package org.mockito.internal.util;13import org.junit.Test;14import static org.junit.Assert.*;15public class TimerTest {16 public void testStart() throws Exception {17 Timer timer = new Timer();18 timer.start();19 long start = timer.start();20 assertEquals(start, timer.start());21 }22}

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.util;2import java.util.concurrent.TimeUnit;3import java.util.concurrent.ScheduledExecutorService;4import java.util.concurrent.ScheduledThreadPoolExecutor;5import java.util.concurrent.ScheduledFuture;6import java.util.concurrent.Callable;7import java.util.concurrent.Executor;8import java.util.concurrent.Executors;9import java.util.concurrent.ThreadFactory;10import java.util.concurrent.atomic.AtomicInteger;11import java.util.concurrent.atomic.AtomicReference;12import java.util.concurrent.atomic.AtomicBoolean;13import java.util.concurrent.locks.Lock;14import java.util.concurrent.locks.ReentrantLock;15import java.util.concurrent.locks.Condition;16import java.util.concurrent.ExecutionException;17import java.util.concurrent.TimeoutException;18import java.util.concurrent.atomic.AtomicLong;19import java.util.concurrent.ThreadFactory;20import java.util.concurrent.TimeUnit;21import java.util.concurrent.atomic.AtomicInteger;22import java.util.concurrent.atomic.AtomicReference;23import java.util.concurrent.atomic.AtomicBoolean;24import java.util.concurrent.locks.Lock;25import java.util.concurrent.locks.ReentrantLock;26import java.util.concurrent.locks.Condition;27import java.util.concurrent.ExecutionException;28import java.util.concurrent.TimeoutException;29import java.util.concurrent.atomic.AtomicLong;30import java.util.concurrent.ThreadFactory;31import java.util.concurrent.TimeUnit;32import java.util.concurrent.atomic.AtomicInteger;33import java.util.concurrent.atomic.AtomicReference;34import java.util.concurrent.atomic.AtomicBoolean;35import java.util.concurrent.locks.Lock;36import java.util.concurrent.locks.ReentrantLock;37import java.util.concurrent.locks.Condition;38import java.util.concurrent.ExecutionException;39import java.util.concurrent.TimeoutException;40import java.util.concurrent.atomic.AtomicLong;41import java.util.concurrent.ThreadFactory;42import java.util.concurrent.TimeUnit;43import java.util.concurrent.atomic.AtomicInteger;44import java.util.concurrent.atomic.AtomicReference;45import java.util.concurrent.atomic.AtomicBoolean;46import java.util.concurrent.locks.Lock;47import java.util.concurrent.locks.ReentrantLock;48import java.util.concurrent.locks.Condition;49import java.util.concurrent.ExecutionException;50import java.util.concurrent.TimeoutException;51import java.util.concurrent.atomic.AtomicLong;52import java.util.concurrent.ThreadFactory;53import java.util.concurrent.TimeUnit;54import java.util.concurrent.atomic.AtomicInteger;55import java.util.concurrent.atomic.AtomicReference;56import java.util.concurrent.atomic.AtomicBoolean;57import java.util.concurrent.locks.Lock;58import java.util.concurrent.locks.ReentrantLock;59import java.util.concurrent.locks.Condition;60import java.util.concurrent.ExecutionException;61import java.util.concurrent.TimeoutException;62import java.util.concurrent.atomic.AtomicLong;63import java.util.concurrent.ThreadFactory;64import java.util.concurrent.TimeUnit;65import java.util.concurrent.atomic.AtomicInteger;

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.coding;2import org.mockito.internal.util.Timer;3public class InputIllegalCatchCheck {4 public void foo() {5 try {6 Thread.sleep(1000);7 } catch (InterruptedException e) {8 Timer.start();9 Thread.currentThread().interrupt();10 }11 }12}13 package com.puppycrawl.tools.checkstyle.checks.coding;14-import java.util.HashSet;15+import java.util.Collections;16 import java.util.Set;17 import antlr.collections.AST;18@@ -8,7 +8,6 @@ import antlr.collections.AST;19 import com.puppycrawl.tools.checkstyle.api.Check;20 import com.puppycrawl.tools.checkstyle.api.DetailAST;21 import com.puppycrawl.tools.checkstyle.api.TokenTypes;22-import com.puppycrawl.tools.checkstyle.utils.CheckUtils;23 private Set<String> illegalClassNames = new HashSet<String>();24 private Set<String> illegalClassPatternStrings = new HashSet<String>();25 private Set<Pattern> illegalClassPatterns = new HashSet<Pattern>();26 new HashSet<Pattern>();

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.imports.importorder;2import java.util.TimerTask;3public class InputImportOrderStartMethod extends TimerTask {4 public void run() {5 System.out.println("Hello World!");6 }7}8[ERROR] /home/akmo/GSoC/Checkstyle/src/1.java:1: Using the '.*' form of import should be avoided - java.util.TimerTask. [AvoidStarImport]9 |--LCURLY -> { [1:39]10 | |--LPAREN -> ( [2:12]11 | `--SLIST -> { [2:15]12 | | `--METHOD_CALL -> ( [3:30]

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.util;2import java.util.Date;3public class MockUtil {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 System.out.println(timer);8 }9}10package org.mockito.internal.util;11import java.util.Date;12public class Timer {13 private Date start;14 public void start() {15 this.start = new Date();16 }17 public String toString() {18 return "Timer started at: " + start;19 }20}

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.coding;2import java.util.concurrent.TimeUnit;3public class InputIllegalCatchExtendedCheckWithStartMethod {4 public void foo() {5 org.mockito.internal.util.Timer timer = new org.mockito.internal.util.Timer();6 timer.start();7 try {8 TimeUnit.SECONDS.sleep(1);9 } catch (InterruptedException e) {10 e.printStackTrace();11 }12 }13}14package com.puppycrawl.tools.checkstyle.checks.coding;15import java.util.concurrent.TimeUnit;16public class InputIllegalCatchExtendedCheckWithStartMethod {17 public void foo() {18 org.mockito.internal.util.Timer timer = new org.mockito.internal.util.Timer();19 timer.start();20 try {21 TimeUnit.SECONDS.sleep(1);22 } catch (InterruptedException e) {23 e.printStackTrace();24 }25 }26}

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.coding;2import org.mockito.internal.util.Timer;3public class InputIllegalThrowsCheck1 {4 public void method1() {5 Timer.start();6 }7}

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package cm.puppycral.tools.checkstyle.checks.coding;2import java.util.concurrent.TimeUnit;3public class InputIllegalCatchExtendedCheckWithStartMethod {4 public void foo() {5 org.mockito.internal.util.Timerimer = new org.mckito.internal.util.Timer();6 timer.start();7 try {8 TimeUnit.SECONDS.sleep(1);9 } catch (InterruptedException e) {10 e.printStackTrace();11 }12 }13}14package com.puppycrawl.tools.checkstyle.checks.coding;15import java.util.concurrent.TimeUnit;16public class InputIllegalCatchExtendedCheckWithStartMethod {17 public void foo() {18 org.mockito.internal.util.Timer timer = new org.mockito.internal.util.Timer();19 timer.start();20 try {21 TimeUnit.SECONDS.sleep(1);22 } catch (InterruptedException e) {23 e.printStackTrace();24 }25 }26}27import java.util.concurrent.locks.Condition;28import java.util.concurrent.ExecutionException;29import java.util.concurrent.TimeoutException;30import java.util.concurrent.atomic.AtomicLong;31import java.util.concurrent.ThreadFactory;32import java.util.concurrent.TimeUnit;33import java.util.concurrent.atomic.AtomicInteger;34import java.util.concurrent.atomic.AtomicReference;35import java.util.concurrent.atomic.AtomicBoolean;36import java.util.concurrent.locks.Lock;37import java.util.concurrent.locks.ReentrantLock;38import java.util.concurrent.locks.Condition;39import java.util.concurrent.ExecutionException;40import java.util.concurrent.TimeoutException;41import java.util.concurrent.atomic.AtomicLong;42import java.util.concurrent.ThreadFactory;43import java.util.concurrent.TimeUnit;44import java.util.concurrent.atomic.AtomicInteger;45import java.util.concurrent.atomic.AtomicReference;46import java.util.concurrent.atomic.AtomicBoolean;47import java.util.concurrent.locks.Lock;48import java.util.concurrent.locks.ReentrantLock;49import java.util.concurrent.locks.Condition;50import java.util.concurrent.ExecutionException;51import java.util.concurrent.TimeoutException;52import java.util.concurrent.atomic.AtomicLong;53import java.util.concurrent.ThreadFactory;54import java.util.concurrent.TimeUnit;55import java.util.concurrent.atomic.AtomicInteger;

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal.util;2import java.util.Date;3public class MockUtil {4 public static void main(String[] args) {5 Timer timer = new Timer();6 timer.start();7 System.out.println(timer);8 }9}10package org.mockito.internal.util;11import java.util.Date;12public class Timer {13 private Date start;14 public void start() {15 this.start = new Date();16 }17 public String toString() {18 return "Timer started at: " + start;19 }20}

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.coding;2import java.util.concurrent.TimeUnit;3public class InputIllegalCatchExtendedCheckWithStartMethod {4 public void foo() {5 org.mockito.internal.util.Timer timer = new org.mockito.internal.util.Timer();6 timer.start();7 try {8 TimeUnit.SECONDS.sleep(1);9 } catch (InterruptedException e) {10 e.printStackTrace();11 }12 }13}14package com.puppycrawl.tools.checkstyle.checks.coding;15import java.util.concurrent.TimeUnit;16public class InputIllegalCatchExtendedCheckWithStartMethod {17 public void foo() {18 org.mockito.internal.util.Timer timer = new org.mockito.internal.util.Timer();19 timer.start();20 try {21 TimeUnit.SECONDS.sleep(1);22 } catch (InterruptedException e) {23 e.printStackTrace();24 }25 }26}

Full Screen

Full Screen

start

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.coding;2import org.mockito.internal.util.Timer;3public class InputIllegalThrowsCheck1 {4 public void method1() {5 Timer.start();6 }7}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in Timer

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful