Java Code Examples for org.apache.commons.lang3.time.DateUtils#addSeconds()

The following examples show how to use org.apache.commons.lang3.time.DateUtils#addSeconds() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IdentityServiceTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@WatchLogger(loggerNames = {INDENTITY_LOGGER}, level = "INFO")
public void testUnsuccessfulLoginAfterFailureWithoutDelay() {
  // given
  User user = identityService.newUser("johndoe");
  user.setPassword("xxx");
  identityService.saveUser(user);

  Date now = ClockUtil.getCurrentTime();
  ClockUtil.setCurrentTime(now);
  assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));

  ClockUtil.setCurrentTime(DateUtils.addSeconds(now, 1));
  Date expectedLockExpitation = DateUtils.addSeconds(now, 3);

  // when try again before exprTime
  assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));

  // then
  assertThat(loggingRule.getFilteredLog(INDENTITY_LOGGER, "The lock will expire at " + expectedLockExpitation).size()).isEqualTo(1);
}
 
Example 2
Source File: LoginAttemptsTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsuccessfulAttemptsResultInLockedUser() throws ParseException {
  // given
  User user = identityService.newUser("johndoe");
  user.setPassword("xxx");
  identityService.saveUser(user);

  Date now = sdf.parse("2000-01-24T13:00:00");
  ClockUtil.setCurrentTime(now);
  // when
  for (int i = 0; i <= 6; i++) {
    assertThat(identityService.checkPassword("johndoe", "invalid pwd")).isFalse();
    now = DateUtils.addSeconds(now, 5);
    ClockUtil.setCurrentTime(now);
  }

  // then
  assertThat(loggingRule.getFilteredLog(INDENTITY_LOGGER, "The user with id 'johndoe' is permanently locked.").size()).isEqualTo(1);
}
 
Example 3
Source File: HistoryCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testLessThanThresholdWithinBatchWindowAfterMidnight() throws ParseException {
  //given
  prepareData(5);

  //we're within batch window, but batch window passes midnight
  Date date = addDays(new Date(), 1);
  ClockUtil.setCurrentTime(DateUtils.setMinutes(DateUtils.setHours(date, 0), 10));  // 00:10 tomorrow
  processEngineConfiguration.setHistoryCleanupBatchWindowStartTime("23:00");
  processEngineConfiguration.setHistoryCleanupBatchWindowEndTime("01:00");
  processEngineConfiguration.initHistoryCleanup();

  //when
  runHistoryCleanup(false);

  //then
  final List<Job> historyCleanupJobs = historyService.findHistoryCleanupJobs();
  for (Job job : historyCleanupJobs) {
    JobEntity jobEntity = (JobEntity) job;
    HistoryCleanupJobHandlerConfiguration configuration = getConfiguration(jobEntity);

    //job rescheduled till current time + delay
    Date nextRun = getNextRunWithDelay(ClockUtil.getCurrentTime(), 0);
    assertTrue(jobEntity.getDuedate().equals(nextRun) || jobEntity.getDuedate().after(nextRun));
    Date nextRunMax = DateUtils.addSeconds(ClockUtil.getCurrentTime(), HistoryCleanupJobHandlerConfiguration.MAX_DELAY);
    assertTrue(jobEntity.getDuedate().before(nextRunMax));

    //countEmptyRuns incremented
    assertEquals(1, configuration.getCountEmptyRuns());
  }

  //data is still removed
  assertResult(0);
}
 
Example 4
Source File: LockServiceImpl.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
@Override
public boolean acquireLock(){
    String clusterName = config.getClusterName();
    String nodeName = config.getNodeName();
    Date expireTime = DateUtils.addSeconds( new Date(), config.getHeartbeatMaximumPauseSeconds() );
    boolean isAcquired = dao.create( clusterName, nodeName, expireTime );
    return isAcquired;
}
 
