Example usage for org.joda.time DateTime DateTime

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

Introduction

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

Prototype

public DateTime(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:at.florian_lentsch.expirysync.net.ServerProxy.java

License:Open Source License

private static ProductEntry jsonToEntry(JSONObject entryObj) throws JSONException, ParseException {
    SimpleDateFormat sdfToDate = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    SimpleDateFormat sdfToDateTime = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

    ProductEntry receivedEntry = new ProductEntry();
    receivedEntry.serverId = entryObj.getInt("id");
    receivedEntry.description = entryObj.getString("description");
    receivedEntry.amount = entryObj.getInt("amount");
    receivedEntry.expiration_date = sdfToDate.parse(entryObj.getString("expiration_date"));
    receivedEntry.created_at = new DateTime(sdfToDateTime.parse(entryObj.getString("created_at")));
    receivedEntry.updated_at = new DateTime(sdfToDateTime.parse(entryObj.getString("updated_at")));

    JSONObject articleObj = entryObj.getJSONObject("article");
    receivedEntry.article = new Article(articleObj.isNull("name") ? null : articleObj.getString("name"));
    receivedEntry.article.barcode = articleObj.isNull("barcode") ? null : articleObj.getString("barcode");

    if (articleObj.has("images")) {
        JSONArray jsonEntries = articleObj.getJSONArray("images");
        for (int i = 0; i < jsonEntries.length(); i++) {
            JSONObject imageObj = jsonEntries.getJSONObject(i);
            ArticleImage image = new ArticleImage();
            image.serverId = imageObj.getInt("id");
            image.article = receivedEntry.article;
            receivedEntry.article.temporaryImages.add(image);
        }/*w w w .j ava  2s  .c  o m*/
    }

    return receivedEntry;
}

From source file:at.florian_lentsch.expirysync.NotifyChecker.java

License:Open Source License

/**
 * (non-Javadoc) The alarm has been triggered -> create a notification, if
 * there are any expired products (or any that will soon expire)
 *///from  ww  w .  j av  a  2 s.  c  o m
@Override
public void onReceive(Context context, Intent intent) {
    Context appContext = context.getApplicationContext();
    final SharedPreferences sharedPref = appContext.getSharedPreferences("main", Context.MODE_PRIVATE);

    int daysBeforeMedium = sharedPref.getInt(SettingsActivity.KEY_DAYS_BEFORE_MEDIUM, 0);

    DatabaseManager.init(appContext);
    List<ProductEntry> products = DatabaseManager.getInstance().getAllProductEntries();
    List<String> expiringProducts = new ArrayList<String>();
    for (ProductEntry productEntry : products) {
        if ((new DateTime(productEntry.expiration_date)).minusDays(daysBeforeMedium).isBeforeNow()) {
            expiringProducts.add(productEntry.amount + "x " + productEntry.article.name);
        }
    }

    if (expiringProducts.size() > 0) {
        this.createExpiryNotification(appContext, expiringProducts);
    }
}

From source file:at.florian_lentsch.expirysync.ProductAdapter.java

License:Open Source License

/**
 * Displays the expiration date according to the thresholds found in the
 * shared preferences/*from   w  w w . j a v  a 2s .c o  m*/
 * 
 * @param productEntry
 *            product entry to display the expiration date for
 * @param view
 *            list item view
 */
private void displayExpirationDate(ProductEntry productEntry, View view) {
    TextView expirationDateTxt = (TextView) view.findViewById(R.id.product_list_item_expiration_date);
    final Resources res = getContext().getResources();

    // coloring:
    final SharedPreferences sharedPref = getContext().getSharedPreferences("main", Context.MODE_PRIVATE);
    int daysBeforeMedium = sharedPref.getInt(SettingsActivity.KEY_DAYS_BEFORE_MEDIUM, 0);
    int daysBeforeBad = sharedPref.getInt(SettingsActivity.KEY_DAYS_BEFORE_BAD, 0);

    expirationDateTxt.setTextColor(res.getColor(R.color.expiration_date_good));

    if ((new DateTime(productEntry.expiration_date)).minusDays(daysBeforeMedium).isBeforeNow()) {
        expirationDateTxt.setTextColor(res.getColor(R.color.expiration_date_medium));
    }

    if ((new DateTime(productEntry.expiration_date)).minusDays(daysBeforeBad).isBeforeNow()) {
        expirationDateTxt.setTextColor(res.getColor(R.color.expiration_date_bad));
    }

    // set the date (formatted for the current locale):
    java.text.DateFormat formatter = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT,
            Locale.getDefault());
    String localPattern = ((SimpleDateFormat) formatter).toLocalizedPattern();
    SimpleDateFormat df = new SimpleDateFormat(localPattern);
    expirationDateTxt
            .setText(res.getText(R.string.expiration_date) + ": " + df.format(productEntry.expiration_date));
}

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder.java

