Example usage for org.joda.time DateTime withChronology

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

Introduction

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

Prototype

public DateTime withChronology(Chronology newChronology) 

Source Link

Document

Returns a copy of this datetime with a different chronology.

Usage

From source file:com.helger.smtp.failed.FailedMailDataMicroTypeConverter.java

License:Apache License

@Nullable
public FailedMailData convertToNative(@Nonnull final IMicroElement eFailedMail) {
    final String sID = eFailedMail.getAttributeValue(ATTR_ID);
    if (sID == null) {
        s_aLogger.error("Failed to read ID");
        return null;
    }// w w w . j  av  a  2 s .c o  m

    // Read error date/time
    final String sErrorDT = eFailedMail.getAttributeValue(ATTR_ERRORDT);
    if (sErrorDT == null) {
        s_aLogger.error("Failed to read error date/time");
        return null;
    }
    LocalDateTime aErrorDT = PDTWebDateUtils.getLocalDateTimeFromXSD(sErrorDT);
    if (aErrorDT == null)
        aErrorDT = PDTWebDateUtils.getLocalDateTimeFromW3C(sErrorDT);
    if (aErrorDT == null) {
        s_aLogger.error("Failed to parse error date '" + sErrorDT + "'");
        return null;
    }

    // read original sent date/time
    final String sOriginalSentDT = eFailedMail.getAttributeValue(ATTR_ORIGINALSENTDT);
    DateTime aOriginalSentDT = null;
    if (sOriginalSentDT != null) {
        aOriginalSentDT = PDTWebDateUtils.getDateTimeFromXSD(sOriginalSentDT);
        if (aOriginalSentDT == null)
            aOriginalSentDT = PDTWebDateUtils.getDateTimeFromW3C(sOriginalSentDT);
    }
    if (aOriginalSentDT != null)
        aOriginalSentDT = aOriginalSentDT.withChronology(PDTConfig.getDefaultChronology());

    // SMTP settings
    final IMicroElement eSMTPSettings = eFailedMail.getFirstChildElement(ELEMENT_SMTPSETTINGS);
    if (eSMTPSettings == null) {
        s_aLogger.error("Failed to get child element of SMTP settings!");
        return null;
    }
    final ISMTPSettings aSMTPSettings = MicroTypeConverter.convertToNative(eSMTPSettings, SMTPSettings.class);

    // email data (may be null)
    final IMicroElement eEmailData = eFailedMail.getFirstChildElement(ELEMENT_EMAILDATA);
    final IEmailData aEmailData = MicroTypeConverter.convertToNative(eEmailData, EmailData.class);

    // error message
    final String sErrorMessage = MicroUtils.getChildTextContent(eFailedMail, ELEMENT_ERRORMSG);
    final Exception aError = StringHelper.hasNoText(sErrorMessage) ? null : new Exception(sErrorMessage);

    return new FailedMailData(sID, aErrorDT, aSMTPSettings, aOriginalSentDT, aEmailData, aError);
}

From source file:com.helger.smtp.impl.EmailDataMicroTypeConverter.java

License:Apache License