Example 5
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean getCanPostMessage(ChatChannel channel)
{
    // We don't currently support posting messages by anonymous users
    if (sessionManager.getCurrentSessionUserId() == null)
        return false;

    boolean allowed = false;
    if (channel != null) {
        allowed = can(ChatFunctions.CHAT_FUNCTION_NEW, channel.getContext());
        if (allowed) {
            // check the dates if they are set (https://jira.sakaiproject.org/browse/SAK-24207)
            Date today = new Date();
            Date start = channel.getStartDate();
            if (start == null) {
                start = today;
            } else {
                // fix up the date to shift to be beginning or end of the day (drop any time component)
                start = DateUtils.truncate(start, Calendar.DATE);
            }
            Date end = channel.getEndDate();
            if (end == null) {
                end = today;
            } else {
                // fix up the date to shift to be beginning or end of the day (drop any time component)
                end = DateUtils.truncate(end, Calendar.DATE);
                end = DateUtils.addSeconds(end, 86398); // just short of a full day in seconds
            }
            if ( today.before(start) || today.after(end) ) {
                // today is outside the configured dates so no posting allowed
                allowed = false;
            }
        }
    }
    return allowed;
}
 
Example 6
Source File: DecoratedChatChannel.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void setEndDate(Date endDate) {
    if (endDate != null) {
        // fix up the date to shift to be beginning or end of the day (drop any time component)
        endDate = DateUtils.truncate(endDate, Calendar.DATE);
        endDate = DateUtils.addSeconds(endDate, 86398); // just short of a full day in seconds
    }
    this.endDate = endDate;
}
 
Example 7
Source File: HistoryCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testLessThanThresholdWithinBatchWindow() {
  //given
  prepareData(5);

  //we're within batch window
  Date now = new Date();
  ClockUtil.setCurrentTime(now);
  processEngineConfiguration.setHistoryCleanupBatchWindowStartTime(new SimpleDateFormat("HH:mm").format(now));
  processEngineConfiguration.setHistoryCleanupBatchWindowEndTime(new SimpleDateFormat("HH:mm").format(DateUtils.addHours(now, HISTORY_TIME_TO_LIVE)));
  processEngineConfiguration.initHistoryCleanup();

  //when
  runHistoryCleanup();

  //then
  final List<Job> historyCleanupJobs = historyService.findHistoryCleanupJobs();
  for (Job job : historyCleanupJobs) {
    JobEntity jobEntity = (JobEntity) job;
    HistoryCleanupJobHandlerConfiguration configuration = getConfiguration(jobEntity);

    //job rescheduled till current time + delay
    Date nextRun = getNextRunWithDelay(ClockUtil.getCurrentTime(), 0);
    assertTrue(jobEntity.getDuedate().equals(nextRun) || jobEntity.getDuedate().after(nextRun));
    Date nextRunMax = DateUtils.addSeconds(ClockUtil.getCurrentTime(), HistoryCleanupJobHandlerConfiguration.MAX_DELAY);
    assertTrue(jobEntity.getDuedate().before(nextRunMax));

    //countEmptyRuns incremented
    assertEquals(1, configuration.getCountEmptyRuns());
  }

  //data is still removed
  assertResult(0);
}
 
Example 8
Source File: CheckInApiController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/check-in/{eventName}/offline-identifiers")
public List<Integer> getOfflineIdentifiers(@PathVariable("eventName") String eventName,
                                          @RequestParam(value = "changedSince", required = false) Long changedSince,
                                          HttpServletResponse resp,
                                          Principal principal) {
    Date since = changedSince == null ? new Date(0) : DateUtils.addSeconds(new Date(changedSince), -1);
    Optional<List<Integer>> ids = eventManager.getOptionalEventAndOrganizationIdByName(eventName, principal.getName())
        .filter(checkInManager.isOfflineCheckInEnabled())
        .map(event -> checkInManager.getAttendeesIdentifiers(event, since, principal.getName()));

    resp.setHeader(ALFIO_TIMESTAMP_HEADER, ids.isPresent() ? Long.toString(new Date().getTime()) : "0");
    return ids.orElse(Collections.emptyList());
}
 