License:EUPL

public static Assertion buildAssertion(AttributeQuery attrQuery, List<String> reqAttributes, IAuthData authData,
        DateTime date, String sessionIndex) throws ConfigurationException {

    AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class);
    authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel());

    List<Attribute> attrList = new ArrayList<Attribute>();
    if (reqAttributes != null) {
        Iterator<String> it = reqAttributes.iterator();
        while (it.hasNext()) {
            String reqAttributName = it.next();
            try {
                Attribute attr = PVPAttributeBuilder.buildAttribute(reqAttributName, null, authData);
                if (attr == null) {
                    Logger.error("Attribute generation failed! for " + reqAttributName);

                } else {
                    attrList.add(attr);//from  www  .ja  v  a  2  s. co  m

                }

            } catch (PVP2Exception e) {
                Logger.error("Attribute generation failed! for " + reqAttributName);

            } catch (Exception e) {
                Logger.error("General Attribute generation failed! for " + reqAttributName, e);

            }
        }
    }

    NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class);
    subjectNameID.setFormat(attrQuery.getSubject().getNameID().getFormat());
    subjectNameID.setValue(attrQuery.getSubject().getNameID().getValue());

    SubjectConfirmationData subjectConfirmationData = null;

    return buildGenericAssertion(attrQuery.getIssuer().getValue(), date, authnContextClassRef, attrList,
            subjectNameID, subjectConfirmationData, sessionIndex,
            new DateTime(authData.getSsoSessionValidTo().getTime()));
}

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder.java

License:EUPL