@Nonnull
@ContainsSoftMigration/*w w  w  .j a va 2  s . c  om*/
public EmailData convertToNative(@Nonnull final IMicroElement eEmailData) {
    final String sEmailType = eEmailData.getAttributeValue(ATTR_TYPE);
    final EEmailType eEmailType = EEmailType.getFromIDOrNull(sEmailType);
    final EmailData aEmailData = new EmailData(eEmailType);

    final IMicroElement eFrom = eEmailData.getFirstChildElement(ELEMENT_FROM);
    aEmailData.setFrom(_readEmailAddress(eFrom));

    final List<IEmailAddress> aReplyTos = new ArrayList<IEmailAddress>();
    for (final IMicroElement eReplyTo : eEmailData.getAllChildElements(ELEMENT_REPLYTO))
        aReplyTos.add(_readEmailAddress(eReplyTo));
    aEmailData.setReplyTo(aReplyTos);

    final List<IEmailAddress> aTos = new ArrayList<IEmailAddress>();
    for (final IMicroElement eTo : eEmailData.getAllChildElements(ELEMENT_TO))
        aTos.add(_readEmailAddress(eTo));
    aEmailData.setTo(aTos);

    final List<IEmailAddress> aCcs = new ArrayList<IEmailAddress>();
    for (final IMicroElement eCc : eEmailData.getAllChildElements(ELEMENT_CC))
        aCcs.add(_readEmailAddress(eCc));
    aEmailData.setCc(aCcs);

    final List<IEmailAddress> aBccs = new ArrayList<IEmailAddress>();
    for (final IMicroElement eBcc : eEmailData.getAllChildElements(ELEMENT_BCC))
        aBccs.add(_readEmailAddress(eBcc));
    aEmailData.setBcc(aBccs);

    final String sSentDate = eEmailData.getAttributeValue(ELEMENT_SENTDATE);
    if (sSentDate != null) {
        final DateTime aDT = PDTWebDateUtils.getDateTimeFromXSD(sSentDate);
        if (aDT != null)
            aEmailData.setSentDate(aDT.withChronology(PDTConfig.getDefaultChronology()));
    }

    aEmailData.setSubject(eEmailData.getAttributeValue(ATTR_SUBJECT));
    aEmailData.setBody(MicroUtils.getChildTextContent(eEmailData, ELEMENT_BODY));

    final IMicroElement eAttachments = eEmailData.getFirstChildElement(ELEMENT_ATTACHMENTS);
    if (eAttachments != null) {
        // Default way: use converter
        aEmailData.setAttachments(MicroTypeConverter.convertToNative(eAttachments, EmailAttachmentList.class));
    } else {
        // For legacy stuff:
        final EmailAttachmentList aAttachments = new EmailAttachmentList();
        for (final IMicroElement eAttachment : eEmailData.getAllChildElements("attachment"))
            aAttachments.addAttachment(MicroTypeConverter.convertToNative(eAttachment, EmailAttachment.class));
        if (!aAttachments.isEmpty())
            aEmailData.setAttachments(aAttachments);
    }

    for (final IMicroElement eCustom : eEmailData.getAllChildElements(ELEMENT_CUSTOM))
        aEmailData.setAttribute(eCustom.getAttributeValue(ATTR_ID), eCustom.getTextContent());

    return aEmailData;
}

From source file:name.martingeisse.wicket.panel.simple.DateTimeTextFieldPanel.java

License:Open Source License

@Override
protected void onBeforeRender() {
    final Class<?> modelType = getType();
    final Object modelObject = getDefaultModelObject();
    if (modelType == DateTime.class) {
        final DateTime modelDateTime = (DateTime) modelObject;
        originalChronology = modelDateTime.getChronology();
        localizedChronology = originalChronology.withZone(MyWicketSession.get().getTimeZone());
        final DateTime localizedModelDateTime = modelDateTime.withChronology(localizedChronology);
        date = localizedModelDateTime.toLocalDate();
        time = localizedModelDateTime.toLocalTime();
    } else if (modelType == LocalDateTime.class) {
        final LocalDateTime modelDateTime = (LocalDateTime) modelObject;
        originalChronology = modelDateTime.getChronology();
        localizedChronology = originalChronology;
        date = modelDateTime.toLocalDate();
        time = modelDateTime.toLocalTime();
    } else {//  w  w w.j  a v a2 s . co  m
        throw new IllegalStateException("unsupported model type for DateTimeTextFieldPanel: " + modelType);
    }
    super.onBeforeRender();
}

From source file:name.martingeisse.wicket.panel.simple.DateTimeTextFieldPanel.java

License:Open Source License

@Override
protected void convertInput() {

    // get all required objects. Note: This method is invoked *before* the sub-text-fields
    // have stored their model values in this object, so we must get them manually.
    final Class<?> modelType = getType();
    final LocalDate date = getDateTextField().getConvertedInput();
    final LocalTime time = getTimeTextField().getConvertedInput();

    // convert the input
    if (modelType == DateTime.class) {
        final DateTime localizedDateTime = new DateTime(date.getYear(), date.getMonthOfYear(),
                date.getDayOfMonth(), time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(),
                time.getMillisOfSecond(), localizedChronology);
        setConvertedInputUnsafe(localizedDateTime.withChronology(originalChronology));
    } else if (modelType == LocalDateTime.class) {
        setConvertedInputUnsafe(new LocalDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(), time.getMillisOfSecond(),
                localizedChronology));/*from  ww w.  j  av a  2  s  .c  o  m*/
    } else {
        throw new IllegalStateException("unsupported model type for DateTimeTextFieldPanel: " + modelType);
    }

}

From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java

License:Apache License