Example 9
Source File: HistoryCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("CAM-10055")
public void testLessThanThresholdWithinBatchWindowAfterMidnightDaylightSaving() throws ParseException {
  //given
  prepareData(5);

  //we're within batch window, but batch window passes midnight
  ClockUtil.setCurrentTime(sdf.parse("2018-05-14T00:10:00"));  // 00:10
  processEngineConfiguration.setHistoryCleanupBatchWindowStartTime("23:00CET");
  processEngineConfiguration.setHistoryCleanupBatchWindowEndTime("01:00CET");
  processEngineConfiguration.initHistoryCleanup();

  //when
  runHistoryCleanup(false);

  //then
  final List<Job> historyCleanupJobs = historyService.findHistoryCleanupJobs();
  for (Job job : historyCleanupJobs) {
    JobEntity jobEntity = (JobEntity) job;
    HistoryCleanupJobHandlerConfiguration configuration = getConfiguration(jobEntity);

    //job rescheduled till current time + delay
    Date nextRun = getNextRunWithDelay(ClockUtil.getCurrentTime(), 0);
    assertTrue(jobEntity.getDuedate().equals(nextRun) || jobEntity.getDuedate().after(nextRun));
    Date nextRunMax = DateUtils.addSeconds(ClockUtil.getCurrentTime(), HistoryCleanupJobHandlerConfiguration.MAX_DELAY);
    assertTrue(jobEntity.getDuedate().before(nextRunMax));

    //countEmptyRuns incremented
    assertEquals(1, configuration.getCountEmptyRuns());
  }

  //data is still removed
  assertResult(0);
}
 
Example 10
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean getCanPostMessage(ChatChannel channel)
{
    // We don't currently support posting messages by anonymous users
    if (sessionManager.getCurrentSessionUserId() == null)
        return false;

    boolean allowed = false;
    if (channel != null) {
        allowed = can(ChatFunctions.CHAT_FUNCTION_NEW, channel.getContext());
        if (allowed) {
            // check the dates if they are set (https://jira.sakaiproject.org/browse/SAK-24207)
            Date today = new Date();
            Date start = channel.getStartDate();
            if (start == null) {
                start = today;
            } else {
                // fix up the date to shift to be beginning or end of the day (drop any time component)
                start = DateUtils.truncate(start, Calendar.DATE);
            }
            Date end = channel.getEndDate();
            if (end == null) {
                end = today;
            } else {
                // fix up the date to shift to be beginning or end of the day (drop any time component)
                end = DateUtils.truncate(end, Calendar.DATE);
                end = DateUtils.addSeconds(end, 86398); // just short of a full day in seconds
            }
            if ( today.before(start) || today.after(end) ) {
                // today is outside the configured dates so no posting allowed
                allowed = false;
            }
        }
    }
    return allowed;
}
 
Example 11
Source File: HistoryCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testLessThanThresholdWithinBatchWindowBeforeMidnight() {
  //given
  prepareData(5);

  //we're within batch window, but batch window passes midnight
  Date date = new Date();
  ClockUtil.setCurrentTime(DateUtils.setMinutes(DateUtils.setHours(date, 23), 10));  //23:10
  processEngineConfiguration.setHistoryCleanupBatchWindowStartTime("23:00");
  processEngineConfiguration.setHistoryCleanupBatchWindowEndTime("01:00");
  processEngineConfiguration.initHistoryCleanup();

  //when
  runHistoryCleanup();

  //then
  final List<Job> historyCleanupJobs = historyService.findHistoryCleanupJobs();
  for (Job job : historyCleanupJobs) {
    JobEntity jobEntity = (JobEntity) job;
    HistoryCleanupJobHandlerConfiguration configuration = getConfiguration(jobEntity);

    //job rescheduled till current time + delay
    Date nextRun = getNextRunWithDelay(ClockUtil.getCurrentTime(), 0);
    assertTrue(jobEntity.getDuedate().equals(nextRun) || jobEntity.getDuedate().after(nextRun));
    Date nextRunMax = DateUtils.addSeconds(ClockUtil.getCurrentTime(), HistoryCleanupJobHandlerConfiguration.MAX_DELAY);
    assertTrue(jobEntity.getDuedate().before(nextRunMax));

    //countEmptyRuns incremented
    assertEquals(1, configuration.getCountEmptyRuns());
  }

  //data is still removed
  assertResult(0);
}
 
