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.rhq.core.pluginapi.event.log.MultiLineLogEntryProcessor.java

protected static void setDateIfNotSet(Date timestamp) {
    Calendar date = convertToCalendar(timestamp);
    // If the format specified a time, but no date, the date will be Jan 1, 1970. In this case, set the date to
    // today's date.
    if (date.get(Calendar.YEAR) == 1970) {
        Calendar currentDate = Calendar.getInstance();
        date.set(currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH),
                currentDate.get(Calendar.DATE));
        timestamp.setTime(date.getTimeInMillis());
    }/* ww  w.  j  av  a2s.  c  o m*/
}

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

private static void evaluateRequestPreconditions(final Request request,
        final HttpServletResponse servletResponse, final FedoraResource resource, final Session session,
        final boolean cacheControl) {

    final String txId = TransactionServiceImpl.getCurrentTransactionId(session);
    if (txId != null) {
        // Force cache revalidation if in a transaction
        servletResponse.addHeader(CACHE_CONTROL, "must-revalidate");
        servletResponse.addHeader(CACHE_CONTROL, "max-age=0");
        return;//from w  ww. j av a2s .  c o m
    }

    final EntityTag etag = new EntityTag(resource.getEtagValue());
    final Date date = resource.getLastModifiedDate();
    final Date roundedDate = new Date();

    if (date != null) {
        roundedDate.setTime(date.getTime() - date.getTime() % 1000);
    }

    Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
    if (builder != null) {
        builder = builder.entity("ETag mismatch");
    } else {
        builder = request.evaluatePreconditions(roundedDate);
        if (builder != null) {
            builder = builder.entity("Date mismatch");
        }
    }

    if (builder != null && cacheControl) {
        final CacheControl cc = new CacheControl();
        cc.setMaxAge(0);
        cc.setMustRevalidate(true);
        // here we are implicitly emitting a 304
        // the exception is not an error, it's genuinely
        // an exceptional condition
        builder = builder.cacheControl(cc).lastModified(date).tag(etag);
    }
    if (builder != null) {
        throw new WebApplicationException(builder.build());
    }
}

From source file:Dates.java

/**
 * Truncates date to the nearest precision milliseconds. MS SQLServer2000 with
 * only the maximum accuracy of 1/300 seconds would not be able to store up to
 * one millisecond accurarcy. That is, User must round the millisecond to some
 * less precisions; or the data in that db would be inconsistence with that in
 * memory. It is useful to store a Date object in a database. Without
 * rounding, if you want to get it back and compare with the one in the
 * memory. See {@link #now} for details.
 * /*from www. j a v a  2s  .c  om*/
 * @param precision
 *          the divider of the precision(e.g. 10 for precision of 10
 *          milliseconds;i.e. all millisecond less than 10 would be truncated)
 * @see #now
 * @see #round(long, int)
 */
public static final Date round(Date date, int precision) {
    date.setTime(round(date.getTime(), precision));
    return date;
}

From source file:uk.ac.susx.tag.method51.webapp.server.RootServer.java

protected static Handler getResourceHandler(String contextPath) throws IOException {

    final ResourceRegistry resources = ResourceRegistry.getRegistry();

    resources.addResources(new WebappCore());
    resources.addResources(new WebappLib());

    //resources.loadResources("webapp-lib");
    //resources.loadResources("webapp");

    resources.loadAllResources();/* ww  w  .j ava  2s. c om*/

    final Date loaded = new Date();

    ResourceHandler resourceHandler = new ResourceHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            if (dev && (new Date().getTime() - loaded.getTime() > 1000)) {
                loaded.setTime(new Date().getTime());
                System.out.println("loading webapp resources");
                resources.loadResources("webapp");
            }
            super.handle(target, baseRequest, request, response);
        }
    };
    resourceHandler.setDirectoriesListed(true);

    resourceHandler.setResourceBase(getPath("public"));

    resourceHandler.getMimeTypes().addMimeMapping("dust", "text/x-template");

    ContextHandler resourceContextHandler = new ContextHandler();
    resourceContextHandler.setContextPath(contextPath);
    resourceContextHandler.setHandler(resourceHandler);

    return resourceContextHandler;
}

From source file:org.apache.rahas.TrustUtil.java

public static OMElement createLifetimeElement(int version, OMElement parent, long ttl) throws TrustException {

    Date creationTime = new Date();
    Date expirationTime = new Date();
    expirationTime.setTime(creationTime.getTime() + ttl);

    DateFormat zulu = new XmlSchemaDateFormat();

    return createLifetimeElement(version, parent, zulu.format(creationTime), zulu.format(expirationTime));
}

From source file:Dates.java

/**
 * Returns a clone but with 23:59:59:999 for hours, minutes, seconds and milliseconds. <p>
 * //  w ww .j  av a 2 s.  co m
 * @return The same date sent as argument (a new date is not created). If null
 *      if sent a null is returned.
 */
public static Date cloneWith2359(Date date) {
    if (date == null)
        return null;
    Date result = (Date) date.clone();
    Calendar cal = Calendar.getInstance();
    cal.setTime(result);
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MILLISECOND, 999);
    result.setTime(cal.getTime().getTime());
    return result;
}

From source file:Dates.java

/**
 * Puts hours, minutes, seconds and milliseconds to zero. <p>
 * //from  ww  w . j  av a2  s.  c  om
 * @return The same date sent as argument (a new date is not created). If null
 *      if sent a null is returned.
 */
