Example usage for org.joda.time DateTime getMillis

List of usage examples for org.joda.time DateTime getMillis

Introduction

In this page you can find the example usage for org.joda.time DateTime getMillis.

Prototype

public long getMillis() 

Source Link

Document

Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z.

Usage

From source file:com.flooose.gpxkeeper.GPXFile.java

License:Open Source License

public void saveTrackingPointAsJSON() {
    DateTime timestamp = null;

    JSONObject trackingPoint = new JSONObject();

    for (int i = 0; i < parser.getAttributeCount(); i++) {
        try {/*  w w  w  . j  a va2 s  .c o  m*/
            if ("lon".equals(parser.getAttributeName(i))) {
                trackingPoint.put(LONGITUDE, parser.getAttributeValue(i));

            } else if ("lat".equals(parser.getAttributeName(i))) {
                trackingPoint.put(LATITUDE, parser.getAttributeValue(i));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    try {
        while (!trackPointEnd()) {
            if ("ele".equals(parser.getName()) && parser.getEventType() != parser.END_TAG) {
                while (parser.getEventType() != parser.TEXT)
                    parser.next();
                trackingPoint.put(GPXFile.ELEVATION, parser.getText());
            } else if ("time".equals(parser.getName()) && parser.getEventType() != parser.END_TAG) {
                while (parser.getEventType() != parser.TEXT)
                    parser.next();
                DateTimeFormatter dtf = DateTimeFormat.forPattern(GPX_DATE_FORMAT_STRING);
                timestamp = dtf.withZoneUTC().parseDateTime(parser.getText());

                if (startTime == null) {
                    startTime = timestamp.withZone(DateTimeZone.getDefault());

                    gpsActivity.put(GPXFile.START_TIME,
                            new SimpleDateFormat(DATE_FORMAT_STRING).format(startTime.getMillis()));
                }
            }
            parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        trackingPoint.put(GPXFile.TIMESTAMP, (timestamp.getMillis() - startTime.getMillis()) / 1000); // there should be a constant defined somewhere. Find it.
        trackingPoint.put(GPXFile.TRACKING_POINT_TYPE, "gps");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    gpsPath.put(trackingPoint);
}

From source file:com.foundationdb.server.types.mcompat.mtypes.MTypesTranslator.java

License:Open Source License

@Override
public long getTimestampMillisValue(ValueSource value) {
    TClass tclass = TInstance.tClass(value.getType());
    long[] ymdhms = null;
    if (tclass == MDateAndTime.DATE) {
        ymdhms = MDateAndTime.decodeDate(value.getInt32());
    } else if (tclass == MDateAndTime.TIME) {
        ymdhms = MDateAndTime.decodeTime(value.getInt32());
    } else if (tclass == MDateAndTime.DATETIME) {
        ymdhms = MDateAndTime.decodeDateTime(value.getInt64());
    }// w ww . ja  va2s.  c o  m
    if (ymdhms != null) {
        DateTime dt = new DateTime((int) ymdhms[0], (int) ymdhms[1], (int) ymdhms[2], (int) ymdhms[3],
                (int) ymdhms[4], (int) ymdhms[5]);
        return dt.getMillis();
    } else {
        return value.getInt32() * 1000L;
    }
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

License:Apache License

/**
 * TransCellAccessToken????./*  w w  w .  j a v  a2s  .  com*/
 * @param token 
 * @return TransCellAccessToken(?)
 * @throws AbstractOAuth2Token.TokenParseException ?
 * @throws AbstractOAuth2Token.TokenDsigException ???
 * @throws AbstractOAuth2Token.TokenRootCrtException CA?
 */
public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException,
        AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException {
    try {
        byte[] samlBytes = DcCoreUtils.decodeBase64Url(token);
        ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = null;
        try {
            builder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // ????????????
            throw new RuntimeException(e);
        }

        Document doc = builder.parse(bais);

        Element assertion = doc.getDocumentElement();
        Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0));
        Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0));
        Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0));
        String id = assertion.getAttribute("ID");
        String issuedAtStr = assertion.getAttribute("IssueInstant");

        DateTime dt = new DateTime(issuedAtStr);

        NodeList audienceList = assertion.getElementsByTagName("Audience");
        Element aud1 = (Element) (audienceList.item(0));
        String target = aud1.getTextContent();
        String schema = null;
        if (audienceList.getLength() > 1) {
            Element aud2 = (Element) (audienceList.item(1));
            schema = aud2.getTextContent();
        }

        List<Role> roles = new ArrayList<Role>();
        NodeList attrList = assertion.getElementsByTagName("AttributeValue");
        for (int i = 0; i < attrList.getLength(); i++) {
            Element attv = (Element) (attrList.item(i));
            roles.add(new Role(new URL(attv.getTextContent())));
        }

        NodeList nl = assertion.getElementsByTagName("Signature");
        if (nl.getLength() == 0) {
            throw new TokenParseException("Cannot find Signature element");
        }
        Element signatureElement = (Element) nl.item(0);

        // ???????TokenDsigException??
        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent());
        DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement);

        // Unmarshal the XMLSignature.
        XMLSignature signature;
        try {
            signature = xmlSignatureFactory.unmarshalXMLSignature(valContext);
        } catch (MarshalException e) {
            throw new TokenDsigException(e.getMessage(), e);
        }

        // CA??
        try {
            x509KeySelector.readRoot(x509RootCertificateFileNames);
        } catch (CertificateException e) {
            // CA????????500
            throw new TokenRootCrtException(e.getMessage(), e);
        }

        // Validate the XMLSignature x509.
        boolean coreValidity;
        try {
            coreValidity = signature.validate(valContext);
        } catch (XMLSignatureException e) {
            if (e.getCause().getClass() == new KeySelectorException().getClass()) {
                throw new TokenDsigException(e.getCause().getMessage(), e.getCause());
            }
            throw new TokenDsigException(e.getMessage(), e);
        }

        // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation

        // Check core validation status.
        if (!coreValidity) {
            // ??
            boolean isDsigValid;
            try {
                isDsigValid = signature.getSignatureValue().validate(valContext);
            } catch (XMLSignatureException e) {
                throw new TokenDsigException(e.getMessage(), e);
            }
            if (!isDsigValid) {
                throw new TokenDsigException("Failed signature validation");
            }

            // 
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                boolean refValid;
                try {
                    refValid = ((Reference) i.next()).validate(valContext);
                } catch (XMLSignatureException e) {
                    throw new TokenDsigException(e.getMessage(), e);
                }
                if (!refValid) {
                    throw new TokenDsigException("Failed to validate reference [" + j + "]");
                }
            }
            throw new TokenDsigException("Signature failed core validation. unkwnon reason.");
        }
        return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(),
                subjectNameID.getTextContent(), target, roles, schema);
    } catch (UnsupportedEncodingException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new TokenParseException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TokenParseException(e.getMessage(), e);
    }
}