Example 12
Source File: LockServiceImpl.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
@Override
public boolean refreshOwnLock(){
    String clusterName = config.getClusterName();
    String nodeName = config.getNodeName();
    Date expireTime = DateUtils.addSeconds( new Date(), config.getHeartbeatMaximumPauseSeconds() );
    boolean isRefreshed = dao.updateExpireTime( clusterName, nodeName, expireTime );
    return isRefreshed;
}
 
Example 13
Source File: GatewayFlowRuleControllerTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateFlowRule() throws Exception {
    String path = "/gateway/flow/save.json";

    // Add one entity into memory repository for update
    GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity();
    addEntity.setId(1L);
    addEntity.setApp(TEST_APP);
    addEntity.setIp(TEST_IP);
    addEntity.setPort(TEST_PORT);
    addEntity.setResource("httpbin_route");
    addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID);
    addEntity.setGrade(FLOW_GRADE_QPS);
    addEntity.setCount(5D);
    addEntity.setInterval(30L);
    addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND);
    addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT);
    addEntity.setBurst(0);
    addEntity.setMaxQueueingTimeoutMs(0);
    Date date = new Date();
    // To make the gmtModified different when do update
    date = DateUtils.addSeconds(date, -1);
    addEntity.setGmtCreate(date);
    addEntity.setGmtModified(date);

    GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity();
    addEntity.setParamItem(addItemEntity);
    addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP);

    repository.save(addEntity);

    UpdateFlowRuleReqVo reqVo = new UpdateFlowRuleReqVo();
    reqVo.setId(addEntity.getId());
    reqVo.setApp(TEST_APP);
    reqVo.setGrade(FLOW_GRADE_QPS);
    reqVo.setCount(6D);
    reqVo.setInterval(2L);
    reqVo.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE);
    reqVo.setControlBehavior(CONTROL_BEHAVIOR_RATE_LIMITER);
    reqVo.setMaxQueueingTimeoutMs(500);

    GatewayParamFlowItemVo itemVo = new GatewayParamFlowItemVo();
    reqVo.setParamItem(itemVo);
    itemVo.setParseStrategy(PARAM_PARSE_STRATEGY_URL_PARAM);
    itemVo.setFieldName("pa");

    given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true);

    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path);
    requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON);

    // Do controller logic
    MvcResult mvcResult = mockMvc.perform(requestBuilder)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print()).andReturn();

    // Verify the modifyGatewayFlowRules method has been called
    verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any());

    Result<GatewayFlowRuleEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<GatewayFlowRuleEntity>>() {
    });
    assertTrue(result.isSuccess());

    GatewayFlowRuleEntity entity = result.getData();
    assertNotNull(entity);
    assertEquals(RESOURCE_MODE_ROUTE_ID, entity.getResourceMode().intValue());
    assertEquals("httpbin_route", entity.getResource());
    assertEquals(6D, entity.getCount().doubleValue(), 0);
    assertEquals(2L, entity.getInterval().longValue());
    assertEquals(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE, entity.getIntervalUnit().intValue());
    assertEquals(CONTROL_BEHAVIOR_RATE_LIMITER, entity.getControlBehavior().intValue());
    assertEquals(0, entity.getBurst().intValue());
    assertEquals(500, entity.getMaxQueueingTimeoutMs().intValue());
    assertEquals(date, entity.getGmtCreate());
    // To make sure gmtModified has been set and it's different from gmtCreate
    assertNotNull(entity.getGmtModified());
    assertNotEquals(entity.getGmtCreate(), entity.getGmtModified());

    // Verify the entity which is update in memory repository
    GatewayParamFlowItemEntity itemEntity = entity.getParamItem();
    assertEquals(PARAM_PARSE_STRATEGY_URL_PARAM, itemEntity.getParseStrategy().intValue());
    assertEquals("pa", itemEntity.getFieldName());
}
 