/**
 * Method to recalculate rate./*from ww  w .  j a  v a  2s . c o  m*/
 *
 * @param _parameter Parameter as passed from the eFaps API.
 * @return new Return.
 * @throws EFapsException on error.
 */
public Return recalculateRate(final Parameter _parameter) throws EFapsException {
    final Instance docInst = Instance.get(_parameter.getParameterValue("docInst"));
    final PrintQuery print = new PrintQuery(docInst);
    print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal,
            CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId,
            CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
    print.execute();

    final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal);
    final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal);
    final DateTime dateDoc = print.<DateTime>getAttribute(CISales.DocumentSumAbstract.Date);
    final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name);
    final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
    final Instance currentInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
    final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst);
    final CurrencyInst curr = new CurrencyInst(currentInst);

    final PriceUtil priceUtil = new PriceUtil();
    final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
    final BigDecimal rate = rates[2];

    final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP);
    final BigDecimal gainloss = newCrossTotal.subtract(crossTotal);
    final Map<String, String[]> map = validateInfo(_parameter, gainloss);
    final String[] accs = map.get("accs");
    final String[] check = map.get("check");
    if (checkAccounts(accs, 0, check).length() > 0 && checkAccounts(accs, 1, check).length() > 0) {
        if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
            if (!tarCurr.equals(curr)) {
                final String[] accOids = map.get("accountOids");

                final Insert insert = new Insert(CIAccounting.Transaction);
                final StringBuilder description = new StringBuilder();
                final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                final String dateStr = dateDoc.withChronology(Context.getThreadContext().getChronology())
                        .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                description
                        .append(DBProperties
                                .getProperty("Accounting_TransactionRecalculateForm.TxnRecalculate.Label"))
                        .append(" ").append(nameDoc).append(" ").append(dateStr);
                insert.add(CIAccounting.Transaction.Description, description);
                insert.add(CIAccounting.Transaction.Date, _parameter.getParameterValue("date"));
                insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                insert.add(CIAccounting.Transaction.Status,
                        Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                insert.execute();

                final Instance instance = insert.getInstance();
                new Create().connectDocs2Transaction(_parameter, instance, docInst);

                final Insert insert2 = new Insert(CIAccounting.TransactionPositionCredit);
                insert2.add(CIAccounting.TransactionPositionCredit.TransactionLink, instance.getId());
                insert2.add(CIAccounting.TransactionPositionCredit.AccountLink,
                        Instance.get(accOids[1]).getId());
                insert2.add(CIAccounting.TransactionPositionCredit.CurrencyLink, curr.getInstance().getId());
                insert2.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                        curr.getInstance().getId());
                insert2.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { 1, 1 });
                insert2.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                insert2.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                insert2.execute();

                final Insert insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                insert3.add(CIAccounting.TransactionPositionDebit.TransactionLink, instance.getId());
                insert3.add(CIAccounting.TransactionPositionDebit.AccountLink,
                        Instance.get(accOids[0]).getId());
                insert3.add(CIAccounting.TransactionPositionDebit.CurrencyLink, curr.getInstance().getId());
                insert3.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, curr.getInstance().getId());
                insert3.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { 1, 1 });
                insert3.add(CIAccounting.TransactionPositionDebit.RateAmount, gainloss.abs().negate());
                insert3.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                insert3.execute();

                _parameter.put(ParameterValues.INSTANCE, docInst);
                new Accounting4DocSum().recalculateRate(_parameter);
            }
        }
    }
    return new Return();
}

From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java

License:Apache License

/**
 * Creates the gain loss4 document account.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return the return/*from ww w.jav a  2  s.  c  om*/
 * @throws EFapsException on error
 */
