Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

In this page you can find the example usage for java.util Date setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:org.gnucash.android.ui.util.dialog.DateRangePickerDialogFragment.java

@Nullable
@Override//  w w w . ja v a  2 s.c  om
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_date_range_picker, container, false);
    ButterKnife.bind(this, view);

    Calendar nextYear = Calendar.getInstance();
    nextYear.add(Calendar.YEAR, 1);

    Date today = new Date();
    mCalendarPickerView.init(mStartRange, mEndRange).inMode(CalendarPickerView.SelectionMode.RANGE)
            .withSelectedDate(today);

    mDoneButton.setText(R.string.done_label);
    mDoneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<Date> selectedDates = mCalendarPickerView.getSelectedDates();
            Date startDate = selectedDates.get(0);
            // If only one day is selected (no interval) start and end should be the same (the selected one)
            Date endDate = selectedDates.size() > 1 ? selectedDates.get(selectedDates.size() - 1)
                    : new Date(startDate.getTime());
            // CaledarPicker returns the start of the selected day but we want all transactions of that day to be included.
            // Therefore we have to add 24 hours to the endDate.
            endDate.setTime(endDate.getTime() + ONE_DAY_IN_MILLIS);
            mDateRangeSetListener.onDateRangeSet(startDate, endDate);
            dismiss();
        }
    });

    mCancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });
    return view;
}

From source file:org.apache.ws.security.message.token.Timestamp.java

/**
 * Return true if the "Created" value is before the current time minus the timeToLive
 * argument, and if the Created value is not "in the future".
 * // w  w w  .  j av a  2 s. co m
 * @param timeToLive the value in seconds for the validity of the Created time
 * @param futureTimeToLive the value in seconds for the future validity of the Created time
 * @return true if the timestamp is before (now-timeToLive), false otherwise
 */
public boolean verifyCreated(int timeToLive, int futureTimeToLive) {
    Date validCreation = new Date();
    long currentTime = validCreation.getTime();
    if (futureTimeToLive > 0) {
        validCreation.setTime(currentTime + ((long) futureTimeToLive * 1000L));
    }
    // Check to see if the created time is in the future
    if (createdDate != null && createdDate.after(validCreation)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Validation of Timestamp: The message was created in the future!");
        }
        return false;
    }

    // Calculate the time that is allowed for the message to travel
    currentTime -= ((long) timeToLive * 1000L);
    validCreation.setTime(currentTime);

    // Validate the time it took the message to travel
    if (createdDate != null && createdDate.before(validCreation)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Validation of Timestamp: The message was created too long ago");
        }
        return false;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Validation of Timestamp: Everything is ok");
    }
    return true;
}

From source file:com.fluidops.iwb.ui.editor.SemWiki.java

/**
  * Save the given wiki content using the underlying wikistorage.
  * If the wiki page contains semantic links, these are stored as
  * well. In case an error occurs while saving semantic links
  * (e.g. due to read only repositories) the wiki page is not 
  * saved and an appropriate error message is thrown wrapped
  * in a exception./*from  ww w .  j  a  v a2 s.  com*/
  * 
  * @param comment
  * @param newContent
  * @return true if the wiki page was save, false, otherwise
  */
public boolean saveWiki(String comment, String newContent) {
    // just to make sure not to write based on old versions
    if (version != null)
        throw new RuntimeException("Editing of non-latest version is not allowed. Aborting Save.");

    if (newContent == null)
        return false;

    String oldContent = wikiText;

    ValueAccessLevel al = EndpointImpl.api().getUserManager().getValueAccessLevel(subject);
    if (al == null || al.compareTo(ValueAccessLevel.READ) <= 0) {
        logger.warn("Illegal access: wiki for resource " + subject + " cannot be saved.");
        return false; // no action
    }

    // now we can be sure the reader has at least WRITE_LIMITED access (i.e., al>=WRITE_LIMITED)

    WikiStorage ws = Wikimedia.getWikiStorage();
    WikiRevision latestRev = ws.getLatestRevision(subject);

    // assert limited write access
    if (SemWikiUtil.violatesWriteLimited(al, newContent)) {
        addClientUpdate(new FClientUpdate("alert('" + SemWikiUtil.WRITE_LIMITED_ERROR_MESSAGE + "')"));
        return false;
    }

    if (latestRev != null && renderTimestamp != null) {
        Date now = new Date();
        now.setTime(System.currentTimeMillis());
        if (latestRev.date.after(now))
            throw new RuntimeException("The Wiki modification date lies in the future, "
                    + "overriding would have no effect. Please fix your system "
                    + "clock settings or contact technical support");
        if (latestRev.date.after(renderTimestamp)) {
            String user = latestRev.user;
            if (user != null)
                user = user.replace("\\", "\\\\");

            throw new RuntimeException("The Wiki has been modified by user " + user + " in the meantime. "
                    + "Please save your edits in an external application, "
                    + "reload the page and apply the edits again.");
        }
    }

    // Bug 5812 - XSS in revision comment
    comment = StringEscapeUtils.escapeHtml(comment);

    if (comment == null || isEmpty(comment.trim()))
        comment = "(no comment)";

    try {
        ws.storeWikiContent(subject, newContent, comment, new Date());
    } catch (Exception e) {
        logger.warn("Error while storing the wiki content: " + e.getMessage());
        throw new RuntimeException(e);
    }
    try {
        SemWikiUtil.saveSemanticLinkDiff(oldContent, newContent, subject,
                Context.getFreshUserContext(ContextLabel.WIKI));
    } catch (RuntimeException e) {
        // undo the latest store operation if we cannot store semantic links   
        ws.deleteRevision(subject, ws.getLatestRevision(subject));
        throw e;
    }
    return true;
}