Example 14
Source File: GatewayApiControllerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateApi() throws Exception {
    String path = "/gateway/api/save.json";

    // Add one entity to memory repository for update
    ApiDefinitionEntity addEntity = new ApiDefinitionEntity();
    addEntity.setApp(TEST_APP);
    addEntity.setIp(TEST_IP);
    addEntity.setPort(TEST_PORT);
    addEntity.setApiName("bbb");
    Date date = new Date();
    // To make the gmtModified different when do update
    date = DateUtils.addSeconds(date, -1);
    addEntity.setGmtCreate(date);
    addEntity.setGmtModified(date);
    Set<ApiPredicateItemEntity> addRedicateItemEntities = new HashSet<>();
    addEntity.setPredicateItems(addRedicateItemEntities);
    ApiPredicateItemEntity addPredicateItemEntity = new ApiPredicateItemEntity();
    addPredicateItemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT);
    addPredicateItemEntity.setPattern("/order");
    addEntity = repository.save(addEntity);

    UpdateApiReqVo reqVo = new UpdateApiReqVo();
    reqVo.setId(addEntity.getId());
    reqVo.setApp(TEST_APP);
    List<ApiPredicateItemVo> itemVos = new ArrayList<>();
    ApiPredicateItemVo itemVo = new ApiPredicateItemVo();
    itemVo.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX);
    itemVo.setPattern("/my_order");
    itemVos.add(itemVo);
    reqVo.setPredicateItems(itemVos);

    given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true);

    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path);
    requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON);

    // Do controller logic
    MvcResult mvcResult = mockMvc.perform(requestBuilder)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print()).andReturn();

    // Verify the modifyApis method has been called
    verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any());

    Result<ApiDefinitionEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<ApiDefinitionEntity>>() {});
    assertTrue(result.isSuccess());

    ApiDefinitionEntity entity = result.getData();
    assertNotNull(entity);
    assertEquals("bbb", entity.getApiName());
    assertEquals(date, entity.getGmtCreate());
    // To make sure gmtModified has been set and it's different from gmtCreate
    assertNotNull(entity.getGmtModified());
    assertNotEquals(entity.getGmtCreate(), entity.getGmtModified());

    Set<ApiPredicateItemEntity> predicateItemEntities = entity.getPredicateItems();
    assertEquals(1, predicateItemEntities.size());
    ApiPredicateItemEntity predicateItemEntity = predicateItemEntities.iterator().next();
    assertEquals(URL_MATCH_STRATEGY_PREFIX, predicateItemEntity.getMatchStrategy().intValue());
    assertEquals("/my_order", predicateItemEntity.getPattern());

    // Verify the entity which is update in memory repository
    List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP);
    assertEquals(1, entitiesInMem.size());
    assertEquals(entity, entitiesInMem.get(0));
}
 