From source file:com.fusesource.examples.horo.db.typehandler.DateTimeTypeHandler.java

License:Apache License

@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, DateTime dateTime,
        JdbcType jdbcType) throws SQLException {
    Validate.notNull(dateTime, "dateTime is null");
    if ((jdbcType == null) || (jdbcType.equals(JdbcType.DATE))) {
        preparedStatement.setDate(i, new java.sql.Date(dateTime.getMillis()));
    } else {/*from   w w w.  j  av  a  2 s  . co  m*/
        throw new UnsupportedOperationException("Unable to convert DateTime to " + jdbcType.toString());
    }
}

From source file:com.ge.predix.acs.policy.evaluation.cache.AbstractPolicyEvaluationCache.java

License:Apache License

@Override
public void set(final PolicyEvaluationRequestCacheKey key, final PolicyEvaluationResult result) {
    try {//  w  w  w.ja va2  s. c  o  m
        DateTime now = new DateTime();
        result.setTimestamp(now.getMillis());
        String value = OBJECT_MAPPER.writeValueAsString(result);
        set(key.toRedisKey(), value);
        setResourceTranslations(key.getZoneId(), result.getResolvedResourceUris(), key.getResourceId());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Setting policy evaluation to cache; key: '%s', value: '%s'.",
                    key.toRedisKey(), value));
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to write policy evaluation result as JSON.", e);
    }
}

From source file:com.github.cherimojava.data.mongo.io.DateTimeCodec.java

License:Apache License

@Override
public void encode(BsonWriter writer, DateTime value, EncoderContext encoderContext) {
    writer.writeDateTime(value.getMillis());
}

From source file:com.github.jasonruckman.sidney.ext.common.JodaDateTimeSerializer.java

License:Apache License

@Override
public void writeValue(DateTime value, Contexts.WriteContext context) {
    millis.writeLong(value.getMillis(), context);
    chrono.writeValue(value.getChronology(), context);
    tz.writeValue(value.getZone().getID(), context);
}

From source file:com.github.jdot.mapper.DateTimeMapper.java

License:Apache License

@Override
public Date toView(DateTime dateTime) {
    return new Date(dateTime.getMillis());
}

From source file:com.github.jeanmerelis.jeanson.ext.typehandler.JodaDateTimeHandler.java

License:Apache License

@Override
public void write(Writer w, DateTime obj) throws IOException {
    if (obj == null) {
        w.write("null");
        return;//from   w ww.j  ava 2  s  .  c  o m
    }
    if (!usesMills) {
        DefaultStringHandler.escapeAndQuote(w, obj.toString(pattern));
    } else {
        w.write(String.valueOf(obj.getMillis()));
    }
}

From source file:com.github.jobs.adapter.JobsAdapter.java

License:Apache License

@Override
public void populateHolder(int position, View view, ViewGroup parent, Job job, ViewHolder holder) {
    holder.title.setText(StringUtils.trim(job.getTitle()));
    holder.location.setText(StringUtils.trim(job.getLocation()));
    if (JobDetailsActivity.FULL_TIME.equals(job.getType())) {
        holder.company.setText(String.format("%s - ", job.getCompany()));
    } else {/*from  w w w.  j a  v  a2 s.c o m*/
        holder.company.setText(job.getCompany());
    }
    holder.type.setText(job.getType());
    try {
        DateTime parsed = DATE_PARSER.withZoneUTC().parseDateTime(job.getCreatedAt());
        String timeAgo = RelativeDate.getTimeAgo(getContext(), parsed.getMillis());
        holder.date.setText(timeAgo);
    } catch (Exception e) {
        Log.wtf(TAG, "Could not parse date: " + job.getCreatedAt(), e);
    }
}