public static Date removeTime(Date date) {
    if (date == null)
        return null;
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    date.setTime(cal.getTime().getTime());
    return date;
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket//from www.ja v a2  s  . c  om
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:MailDateFormatter.java

/**
 * Parses the string in RFC 2822 format and return a <code>Date</code>
 * object. <p>/*from  ww w. j  a v  a2  s.  c  o m*/
 * Parse strings like:
 * Thu, 03 May 2007 14:45:38 GMT
 * Thu, 03 May 2007 14:45:38 GMT+0200
 * Thu,  1 Feb 2007 03:57:01 -0800
 * Fri, 04 May 2007 13:40:17 PDT
 * 
 * @param d the date representation to parse
 * @return a date, if valid, or null on error
 *
 */
public static Date parseRfc2822Date(String stringDate) {
    if (stringDate == null) {
        return null;
    }

    long hourOffset = 0;
    long minOffset = 0;
    Calendar cal = Calendar.getInstance();

    try {

        // We use the ' ' as separator and we expect only one space. We
        // clean the string to remove extra spaces
        StringBuffer cleanedDate = new StringBuffer();
        char previous = 'a';
        for (int i = 0; i < stringDate.length(); ++i) {
            char ch = stringDate.charAt(i);
            if (ch != ' ' || previous != ' ') {
                cleanedDate.append(ch);
            }
            previous = ch;
        }
        stringDate = cleanedDate.toString();
        // Log.debug("Cleaned date: " + stringDate);

        // Just skip the weekday if present
        int start = stringDate.indexOf(',');
        //put start after ", "
        start = (start == -1) ? 0 : start + 2;

        stringDate = stringDate.substring(start).trim();
        start = 0;

        // Get day of month
        int end = stringDate.indexOf(' ', start);

        //4  Nov 2008 10:30:05 -0400

        int day = 1;
        try {
            day = Integer.parseInt(stringDate.substring(start, end));
        } catch (NumberFormatException ex) {

            day = Integer.parseInt(stringDate.substring(start + 3, end));
        }

        cal.set(Calendar.DAY_OF_MONTH, day);

        // Get month
        start = end + 1;
        end = stringDate.indexOf(' ', start);
        cal.set(Calendar.MONTH, getMonthNumber(stringDate.substring(start, end)));

        // Get year
        start = end + 1;
        end = stringDate.indexOf(' ', start);
        cal.set(Calendar.YEAR, Integer.parseInt(stringDate.substring(start, end)));

        // Get hour
        start = end + 1;
        end = stringDate.indexOf(':', start);
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(stringDate.substring(start, end).trim()));

        // Get min
        start = end + 1;
        end = stringDate.indexOf(':', start);
        cal.set(Calendar.MINUTE, Integer.parseInt(stringDate.substring(start, end)));

        // Get sec
        start = end + 1;
        end = stringDate.indexOf(' ', start);
        cal.set(Calendar.SECOND, Integer.parseInt(stringDate.substring(start, end)));

        // Get OFFSET
        start = end + 1;
        end = stringDate.indexOf('\r', start);

        // Process Timezone, checking first for the actual RFC2822 format,
        // and then for nthe obsolete syntax.

        char sign = '+';
        String hourDiff = "0";
        String minDiff = "0";

        String offset = stringDate.substring(start).trim();
        if (offset.startsWith("+") || offset.startsWith("-")) {
            if (offset.length() >= 5) {
                sign = offset.charAt(0);
                hourDiff = offset.substring(1, 3);
                minDiff = offset.substring(3, 5);
            } else if (offset.length() == 3) {
                sign = offset.charAt(0);
                hourDiff = offset.substring(1);
                minDiff = "00";
            }
            // Convert offset to int
            hourOffset = Long.parseLong(hourDiff);
            minOffset = Long.parseLong(minDiff);
            if (sign == '-') {
                hourOffset = -hourOffset;
            }
        } else if (offset.equals("EDT")) {
            hourOffset = -4;
        } else if (offset.equals("EST") || offset.equals("CDT")) {
            hourOffset = -5;
        } else if (offset.equals("CST") || offset.equals("MDT")) {
            hourOffset = -6;
        } else if (offset.equals("PDT") || offset.equals("MST")) {
            hourOffset = -7;
        } else if (offset.equals("PST")) {
            hourOffset = -8;
        } else if (offset.equals("GMT") || offset.equals("UT")) {
            hourOffset = 0;
        } else if (offset.substring(0, 3).equals("GMT") && offset.length() > 3) {
            sign = offset.charAt(3);
            hourDiff = offset.substring(4, 6);
            minDiff = offset.substring(6, 8);
        }

        long millisOffset = (hourOffset * 3600000) + (minOffset * 60000);

        Date gmtDate = cal.getTime();
        long millisDate = gmtDate.getTime();

        millisDate -= millisOffset;

        gmtDate.setTime(millisDate);
        return gmtDate;

    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }
}

From source file:MailDateFormatter.java

/**
 * Convert the given date (GMT) into the local date.
 * NOTE: changes the original date too!/*  w w w  .  j av  a2s  .  com*/
 * Should we change it to a void toLocalDate(Date) that changes the
 * input date only?
 */
public static Date getDeviceLocalDate(Date gmtDate) {
    if (null != gmtDate) {
        /*long dateInMillis = gmtDate.getTime();
        Date deviceDate = new Date();
        deviceDate.setTime(dateInMillis+millisDeviceOffset);
        return deviceDate;
         **/
        gmtDate.setTime(gmtDate.getTime() + millisDeviceOffset);
        return gmtDate;
    } else {
        return null;
    }
}