Example 15
Source File: GatewayApiControllerTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateApi() throws Exception {
    String path = "/gateway/api/save.json";

    // Add one entity to memory repository for update
    ApiDefinitionEntity addEntity = new ApiDefinitionEntity();
    addEntity.setApp(TEST_APP);
    addEntity.setIp(TEST_IP);
    addEntity.setPort(TEST_PORT);
    addEntity.setApiName("bbb");
    Date date = new Date();
    // To make the gmtModified different when do update
    date = DateUtils.addSeconds(date, -1);
    addEntity.setGmtCreate(date);
    addEntity.setGmtModified(date);
    Set<ApiPredicateItemEntity> addRedicateItemEntities = new HashSet<>();
    addEntity.setPredicateItems(addRedicateItemEntities);
    ApiPredicateItemEntity addPredicateItemEntity = new ApiPredicateItemEntity();
    addPredicateItemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT);
    addPredicateItemEntity.setPattern("/order");
    addEntity = repository.save(addEntity);

    UpdateApiReqVo reqVo = new UpdateApiReqVo();
    reqVo.setId(addEntity.getId());
    reqVo.setApp(TEST_APP);
    List<ApiPredicateItemVo> itemVos = new ArrayList<>();
    ApiPredicateItemVo itemVo = new ApiPredicateItemVo();
    itemVo.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX);
    itemVo.setPattern("/my_order");
    itemVos.add(itemVo);
    reqVo.setPredicateItems(itemVos);

    given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true);

    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path);
    requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON);

    // Do controller logic
    MvcResult mvcResult = mockMvc.perform(requestBuilder)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print()).andReturn();

    // Verify the modifyApis method has been called
    verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any());

    Result<ApiDefinitionEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<ApiDefinitionEntity>>() {});
    assertTrue(result.isSuccess());

    ApiDefinitionEntity entity = result.getData();
    assertNotNull(entity);
    assertEquals("bbb", entity.getApiName());
    assertEquals(date, entity.getGmtCreate());
    // To make sure gmtModified has been set and it's different from gmtCreate
    assertNotNull(entity.getGmtModified());
    assertNotEquals(entity.getGmtCreate(), entity.getGmtModified());

    Set<ApiPredicateItemEntity> predicateItemEntities = entity.getPredicateItems();
    assertEquals(1, predicateItemEntities.size());
    ApiPredicateItemEntity predicateItemEntity = predicateItemEntities.iterator().next();
    assertEquals(URL_MATCH_STRATEGY_PREFIX, predicateItemEntity.getMatchStrategy().intValue());
    assertEquals("/my_order", predicateItemEntity.getPattern());

    // Verify the entity which is update in memory repository
    List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP);
    assertEquals(1, entitiesInMem.size());
    assertEquals(entity, entitiesInMem.get(0));
}
 
Example 16
Source File: DateUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 终于到了,续一秒.
 */
public static Date addSeconds(@NotNull final Date date, int amount) {
	return DateUtils.addSeconds(date, amount);
}
 
Example 17
Source File: AliyunossProvider.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> createUploadToken(UploadTokenParam param) {
	
	Map<String, Object> result = new HashMap<>();
	
	PolicyConditions policyConds = new PolicyConditions();
	if(param.getFsizeMin() != null && param.getFsizeMax() != null){			
		policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, param.getFsizeMin(), param.getFsizeMax());
	}else{
		policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
	}
	if(param.getUploadDir() != null){			
		policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, param.getUploadDir());
	}
       
	if(StringUtils.isBlank(param.getCallbackHost())){
		param.setCallbackHost(host);
	}
	
	if(StringUtils.isBlank(param.getCallbackBody())){
		param.setCallbackBody(DEFAULT_CALLBACK_BODY);
	}
	
	Date expire = DateUtils.addSeconds(new Date(), (int)param.getExpires());
	String policy = ossClient.generatePostPolicy(expire, policyConds);
       String policyBase64 = null;
       String callbackBase64 = null;
       try {
       	policyBase64 = BinaryUtil.toBase64String(policy.getBytes(StandardCharsets.UTF_8.name()));
       	String callbackJson = param.getCallbackRuleAsJson();
       	if(callbackJson != null){
       		callbackBase64 = BinaryUtil.toBase64String(callbackJson.getBytes(StandardCharsets.UTF_8.name()));
       	}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	String signature = ossClient.calculatePostSignature(policy);
	
	result.put("OSSAccessKeyId", accessKeyId);
	result.put("policy", policyBase64);
	result.put("signature", signature);
	result.put("host", this.urlprefix);
	result.put("dir", param.getUploadDir());
	result.put("expire", String.valueOf(expire.getTime()));
	if(callbackBase64 != null){
		result.put("callback", callbackBase64);
	}
	return result;
}
 