public static Assertion buildAssertion(AuthnRequest authnRequest, IAuthData authData,
        EntityDescriptor peerEntity, DateTime date, AssertionConsumerService assertionConsumerService,
        SLOInformationImpl sloInformation) throws MOAIDException {

    RequestedAuthnContext reqAuthnContext = authnRequest.getRequestedAuthnContext();

    AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class);

    OAAuthParameter oaParam = AuthConfigurationProvider.getInstance()
            .getOnlineApplicationParameter(peerEntity.getEntityID());

    if (reqAuthnContext == null) {
        authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel());

    } else {//from  w ww .  java2s  .  c  o  m

        boolean stork_qaa_1_4_found = false;

        List<AuthnContextClassRef> reqAuthnContextClassRefIt = reqAuthnContext.getAuthnContextClassRefs();

        if (reqAuthnContextClassRefIt.size() == 0) {

            QAALevelVerifier.verifyQAALevel(authData.getQAALevel(), STORK_QAA_1_4);

            stork_qaa_1_4_found = true;
            authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4);

        } else {
            for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) {
                String qaa_uri = authnClassRef.getAuthnContextClassRef();
                if (qaa_uri.trim().equals(STORK_QAA_1_4) || qaa_uri.trim().equals(STORK_QAA_1_3)
                        || qaa_uri.trim().equals(STORK_QAA_1_2) || qaa_uri.trim().equals(STORK_QAA_1_1)) {

                    if (authData.isForeigner()) {
                        QAALevelVerifier.verifyQAALevel(authData.getQAALevel(),
                                STORK_QAA_PREFIX + oaParam.getQaaLevel());

                        stork_qaa_1_4_found = true;
                        authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel());

                    } else {

                        QAALevelVerifier.verifyQAALevel(authData.getQAALevel(), qaa_uri.trim());

                        stork_qaa_1_4_found = true;
                        authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel());

                    }
                    break;
                }
            }
        }

        if (!stork_qaa_1_4_found) {
            throw new QAANotSupportedException(STORK_QAA_1_4);
        }
    }

    SPSSODescriptor spSSODescriptor = peerEntity.getSPSSODescriptor(SAMLConstants.SAML20P_NS);

    //add Attributes to Assertion
    List<Attribute> attrList = new ArrayList<Attribute>();
    if (spSSODescriptor.getAttributeConsumingServices() != null
            && spSSODescriptor.getAttributeConsumingServices().size() > 0) {

        Integer aIdx = authnRequest.getAttributeConsumingServiceIndex();
        int idx = 0;

        AttributeConsumingService attributeConsumingService = null;

        if (aIdx != null) {
            idx = aIdx.intValue();
            attributeConsumingService = spSSODescriptor.getAttributeConsumingServices().get(idx);

        } else {
            List<AttributeConsumingService> attrConsumingServiceList = spSSODescriptor
                    .getAttributeConsumingServices();
            for (AttributeConsumingService el : attrConsumingServiceList) {
                if (el.isDefault())
                    attributeConsumingService = el;
            }
        }

        if (attributeConsumingService != null) {
            Iterator<RequestedAttribute> it = attributeConsumingService.getRequestAttributes().iterator();
            while (it.hasNext()) {
                RequestedAttribute reqAttribut = it.next();
                try {
                    Attribute attr = PVPAttributeBuilder.buildAttribute(reqAttribut.getName(), oaParam,
                            authData);
                    if (attr == null) {
                        if (reqAttribut.isRequired()) {
                            throw new UnprovideableAttributeException(reqAttribut.getName());
                        }
                    } else {
                        attrList.add(attr);
                    }

                } catch (UnavailableAttributeException e) {
                    Logger.info("Attribute generation for " + reqAttribut.getFriendlyName() + " not possible.");
                    if (reqAttribut.isRequired()) {
                        throw new UnprovideableAttributeException(reqAttribut.getName());
                    }

                } catch (PVP2Exception e) {
                    Logger.warn("Attribute generation failed! for " + reqAttribut.getFriendlyName());
                    if (reqAttribut.isRequired()) {
                        throw new UnprovideableAttributeException(reqAttribut.getName());
                    }

                } catch (Exception e) {
                    Logger.error("General Attribute generation failed! for " + reqAttribut.getFriendlyName(),
                            e);
                    if (reqAttribut.isRequired()) {
                        throw new UnprovideableAttributeException(reqAttribut.getName());
                    }

                }
            }
        }
    }

    NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class);

    //build nameID and nameID Format from moasession
    if (authData.isUseMandate()) {
        Element mandate = authData.getMandate();
        if (mandate == null) {
            throw new NoMandateDataAvailableException();
        }
        Mandate mandateObject = MandateBuilder.buildMandate(mandate);
        if (mandateObject == null) {
            throw new NoMandateDataAvailableException();
        }
        CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody();
        PhysicalPersonType pysicalperson = mandateObject.getMandator().getPhysicalPerson();

        IdentificationType id;
        if (corporation != null && corporation.getIdentification().size() > 0)
            id = corporation.getIdentification().get(0);

        else if (pysicalperson != null && pysicalperson.getIdentification().size() > 0)
            id = pysicalperson.getIdentification().get(0);

        else {
            Logger.error("Failed to generate IdentificationType");
            throw new NoMandateDataAvailableException();
        }

        String bpktype = id.getType();
        String bpk = id.getValue().getValue();

        if (bpktype.equals(Constants.URN_PREFIX_BASEID)) {
            if (oaParam.getBusinessService()) {
                subjectNameID
                        .setValue(new BPKBuilder().buildWBPK(bpk, oaParam.getIdentityLinkDomainIdentifier()));
                if (oaParam.getIdentityLinkDomainIdentifier()
                        .startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
                    subjectNameID.setNameQualifier(oaParam.getIdentityLinkDomainIdentifier());
                else
                    subjectNameID.setNameQualifier(
                            Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier());

            } else {
                subjectNameID.setValue(new BPKBuilder().buildBPK(bpk, oaParam.getTarget()));
                if (oaParam.getTarget().startsWith(Constants.URN_PREFIX_CDID + "+"))
                    subjectNameID.setNameQualifier(oaParam.getTarget());
                else
                    subjectNameID.setNameQualifier(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget());
            }

        } else {
            subjectNameID.setNameQualifier(bpktype);
            subjectNameID.setValue(bpk);
        }

    } else {
        subjectNameID.setNameQualifier(authData.getBPKType());
        subjectNameID.setValue(authData.getBPK());
    }

    String nameIDFormat = NameID.TRANSIENT;

    //get NameIDFormat from request      
    AuthnRequest authnReq = (AuthnRequestImpl) authnRequest;
    if (authnReq.getNameIDPolicy() != null) {
        nameIDFormat = authnReq.getNameIDPolicy().getFormat();

    } else {
        //get NameIDFormat from metadata
        List<NameIDFormat> metadataNameIDFormats = spSSODescriptor.getNameIDFormats();

        if (metadataNameIDFormats != null) {

            for (NameIDFormat el : metadataNameIDFormats) {
                if (NameID.PERSISTENT.equals(el.getFormat())) {
                    nameIDFormat = NameID.PERSISTENT;
                    break;

                } else if (NameID.TRANSIENT.equals(el.getFormat()) || NameID.UNSPECIFIED.equals(el.getFormat()))
                    break;

            }
        }
    }

    if (NameID.TRANSIENT.equals(nameIDFormat) || NameID.UNSPECIFIED.equals(nameIDFormat)) {
        String random = Random.nextRandom();
        String nameID = subjectNameID.getValue();

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] hash = md.digest((nameID + random).getBytes("ISO-8859-1"));
            subjectNameID.setValue(Base64Utils.encode(hash));
            subjectNameID.setNameQualifier(null);
            subjectNameID.setFormat(NameID.TRANSIENT);

        } catch (Exception e) {
            Logger.warn("PVP2 subjectNameID error", e);
            throw new MOAIDException("pvp2.13", null, e);
        }

    } else
        subjectNameID.setFormat(nameIDFormat);

    String sessionIndex = null;

    //if request is a reauthentication and NameIDFormat match reuse old session information
    if (MiscUtil.isNotEmpty(authData.getNameID()) && MiscUtil.isNotEmpty(authData.getNameIDFormat())
            && nameIDFormat.equals(authData.getNameIDFormat())) {
        subjectNameID.setValue(authData.getNameID());
        sessionIndex = authData.getSessionIndex();

    } else
        sessionIndex = SAML2Utils.getSecureIdentifier();

    SubjectConfirmationData subjectConfirmationData = SAML2Utils
            .createSAMLObject(SubjectConfirmationData.class);
    subjectConfirmationData.setInResponseTo(authnRequest.getID());
    subjectConfirmationData.setNotOnOrAfter(new DateTime(authData.getSsoSessionValidTo().getTime()));

    subjectConfirmationData.setRecipient(assertionConsumerService.getLocation());

    //set SLO information
    sloInformation.setUserNameIdentifier(subjectNameID.getValue());
    sloInformation.setNameIDFormat(subjectNameID.getFormat());
    sloInformation.setSessionIndex(sessionIndex);

    return buildGenericAssertion(peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID,
            subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter());
}