From source file:uk.co.anthonycampbell.java.mp4reader.reader.MP4InputStream.java

/**
 * Constructor./*  www.  j av  a 2  s .  c  om*/
 * 
 * @param file - the file to read.
 * @throws IllegalArgumentException - Provided file reference is invalid.
 * @throws IOException - Unable to read provided file reference.
 */
public MP4InputStream(final File file) throws IllegalArgumentException, IOException {
    log.trace("Initialise MP4 reader...");

    // Validate
    if (file != null && file.isFile() && file.canRead()) {
        log.trace("- file: " + file.getPath());

        // Prepare last modified date
        final Date lastModified = new Date();
        lastModified.setTime(file.lastModified());

        // Initialise stream
        this.inputStream = FileUtils.openInputStream(file);
        this.bufferedInputStream = new BufferedInputStream(this.inputStream);
        this.dataInputStream = new DataInputStream(this.bufferedInputStream);
        this.mp4Instance = new MP4(null);
        this.bytesRead = 0;

        log.trace("- size: " + available());
    } else {
        throw new IllegalArgumentException("Provided file reference is invalid! (file=" + file + ")");
    }
}

From source file:com.apteligent.ApteligentJavaClient.java

/**
 * Attempt to validate an existing token object
 * Note: this call does not yet check the validity of a token, only if it has not yet expired.
 * @param apiTokenObj/*from   ww  w . j ava2s.  c o m*/
 * @return true if the client accepted the token, false otherwise
 */
public boolean connect(Token apiTokenObj) {
    boolean success = false;
    if (apiTokenObj != null) {

        // check if the token is still active or expired
        Date today = new Date();

        // setup expiration date object
        Date dateTokenExpires = apiTokenObj.getCreationDate();
        long secondsOffset = apiTokenObj.getExpiresIn();
        dateTokenExpires.setTime(dateTokenExpires.getTime() + 1000 * secondsOffset);

        if (today.before(dateTokenExpires)) {
            this.token = apiTokenObj;
            success = true;
        }
    }
    return success;
}

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Check that the acummulated is set to 0 and added a negative value (refund)
 *//*  w  ww  .j  a  v a  2 s  .  co m*/
@Transactional
public void updateResetControls() {
    try {
        DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
        // Set user for testing
        tx.setTxEndUserId("userIdUpdate");
        tx.setTcTransactionType(Constants.REFUND_TYPE);
        tx.setFtChargedAmount(new BigDecimal(2));

        List<DbeExpendControl> controls = this.getExpenditureControls(tx);

        DbeExpendControl control = controls.get(0);
        // Reset period
        Date date = new Date();
        date.setTime((new Date()).getTime() - 100000000);
        control.setDtNextPeriodStart(date);

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);

        controlService.createOrUpdate(control);

        transactionManager.commit(status);

        limitService.updateLimit(tx);
        List<DbeExpendControl> controls2 = this.getExpenditureControls(tx);

        for (DbeExpendControl controlAux : controls2) {
            if (control.getId().getTxElType().equalsIgnoreCase(controlAux.getId().getTxElType())) {
                Assert.assertTrue("Expensed amount: " + controlAux.getFtExpensedAmount(),
                        controlAux.getFtExpensedAmount().compareTo(new BigDecimal(-2)) == 0);
            }
        }

    } catch (RSSException e) {
        Assert.fail("Exception not expected" + e.getMessage());
    }
}