public Return createGainLoss4DocumentAccount(final Parameter _parameter) throws EFapsException {
    final Set<String> setAccounts = getAccounts4DocumentConfig(_parameter);

    final String[] oidsDoc = (String[]) Context.getThreadContext().getSessionAttribute(
            CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.selectedDocuments.name);
    final DateTime dateTo = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.transactionDate.name));
    for (final String oid : oidsDoc) {
        final Instance instDoc = Instance.get(oid);

        final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction2SalesDocument);
        attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction2SalesDocument.ToLink, instDoc);
        final AttributeQuery attrQuery = attrQuerBldr
                .getAttributeQuery(CIAccounting.Transaction2SalesDocument.FromLink);

        // filter classification Document
        final QueryBuilder attrQueryBldr2 = new QueryBuilder(CIAccounting.Transaction);
        attrQueryBldr2.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink,
                _parameter.getInstance().getId());
        attrQueryBldr2.addWhereAttrInQuery(CIAccounting.Transaction.ID, attrQuery);
        final AttributeQuery attrQuery2 = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID);

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
        queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery2);
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount,
                CIAccounting.TransactionPositionAbstract.RateAmount,
                CIAccounting.TransactionPositionAbstract.CurrencyLink,
                CIAccounting.TransactionPositionAbstract.RateCurrencyLink);
        final SelectBuilder selAcc = new SelectBuilder()
                .linkto(CIAccounting.TransactionPositionAbstract.AccountLink).oid();
        multi.addSelect(selAcc);
        multi.execute();
        final Map<String, AccountInfo> map = new HashMap<>();
        while (multi.next()) {
            final Instance accountInst = Instance.get(multi.<String>getSelect(selAcc));
            if (setAccounts.contains(accountInst.getOid())) {
                final BigDecimal oldRateAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount);
                final BigDecimal oldAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
                final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.RateCurrencyLink));
                final Instance currentInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.CurrencyLink));

                final PriceUtil priceUtil = new PriceUtil();
                final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
                final BigDecimal rate = rates[2];
                final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP);

                BigDecimal gainloss = BigDecimal.ZERO;
                if (!currentInst.equals(targetCurrInst)) {
                    gainloss = newAmount.subtract(oldAmount);
                } else {
                    gainloss = newAmount;
                }
                if (map.containsKey(accountInst.getOid())) {
                    final AccountInfo tarAcc = map.get(accountInst.getOid());
                    tarAcc.addAmount(gainloss);
                } else {
                    final AccountInfo tarAcc = new AccountInfo(accountInst, gainloss);
                    tarAcc.setAmountRate(gainloss);
                    tarAcc.setCurrInstance(currentInst);
                    map.put(accountInst.getOid(), tarAcc);
                }
            }
        }

        if (!map.isEmpty()) {
            Insert insert = null;
            CurrencyInst curr = null;
            BigDecimal gainlossSum = BigDecimal.ZERO;
            for (final Entry<String, AccountInfo> entry : map.entrySet()) {
                final AccountInfo tarAcc = entry.getValue();
                final Instance instAcc = Instance.get(entry.getKey());
                final BigDecimal gainloss = tarAcc.getAmount();
                gainlossSum = gainlossSum.add(gainloss);
                final Instance currInstance = tarAcc.getCurrInstance();
                curr = new CurrencyInst(currInstance);
                final Map<String, String[]> mapVal = validateInfo(_parameter, gainloss);
                final String[] accs = mapVal.get("accs");
                final String[] check = mapVal.get("check");

                if (checkAccounts(accs, 0, check).length() > 0) {
                    if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
                        final String[] accOids = mapVal.get("accountOids");
                        if (insert == null) {
                            final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                            final String dateStr = dateTo
                                    .withChronology(Context.getThreadContext().getChronology())
                                    .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                            final StringBuilder description = new StringBuilder();
                            description
                                    .append(DBProperties
                                            .getProperty("Accounting_DocumentAccountForm.TxnRecalculate.Label"))
                                    .append(" ").append(dateStr);
                            insert = new Insert(CIAccounting.Transaction);
                            insert.add(CIAccounting.Transaction.Description, description.toString());
                            insert.add(CIAccounting.Transaction.Date, dateTo);
                            insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                            insert.add(CIAccounting.Transaction.Status,
                                    Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                            insert.execute();
                        }

                        Insert insertPos = new Insert(CIAccounting.TransactionPositionCredit);
                        insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc.getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();

                        insertPos = new Insert(CIAccounting.TransactionPositionDebit);
                        insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc.getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount,
                                gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();
                    }
                }
            }
            if (insert != null) {
                final Instance instance = insert.getInstance();
                // create classifications
                final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType();
                final Insert relInsert1 = new Insert(classification1.getClassifyRelationType());
                relInsert1.add(classification1.getRelLinkAttributeName(), instance.getId());
                relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId());
                relInsert1.execute();

                final Insert classInsert1 = new Insert(classification1);
                classInsert1.add(classification1.getLinkAttributeName(), instance.getId());
                classInsert1.execute();

                final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss
                        .getType();
                final Insert relInsert = new Insert(classification.getClassifyRelationType());
                relInsert.add(classification.getRelLinkAttributeName(), instance.getId());
                relInsert.add(classification.getRelTypeAttributeName(), classification.getId());
                relInsert.execute();

                final Insert classInsert = new Insert(classification);
                classInsert.add(classification.getLinkAttributeName(), instance.getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink,
                        curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Rate,
                        new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                classInsert.execute();

                new Create().connectDocs2Transaction(_parameter, instance, instDoc);
            }
        }
    }

    return new Return();
}