From source file:au.com.scds.chats.dom.call.CalendarDayCallSchedule.java

License:Apache License

public DateTime default1AddNewCall() {
    return new DateTime(getCalendarDate().toDateTimeAtCurrentTime());
}

From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java

License:Apache License

private void addListing(ChannelListings channelListings, Config config, ChannelConfig channelConfig,
        String channelTag, DateTime from, DateTime to) {
    StopWatch watch = new StopWatch();
    watch.start();//from   www .  j  av a 2 s .c  o m
    List<Event> events = getEvents(config, channelTag, from, to);
    LOGGER.debug("Found {} events between {} and {}", events.size(), from, to);
    for (Event event : events) {
        ProgrammeDetail programmeDetails;
        LOGGER.debug("Processing event id {}", event.getEventId());
        DateTime scheduleDate = new DateTime(event.getScheduledDate());
        if (scheduleDate.plusMinutes(event.getDuration()).isAfterNow()
                && scheduleDate.isBefore(from.plusDays(config.getSynopsis()))) {
            LOGGER.debug("Fetching detailed synopsis for {}", event.getEventId());
            try {
                EventDetails eventDetails = getForObject(DETAILS_URI, EventDetails.class, event.getEventId(),
                        config.getRegionId());
                programmeDetails = createProgrammeDetails(eventDetails.getEvent());
            } catch (Exception e) {
                LOGGER.debug("Failed to get detailed synopsis. Using basic details instead.");
                programmeDetails = createProgrammeDetails(event);
            }
        } else {
            programmeDetails = createProgrammeDetails(event);
        }
        channelListings.addProgram(channelConfig.getId(), programmeDetails);
    }
    watch.stop();
    String numberOfPrograms = String.valueOf(channelListings.getNumberOfPrograms(channelConfig.getId()));
    LOGGER.info("{} {} events [took {}]", rightPad(channelConfig.getId() + " - " + channelConfig.getName(), 40),
            leftPad(numberOfPrograms, 4), formatDurationWords(watch.getTime()));
}