From source file:ch.entwine.weblounge.bridge.oaipmh.WebloungeHarvester.java

/**
 * {@inheritDoc}//from  w  ww.  j a  va2s . com
 * 
 * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
 *      java.util.Dictionary)
 */
@SuppressWarnings("unchecked")
public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Get hold of the content repository
    WritableContentRepository contentRepository = null;
    if (site.getContentRepository().isReadOnly())
        throw new JobException(this, "Content repository of site '" + site + "' is read only");
    contentRepository = (WritableContentRepository) site.getContentRepository();

    // Read the configuration value for the repository url
    String repositoryUrl = (String) ctx.get(OPT_REPOSITORY_URL);
    if (StringUtils.isBlank(repositoryUrl))
        throw new JobException(this,
                "Configuration option '" + OPT_REPOSITORY_URL + "' is missing from the job configuration");

    // Make sure the url is well formed
    URL url = null;
    try {
        url = new URL(repositoryUrl);
    } catch (MalformedURLException e) {
        throw new JobException(this, "Repository url '" + repositoryUrl + "' is malformed: " + e.getMessage());
    }

    // Read the configuration value for the flavors
    String presentationTrackFlavor = (String) ctx.get(OPT_PRSENTATION_TRACK_FLAVORS);
    if (StringUtils.isBlank(presentationTrackFlavor))
        throw new JobException(this, "Configuration option '" + OPT_PRSENTATION_TRACK_FLAVORS
                + "' is missing from the job configuration");

    String presenterTrackFlavor = (String) ctx.get(OPT_PRESENTER_TRACK_FLAVORS);
    if (StringUtils.isBlank(presenterTrackFlavor))
        throw new JobException(this, "Configuration option '" + OPT_PRESENTER_TRACK_FLAVORS
                + "' is missing from the job configuration");

    String dcEpisodeFlavor = (String) ctx.get(OPT_EPISODE_DC_FLAVORS);
    if (StringUtils.isBlank(dcEpisodeFlavor))
        throw new JobException(this,
                "Configuration option '" + OPT_EPISODE_DC_FLAVORS + "' is missing from the job configuration");

    String dcSeriesFlavor = (String) ctx.get(OPT_SERIES_DC_FLAVORS);
    if (StringUtils.isBlank(dcSeriesFlavor))
        throw new JobException(this,
                "Configuration option '" + OPT_SERIES_DC_FLAVORS + "' is missing from the job configuration");

    String mimesTypes = (String) ctx.get(OPT_MIMETYPES);
    if (StringUtils.isBlank(mimesTypes))
        throw new JobException(this,
                "Configuration option '" + OPT_MIMETYPES + "' is missing from the job configuration");

    // Read the configuration value for the handler class
    String handlerClass = (String) ctx.get(OPT_HANDLER_CLASS);
    if (StringUtils.isBlank(handlerClass))
        throw new JobException(this,
                "Configuration option '" + OPT_HANDLER_CLASS + "' is missing from the job configuration");

    UserImpl harvesterUser = new UserImpl(name, site.getIdentifier(), "Harvester");

    RecordHandler handler;
    try {
        Class<? extends AbstractWebloungeRecordHandler> c = (Class<? extends AbstractWebloungeRecordHandler>) Thread
                .currentThread().getContextClassLoader().loadClass(handlerClass);
        Class<?> paramTypes[] = new Class[8];
        paramTypes[0] = Site.class;
        paramTypes[1] = WritableContentRepository.class;
        paramTypes[2] = User.class;
        paramTypes[3] = String.class;
        paramTypes[4] = String.class;
        paramTypes[5] = String.class;
        paramTypes[6] = String.class;
        paramTypes[7] = String.class;
        Constructor<? extends AbstractWebloungeRecordHandler> constructor = c.getConstructor(paramTypes);
        Object arglist[] = new Object[8];
        arglist[0] = site;
        arglist[1] = contentRepository;
        arglist[2] = harvesterUser;
        arglist[3] = presentationTrackFlavor;
        arglist[4] = presenterTrackFlavor;
        arglist[5] = dcEpisodeFlavor;
        arglist[6] = dcSeriesFlavor;
        arglist[7] = mimesTypes;
        handler = constructor.newInstance(arglist);
    } catch (Throwable t) {
        throw new IllegalStateException("Unable to instantiate class " + handlerClass + ": " + t.getMessage(),
                t);
    }

    SearchResult searchResult;
    SearchQuery q = new SearchQueryImpl(site);
    q.withTypes(MovieResource.TYPE);
    q.sortByPublishingDate(Order.Descending);
    q.withPublisher(harvesterUser);
    try {
        searchResult = contentRepository.find(q);
    } catch (ContentRepositoryException e) {
        logger.error("Error searching for resources with harvester publisher.");
        throw new RuntimeException(e);
    }

    Option<Date> harvestingDate = Option.<Date>none();
    if (searchResult.getHitCount() > 0) {
        MovieResourceSearchResultItemImpl resultItem = (MovieResourceSearchResultItemImpl) searchResult
                .getItems()[0];
        Date lastDate = resultItem.getMovieResource().getPublishFrom();
        // To not include the resources updated, 1 second is added to the last
        // update date
        lastDate.setTime(lastDate.getTime() + 1000);
        harvestingDate = some(lastDate);
    }

    try {
        harvest(repositoryUrl, harvestingDate, handler);
    } catch (Exception e) {
        logger.warn("An error occured while harvesting " + url + ". Skipping this repository for now...",
                e.getMessage());

    }
}