From source file:org.efaps.ui.wicket.models.field.factories.DateTimeUIFactory.java

License:Apache License

/**
 * {@inheritDoc}/*from w w w .  j  a v  a  2  s .c  o m*/
 */
@Override
protected String getReadOnlyValue(final AbstractUIField _abstractUIField) throws EFapsException {
    String strValue = "";
    final Object valueTmp = _abstractUIField.getValue()
            .getReadOnlyValue(_abstractUIField.getParent().getMode());
    if (valueTmp instanceof DateTime) {
        final DateTime datetime = (DateTime) valueTmp;
        final DateTime dateTmp = datetime.withChronology(Context.getThreadContext().getChronology());
        final String formatStr = Configuration.getAttribute(Configuration.ConfigAttribute.FORMAT_DATETIME);
        final DateTimeFormatter formatter;
        if (formatStr.matches("^[S,M,L,F,-]{2}$")) {
            formatter = DateTimeFormat.forStyle(formatStr);
        } else {
            formatter = DateTimeFormat.forPattern(formatStr);
        }
        strValue = dateTmp.toString(formatter.withLocale(Context.getThreadContext().getLocale()));
    }
    return strValue;
}

From source file:org.efaps.ui.wicket.models.field.factories.DateUIFactory.java

License:Apache License

/**
 * {@inheritDoc}//from  w  ww  .  ja v a2s  .  c om
 */
@Override
protected String getReadOnlyValue(final AbstractUIField _abstractUIField) throws EFapsException {
    String strValue = "";
    final Object valueTmp = _abstractUIField.getValue()
            .getReadOnlyValue(_abstractUIField.getParent().getMode());
    if (valueTmp instanceof DateTime) {
        final DateTime datetime = (DateTime) valueTmp;
        final DateTime dateTmp = datetime.withChronology(Context.getThreadContext().getChronology())
                .withTimeAtStartOfDay();
        final String formatStr = Configuration.getAttribute(Configuration.ConfigAttribute.FORMAT_DATE);
        final DateTimeFormatter formatter;
        if (formatStr.matches("^[S,M,L,F,-]{2}$")) {
            formatter = DateTimeFormat.forStyle(formatStr);
        } else {
            formatter = DateTimeFormat.forPattern(formatStr);
        }
        strValue = dateTmp.toString(formatter.withLocale(Context.getThreadContext().getLocale()));
    }
    return strValue;
}

From source file:org.efaps.util.DateTimeUtil.java

License:Apache License

/**
 * The given DateTime will be normalized to ISO calendar with time zone
 * from {@link EFapsSystemConfiguration#KERNEL kernel system configuration}
 * &quot;Admin_Common_DataBaseTimeZone&quot;. In case that the
 * system configuration is missing &quot;UTC&quot; will be used.
 *
 * @param _date     date to normalize/*  w  w w  . jav  a 2 s  . c  o m*/
 * @return DateTime normalized for the database
 * @throws EFapsException on error
 */
public static DateTime normalize(final DateTime _date) throws EFapsException {
    // reads the Value from "Admin_Common_DataBaseTimeZone"
    final String timezoneID = EFapsSystemConfiguration.get().getAttributeValue(KernelSettings.DBTIMEZONE);
    final ISOChronology chron;
    if (timezoneID != null) {
        final DateTimeZone timezone = DateTimeZone.forID(timezoneID);
        chron = ISOChronology.getInstance(timezone);
    } else {
        chron = ISOChronology.getInstanceUTC();
    }
    return _date.withChronology(chron);
}

From source file:org.forgerock.openidm.util.DateUtil.java

License:CDDL license

/**
 * Formats a given DateTime into a timestamp.
 *
 * @param date/*from  w  w  w . j  a v a 2  s .  com*/
 *            DateTime object to convert
 * @return String containing the formatted timestamp
 */
public String formatDateTime(DateTime date) {
    return date.withChronology(chrono).toString();
}