From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java

License:Apache License

private ProgrammeDetail createProgrammeDetails(Event event) {
    DateTime startDate = new DateTime(event.getScheduledDate());
    Minutes duration = Minutes.minutes(event.getDuration());
    String title = event.getProgramTitle();
    EpisodeDetail episodeDetail = new EpisodeDetail(event.getEpisodeTitle(), "TBA", event.getSeriesNumber(),
            event.getEpisodeNumber());/* ww w.  j  a  va  2 s.c  o  m*/
    return new ProgrammeDetail(startDate, duration, title, episodeDetail, Collections.<String>emptyList(),
            event.getParentalRating());
}

From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java

License:Apache License

private ProgrammeDetail createProgrammeDetails(EventDetail eventDetail) {
    DateTime startDate = new DateTime(eventDetail.getScheduledDate());
    Minutes duration = Minutes.minutes(eventDetail.getDuration());
    String title = eventDetail.getProgramTitle();
    EpisodeDetail episodeDetail = new EpisodeDetail(eventDetail.getEpisodeTitle(),
            eventDetail.getShortSynopsis(), eventDetail.getSeriesNumber(), eventDetail.getEpisodeNumber());
    String rating = eventDetail.getParentalRating();
    return new ProgrammeDetail(startDate, duration, title, episodeDetail,
            asList(eventDetail.getGenre(), eventDetail.getSubGenre()), rating);
}

From source file:au.id.hazelwood.xmltvguidebuilder.utils.DateTimeUtils.java

License:Apache License

public static DateTime toDateTime(Calendar calendar) {
    return new DateTime(calendar);
}