From source file:tools.xor.logic.DefaultQueryInheritanceCustom.java

public void listPatentsBeforeDate() {
    setupMetaEntityStateVO(aggregateService);
    setupMetaEntityTypeVO(aggregateService);

    Date today = new Date();
    Date yesterday = new Date();
    yesterday.setTime(today.getTime() - 1 * 1000 * 60 * 60 * 24);

    // Create first patent
    Patent patent1 = new Patent();
    patent1.setName("PATENT1");
    patent1.setDisplayName("Defects");
    patent1.setDescription("User story to address product defects");
    patent1.setState(getState(MetaEntityStateEnum.RETIRED.name()));
    patent1.setMetaEntityType(getType(MetaEntityTypeEnum.PATENT.name()));
    patent1.setCreatedOn(yesterday);/*from  ww  w  .  java2 s .  c  o m*/
    patent1 = (Patent) aggregateService.create(patent1, new Settings());

    // Create second patent
    Patent patent2 = new Patent();
    patent2.setName("PATENT2");
    patent2.setDisplayName("Enhancements");
    patent2.setDescription("User story to address product enhancements");
    patent2.setState(getState(MetaEntityStateEnum.ACTIVE.name()));
    patent2.setMetaEntityType(getType(MetaEntityTypeEnum.PATENT.name()));
    patent2.setCreatedOn(today);
    patent2 = (Patent) aggregateService.create(patent2, new Settings());

    // query the task object
    Settings settings = new Settings();
    settings.addFunctionFilter("ilike(name, :name)");
    settings.addFunctionFilter("in(state.name, :state)");
    settings.addFunctionFilter("equal(ownedBy.name, :owner)");
    settings.addFunctionFilter("lt(createdOn, :createdBefore)");
    settings.addFunctionFilter("asc(name)", 1);

    // Filter by name
    settings.addFilter("createdBefore", today);

    settings.setView(aggregateService.getView("ARTIFACTINFO"));
    MetaEntityVO input = new MetaEntityVO();
    MetaEntityTypeVO typeVO = new MetaEntityTypeVO();
    typeVO.setName(MetaEntityTypeEnum.PATENT.name());
    input.setMetaEntityType(typeVO);
    List<?> toList = aggregateService.query(input, settings);

    assert (toList.size() == 1);

    Object obj = toList.get(0);
    assert (PatentVO.class.isAssignableFrom(obj.getClass()));

    PatentVO a1 = (PatentVO) obj;
    assert (a1.getName().equals("PATENT1"));
}

From source file:tools.xor.logic.DefaultQueryInheritanceCustom.java

