Example usage for org.apache.commons.lang3.time DateUtils addHours

List of usage examples for org.apache.commons.lang3.time DateUtils addHours

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils addHours.

Prototype

public static Date addHours(final Date date, final int amount) 

Source Link

Document

Adds a number of hours to a date returning a new object.

Usage

From source file:com.gargoylesoftware.htmlunit.CacheTest.java

/**
 * Ensures {@link WebResponse#cleanUp()} is called on calling {@link Cache#clear()}.
 * @throws Exception if the test fails//w ww  .  j a  v a  2  s. c om
 */
@Test
public void cleanUpOnClear() throws Exception {
    final WebRequest request1 = new WebRequest(URL_FIRST, HttpMethod.GET);
    final WebResponse response1 = createMock(WebResponse.class);
    expect(response1.getWebRequest()).andReturn(request1);
    expectLastCall().atLeastOnce();
    expect(response1.getResponseHeaderValue("Last-Modified")).andReturn(null);
    expect(response1.getResponseHeaderValue("Expires"))
            .andReturn(StringUtils.formatHttpDate(DateUtils.addHours(new Date(), 1)));

    response1.cleanUp();

    replay(response1);

    final Cache cache = new Cache();
    cache.cacheIfPossible(request1, response1, null);

    cache.clear();

    verify(response1);
}

From source file:gov.nih.nci.caintegrator.mockito.AbstractMockitoTest.java

private void setUpWorkspaceService() throws Exception {
    workspaceService = mock(WorkspaceService.class);
    when(workspaceService.getWorkspace()).thenAnswer(new Answer<UserWorkspace>() {
        @Override/*from   www.jav  a  2s . c o m*/
        public UserWorkspace answer(InvocationOnMock invocation) throws Throwable {
            UserWorkspace workspace = new UserWorkspace();
            workspace.setDefaultSubscription(getStudySubscription());
            workspace.getSubscriptionCollection().add(workspace.getDefaultSubscription());
            if (studySubscription != null) {
                workspace.getSubscriptionCollection().add(studySubscription);
            }
            workspace.setUsername("username");
            return workspace;
        }
    });
    when(workspaceService.retrieveStudyConfigurationJobs(any(UserWorkspace.class)))
            .thenAnswer(new Answer<Set<StudyConfiguration>>() {
                @Override
                public Set<StudyConfiguration> answer(InvocationOnMock invocation) throws Throwable {
                    Set<StudyConfiguration> results = new HashSet<StudyConfiguration>();
                    StudyConfiguration config = new StudyConfiguration();
                    config.setStatus(Status.PROCESSING);
                    Date today = new Date();
                    config.setDeploymentStartDate(DateUtils.addHours(today, -13));
                    results.add(config);

                    config = new StudyConfiguration();
                    config.setStatus(Status.PROCESSING);
                    config.setDeploymentStartDate(today);
                    results.add(config);
                    return results;
                }
            });
    when(workspaceService.createDisplayableStudySummary(any(Study.class)))
            .thenAnswer(new Answer<DisplayableStudySummary>() {
                @Override
                public DisplayableStudySummary answer(InvocationOnMock invocation) throws Throwable {
                    Study study = (Study) invocation.getArguments()[0];
                    return new DisplayableStudySummary(study);
                }
            });
    when(workspaceService.getRefreshedEntity(any(AbstractCaIntegrator2Object.class)))
            .thenAnswer(new Answer<AbstractCaIntegrator2Object>() {
                @Override
                public AbstractCaIntegrator2Object answer(InvocationOnMock invocation) throws Throwable {
                    AbstractCaIntegrator2Object obj = (AbstractCaIntegrator2Object) invocation
                            .getArguments()[0];
                    return obj;
                }
            });
    when(workspaceService.getWorkspaceReadOnly()).thenAnswer(new Answer<UserWorkspace>() {
        @Override
        public UserWorkspace answer(InvocationOnMock invocation) throws Throwable {
            UserWorkspace workspace = new UserWorkspace();
            workspace.setDefaultSubscription(getStudySubscription());
            workspace.getSubscriptionCollection().add(workspace.getDefaultSubscription());
            workspace.setUsername(UserWorkspace.ANONYMOUS_USER_NAME);
            return workspace;
        }
    });
    when(workspaceService.retrievePlatformsInStudy(any(Study.class))).thenReturn(new HashSet<Platform>());
}