Example 18
Source File: SchedTaskITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void deferred() {
    ImplementationTO taskJobDelegate = implementationService.read(
            IdRepoImplementationType.TASKJOB_DELEGATE, TestSampleJobDelegate.class.getSimpleName());
    assertNotNull(taskJobDelegate);

    SchedTaskTO task = new SchedTaskTO();
    task.setActive(true);
    task.setName("deferred");
    task.setJobDelegate(taskJobDelegate.getKey());

    Response response = taskService.create(TaskType.SCHEDULED, task);
    task = getObject(response.getLocation(), TaskService.class, SchedTaskTO.class);
    assertNotNull(task);

    Date initial = new Date();
    Date later = DateUtils.addSeconds(initial, 2);

    taskService.execute(new ExecuteQuery.Builder().key(task.getKey()).startAt(later).build());

    int i = 0;

    // wait for completion (executions incremented)
    do {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        task = taskService.read(TaskType.SCHEDULED, task.getKey(), true);

        assertNotNull(task);
        assertNotNull(task.getExecutions());

        i++;
    } while (task.getExecutions().isEmpty() && i < MAX_WAIT_SECONDS);

    PagedResult<ExecTO> execs =
            taskService.listExecutions(new ExecQuery.Builder().key(task.getKey()).build());
    assertEquals(1, execs.getTotalCount());
    assertTrue(execs.getResult().get(0).getStart().after(initial));
    // round 1 sec for safety
    assertTrue(DateUtils.addSeconds(execs.getResult().get(0).getStart(), 1).after(later));
}
 
Example 19
Source File: IncreaseCurrentTimeServiceTask.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  Date currentTime = (Date)execution.getVariable("currentTime");
  currentTime = DateUtils.addSeconds(currentTime, 1);
  ClockUtil.setCurrentTime(currentTime);
  execution.setVariable("currentTime", currentTime);
}
 
Example 20
Source File: GatewayFlowRuleControllerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeleteFlowRule() throws Exception {
    String path = "/gateway/flow/delete.json";

    // Add one entity into memory repository for delete
    GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity();
    addEntity.setId(1L);
    addEntity.setApp(TEST_APP);
    addEntity.setIp(TEST_IP);
    addEntity.setPort(TEST_PORT);
    addEntity.setResource("httpbin_route");
    addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID);
    addEntity.setGrade(FLOW_GRADE_QPS);
    addEntity.setCount(5D);
    addEntity.setInterval(30L);
    addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND);
    addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT);
    addEntity.setBurst(0);
    addEntity.setMaxQueueingTimeoutMs(0);
    Date date = new Date();
    date = DateUtils.addSeconds(date, -1);
    addEntity.setGmtCreate(date);
    addEntity.setGmtModified(date);

    GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity();
    addEntity.setParamItem(addItemEntity);
    addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP);

    repository.save(addEntity);

    given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true);

    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path);
    requestBuilder.param("id", String.valueOf(addEntity.getId()));

    // Do controller logic
    MvcResult mvcResult = mockMvc.perform(requestBuilder)
            .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();

    // Verify the modifyGatewayFlowRules method has been called
    verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any());

    // Verify the result
    Result<Long> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<Long>>() {});
    assertTrue(result.isSuccess());

    assertEquals(addEntity.getId(), result.getData());

    // Now no entities in memory
    List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP);
    assertEquals(0, entitiesInMem.size());
}