public void listPatentsByState() {
    setupMetaEntityStateVO(aggregateService);
    setupMetaEntityTypeVO(aggregateService);

    Date today = new Date();
    Date yesterday = new Date();
    yesterday.setTime(today.getTime() - 1 * 1000 * 60 * 60 * 24);

    // Create first patent
    Patent patent1 = new Patent();
    patent1.setName("PATENT1");
    patent1.setDisplayName("Defects");
    patent1.setDescription("User story to address product defects");
    patent1.setState(getState(MetaEntityStateEnum.RETIRED.name()));
    patent1.setMetaEntityType(getType(MetaEntityTypeEnum.PATENT.name()));
    patent1.setCreatedOn(yesterday);/*  ww  w  . j a  v  a 2s  .co m*/
    patent1 = (Patent) aggregateService.create(patent1, new Settings());

    // Create second patent
    Patent patent2 = new Patent();
    patent2.setName("PATENT2");
    patent2.setDisplayName("Enhancements");
    patent2.setDescription("User story to address product enhancements");
    patent2.setState(getState(MetaEntityStateEnum.ACTIVE.name()));
    patent2.setMetaEntityType(getType(MetaEntityTypeEnum.PATENT.name()));
    patent2.setCreatedOn(today);
    patent2 = (Patent) aggregateService.create(patent2, new Settings());

    // query the task object
    Settings settings = new Settings();
    settings.addFunctionFilter("ilike(name, :name)");
    settings.addFunctionFilter("in(state.name, :state)");
    settings.addFunctionFilter("equal(ownedBy.name, :owner)");
    settings.addFunctionFilter("ge(createdOn, :createdSince)");
    settings.addFunctionFilter("ge(updatedOn, :updatedSince)");
    settings.addFunctionFilter("asc(name)", 1);

    // Filter by name
    settings.addFilter("state", "ACTIVE");

    settings.setView(aggregateService.getView("ARTIFACTINFO"));
    MetaEntityVO input = new MetaEntityVO();
    MetaEntityTypeVO typeVO = new MetaEntityTypeVO();
    typeVO.setName(MetaEntityTypeEnum.PATENT.name());
    input.setMetaEntityType(typeVO);
    List<?> toList = aggregateService.query(input, settings);

    assert (toList.size() == 1);

    Object obj = toList.get(0);
    assert (PatentVO.class.isAssignableFrom(obj.getClass()));

    PatentVO a1 = (PatentVO) obj;
    assert (a1.getName().equals("PATENT2"));
}

From source file:org.fcrepo.http.api.FedoraBatch.java

/**
 * Retrieve multiple datastream bitstreams in a single request as a
 * multipart/mixed response.//from w w  w. j a  va 2 s.  com
 *
 * @param pathList
 * @param requestedChildren
 * @param request
 * @return
 * @throws RepositoryException
 * @throws NoSuchAlgorithmException
 */
@GET
@Produces("multipart/mixed")
@Timed
public Response getBinaryContents(@PathParam("path") final List<PathSegment> pathList,
        @QueryParam("child") final List<String> requestedChildren, @Context final Request request)
        throws RepositoryException, NoSuchAlgorithmException {

    final List<Datastream> datastreams = new ArrayList<>();

    try {
        final String path = toPath(pathList);
        // TODO: wrap some of this JCR logic in an fcrepo abstraction;

        final Node node = nodeService.getObject(session, path).getNode();

        Date date = new Date();

        final MessageDigest digest = MessageDigest.getInstance("SHA-1");

        final NodeIterator ni;

        if (requestedChildren.isEmpty()) {
            ni = node.getNodes();
        } else {
            ni = node.getNodes(requestedChildren.toArray(new String[requestedChildren.size()]));
        }

        // complain if no children found
        if (ni.getSize() == 0) {
            return status(Status.BAD_REQUEST).build();
        }

        // transform the nodes into datastreams, and calculate cache header
        // data
        while (ni.hasNext()) {

            final Node dsNode = ni.nextNode();
            final Datastream ds = datastreamService.asDatastream(dsNode);

            if (!ds.hasContent()) {
                continue;
            }

            digest.update(ds.getContentDigest().toString().getBytes(UTF_8));

            if (ds.getLastModifiedDate().after(date)) {
                date = ds.getLastModifiedDate();
            }

            datastreams.add(ds);
        }

        final URI digestURI = ContentDigest.asURI(digest.getAlgorithm(), digest.digest());
        final EntityTag etag = new EntityTag(digestURI.toString());

        final Date roundedDate = new Date();
        roundedDate.setTime(date.getTime() - date.getTime() % 1000);

        ResponseBuilder builder = request.evaluatePreconditions(roundedDate, etag);

        final CacheControl cc = new CacheControl();
        cc.setMaxAge(0);
        cc.setMustRevalidate(true);

        if (builder == null) {
            final MultiPart multipart = new MultiPart();

            for (final Datastream ds : datastreams) {
                final BodyPart bodyPart = new BodyPart(ds.getContent(), MediaType.valueOf(ds.getMimeType()));
                bodyPart.setContentDisposition(ContentDisposition.type(ATTACHMENT).fileName(ds.getPath())
                        .creationDate(ds.getCreatedDate()).modificationDate(ds.getLastModifiedDate())
                        .size(ds.getContentSize()).build());
                multipart.bodyPart(bodyPart);
            }

            builder = ok(multipart, MULTIPART_FORM_DATA);
        }

        return builder.cacheControl(cc).lastModified(date).tag(etag).build();

    } finally {
        session.logout();
    }
}