From source file:com.feilong.core.date.DateUtil.java

/**
 *  <code>date</code>?? ({@link Calendar#HOUR_OF_DAY} 24??,??),,.
 * /* w ww.j a v  a 2  s.  c om*/
 * <p>
 * ?<code>date</code>??
 * </p>
 * 
 * <h3>:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * DateUtil.addHour(2012-06-29 00:46:24,5)   =2012-06-29 05:46:24
 * DateUtil.addHour(2012-06-29 00:46:24,-5)  =2012-06-28 19:46:24
 * </pre>
 * 
 * </blockquote>
 * <p>
 * {@link Calendar#HOUR}:12?? <br>
 * {@link Calendar#HOUR_OF_DAY}:24??
 * </p>
 * 
 * @param date
 *            ?
 * @param hour
 *            the hour,<span style="color:red">?</span>,??<br>
 * @return  <code>date</code>null, {@link java.lang.IllegalArgumentException}
 * @see org.apache.commons.lang3.time.DateUtils#addHours(Date, int)
 */
public static Date addHour(Date date, int hour) {
    return DateUtils.addHours(date, hour);
}

From source file:com.formkiq.core.service.UserServiceImplTest.java

/**
 * testUpdatePassword04().// w  ww  . j  a  v a2 s.  co m
 * ResetToken is expired
 */
@Test
public void testUpdatePassword04() {
    // given
    String email = "me@formkiq.com";
    final int resetInsertDate = 25;
    Date now = new Date();
    String newPassword = "new";
    String resettoken = "old";

    String resetToken = this.service.generatedSecuredPasswordHash(resettoken);

    // when
    expect(this.user.getResetToken()).andReturn(resetToken);
    expect(this.user.getResetInsertedDate()).andReturn(DateUtils.addHours(now, -resetInsertDate));
    expect(this.userDao.findUser(email)).andReturn(this.user);
    expect(this.dateService.now()).andReturn(now);

    replayAll();

    try {
        this.service.updatePassword(email, resettoken, newPassword);
        fail();
    } catch (Exception e) {
        // then
        verifyAll();

        assertEquals("Invalid Old Password or Reset Token", e.getMessage());
    }
}

From source file:np.com.drose.parkgarau.ws.resource.v1.impl.ParkGarauWSIMPL.java

private String issueToken(String userName) {
    Optional<Token> tkn1 = Optional.ofNullable(tokenParkGarauService.findWithAnotherObjectCode(userName));
    if (tkn1.isPresent()) {
        Token tkn = tkn1.get();//from   w ww.j  a va2  s .co m
        tkn.setActive(false);
        tkn.getAuditInfo().setModifiedOn(new Date());
        tkn.getAuditInfo().setModifiedBy(userName);
        tokenParkGarauService.edit(tkn);
    }
    //String token = UUID.randomUUID().toString();
    Random random = new SecureRandom();
    String token = new BigInteger(130, random).toString(32);
    LOG.log(Level.INFO, "ISSUE TOKEN .....{0}", token);
    this.tokenParkGarauService
            .add(new Token(userName, token, DateUtils.addHours(new Date(), 12), new AuditInfo()));
    LOG.log(Level.INFO, "successfully inserted token {0}", userName);
    return token;
}

From source file:org.apache.nifi.processors.aws.s3.TestListS3.java

@Test
public void testListIgnoreByMinAge() throws IOException {
    runner.setProperty(ListS3.REGION, "eu-west-1");
    runner.setProperty(ListS3.BUCKET, "test-bucket");
    runner.setProperty(ListS3.MIN_AGE, "30 sec");

    Date lastModifiedNow = new Date();
    Date lastModifiedMinus1Hour = DateUtils.addHours(lastModifiedNow, -1);
    Date lastModifiedMinus3Hour = DateUtils.addHours(lastModifiedNow, -3);
    ObjectListing objectListing = new ObjectListing();
    S3ObjectSummary objectSummary1 = new S3ObjectSummary();
    objectSummary1.setBucketName("test-bucket");
    objectSummary1.setKey("minus-3hour");
    objectSummary1.setLastModified(lastModifiedMinus3Hour);
    objectListing.getObjectSummaries().add(objectSummary1);
    S3ObjectSummary objectSummary2 = new S3ObjectSummary();
    objectSummary2.setBucketName("test-bucket");
    objectSummary2.setKey("minus-1hour");
    objectSummary2.setLastModified(lastModifiedMinus1Hour);
    objectListing.getObjectSummaries().add(objectSummary2);
    S3ObjectSummary objectSummary3 = new S3ObjectSummary();
    objectSummary3.setBucketName("test-bucket");
    objectSummary3.setKey("now");
    objectSummary3.setLastModified(lastModifiedNow);
    objectListing.getObjectSummaries().add(objectSummary3);
    Mockito.when(mockS3Client.listObjects(Mockito.any(ListObjectsRequest.class))).thenReturn(objectListing);

    Map<String, String> stateMap = new HashMap<>();
    String previousTimestamp = String.valueOf(lastModifiedMinus3Hour.getTime());
    stateMap.put(ListS3.CURRENT_TIMESTAMP, previousTimestamp);
    stateMap.put(ListS3.CURRENT_KEY_PREFIX + "0", "minus-3hour");
    runner.getStateManager().setState(stateMap, Scope.CLUSTER);

    runner.run();/* www. j  av  a 2s  . c o  m*/

    ArgumentCaptor<ListObjectsRequest> captureRequest = ArgumentCaptor.forClass(ListObjectsRequest.class);
    Mockito.verify(mockS3Client, Mockito.times(1)).listObjects(captureRequest.capture());
    ListObjectsRequest request = captureRequest.getValue();
    assertEquals("test-bucket", request.getBucketName());
    Mockito.verify(mockS3Client, Mockito.never()).listVersions(Mockito.any());

    runner.assertAllFlowFilesTransferred(ListS3.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ListS3.REL_SUCCESS);
    MockFlowFile ff0 = flowFiles.get(0);
    ff0.assertAttributeEquals("filename", "minus-1hour");
    ff0.assertAttributeEquals("s3.bucket", "test-bucket");
    String lastModifiedTimestamp = String.valueOf(lastModifiedMinus1Hour.getTime());
    ff0.assertAttributeEquals("s3.lastModified", lastModifiedTimestamp);
    runner.getStateManager().assertStateEquals(ListS3.CURRENT_TIMESTAMP, lastModifiedTimestamp, Scope.CLUSTER);
}

From source file:org.egov.pgr.service.CitizenComplaintDataPublisher.java

public void onRegistration(Complaint complaint) {
    Integer slaHours = complaint.getComplaintType().getSlaHours();
    String messageHeader;/*from   w w w . j  ava  2 s . c om*/
    if (COMPLAINT_REGISTERED.equals(complaint.getStatus().getName()))
        messageHeader = "Grievance Recorded";
    else
        messageHeader = "Grievance Redressal";

    StringBuilder detailedMessage = new StringBuilder().append("Complaint Type : ")
            .append(complaint.getComplaintType().getName()).append(" in ")
            .append(complaint.getLocation().getName());
    PortalInboxBuilder portalInboxBuilder = new PortalInboxBuilder(moduleService.getModuleByName(MODULE_NAME),
            complaint.getStateType(), complaint.getCrn(), complaint.getCrn(), complaint.getId(), messageHeader,
            detailedMessage.toString(), String.format(COMPLAINT_UPDATE_URL, complaint.getCrn()), false,
            complaint.getStatus().getName(),
            DateUtils.addHours(new Date(),
                    slaHours == null ? configurationService.getDefaultComplaintResolutionTime() : slaHours),
            complaint.getState(), Arrays.asList(securityUtils.getCurrentUser()));

    portalInboxService.pushInboxMessage(portalInboxBuilder.build());
}

From source file:org.egov.tl.service.LicenseCitizenPortalService.java

public void onCreate(TradeLicense tradeLicense) {
    final Module module = moduleService.getModuleByName(TRADE_LICENSE);
    final PortalInboxBuilder portalInboxBuilder = new PortalInboxBuilder(module,
            tradeLicense.getState().getNatureOfTask(), tradeLicense.getApplicationNumber(),
            tradeLicense.getLicenseNumber() != null ? tradeLicense.getLicenseNumber()
                    : tradeLicense.getApplicationNumber(),
            tradeLicense.getId(), tradeLicense.getStateType(), getDetailedMessage(tradeLicense),
            format(APPLICATION_VIEW_URL, tradeLicense.getUid()), tradeLicense.transitionCompleted(),
            tradeLicense.getStatus().getName(),
            DateUtils.addHours(new Date(), licenseUtils.getSlaForAppType(tradeLicense.getLicenseAppType())),
            tradeLicense.getState(), Arrays.asList(securityUtils.getCurrentUser()));
    portalInboxService.pushInboxMessage(portalInboxBuilder.build());
}

From source file:org.kuali.coeus.sys.impl.scheduling.ScheduleServiceImpl.java

/**
 * This is helper method, wraps date with time accurately in java.util.Date (milliseconds).
 * /*from   w  w  w.  ja  v a 2 s  .  com*/
 * @param date to be wrapped.
 * @param time to be added to date.
 * @return wrapped date &amp; time.
 */
protected Date wrapTime(Date date, Time24HrFmt time) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    int hour = calendar.get(Calendar.HOUR);
    int min = calendar.get(Calendar.MINUTE);
    int am_pm = calendar.get(Calendar.AM_PM);
    if (am_pm == Calendar.AM) {
        date = DateUtils.addHours(date, -hour);
        date = DateUtils.addMinutes(date, -min);
    } else {
        date = DateUtils.addHours(date, -hour - 12);
        date = DateUtils.addMinutes(date, -min);
    }
    if (null != time) {
        date = DateUtils.addHours(date, new Integer(time.getHours()));
        date = DateUtils.addMinutes(date, new Integer(time.getMinutes()));
    }
    return date;
}

From source file:org.mashupmedia.service.LibraryUpdateManagerImpl.java

@Override
public void updateLibrary(Library library) {

    library = libraryManager.getLibrary(library.getId());

    if (!library.isEnabled()) {
        logger.info("Library is disabled, will not update:" + library.toString());
        return;/*from   w  w  w .  j ava  2 s  .com*/
    }

    Date lastUpdated = library.getUpdatedOn();
    Date date = new Date();
    date = DateUtils.addHours(date, -LIBRARY_UPDATE_TIMEOUT_HOURS);

    if (library.getLibraryStatusType() == LibraryStatusType.WORKING && date.before(lastUpdated)) {
        logger.info("Library is already updating, exiting:" + library.toString());
        return;
    }

    try {
        library.setLibraryStatusType(LibraryStatusType.WORKING);
        libraryManager.saveLibrary(library);

        Location location = library.getLocation();
        File folder = new File(location.getPath());
        if (!folder.isDirectory()) {
            logger.error("Media library points to a file not a directory, exiting...");
            return;
        }

        processLibrary(library);

        library.setLibraryStatusType(LibraryStatusType.OK);

    } catch (Exception e) {
        logger.error("Error updating library", e);
        library.setLibraryStatusType(LibraryStatusType.ERROR);
    } finally {
        libraryManager.saveLibrary(library);
    }

}