Example usage for java.util GregorianCalendar get

List of usage examples for java.util GregorianCalendar get

Introduction

In this page you can find the example usage for java.util GregorianCalendar get.

Prototype

public int get(int field) 

Source Link

Document

Returns the value of the given calendar field.

Usage

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.SolrResultUploader.java

/**
 * Determine the database name, based on the composite key, or null if any of the composite key replacements could not be resolved.
 *
 * XXX: We only consider the replacement values from the first document given.
 *
 * @param name//from w w  w .j  av a 2s  .  co  m
 * @param nameComposition
 * @param namePrerequisitesExpression
 * @param documents
 * @return String
 */
private String determineAlternateDatabaseName(final String name, final String nameComposition,
        final String namePrerequisitesExpression, final List<SolrInputDocument> documents) {
    GregorianCalendar calendar = new GregorianCalendar();

    calendar.setTime(new Date());

    String result;

    result = nameComposition.replace("{name}", name).trim();

    result = result.replace("{year}", String.format("%04d", calendar.get(calendar.YEAR)));
    result = result.replace("{month}", String.format("%02d", calendar.get(calendar.MONTH)));

    if (documents.size() > 0) {
        final SolrInputDocument document = documents.get(0);

        while (result.contains("{") && result.indexOf("}") > result.indexOf("{")) {
            String fieldName = result.substring(result.indexOf("{") + 1, result.indexOf("}"));

            if (document.containsKey(fieldName))
                result = result.replace("{" + fieldName + "}", document.getFieldValue(fieldName).toString());
            else {
                if (logger.isDebugEnabled())
                    logger.debug(String.format(
                            "Field '%s' was missing from document with ID '%s' - will revert back to default collection '%s'",
                            fieldName, document.getFieldValue(REFERENCE_FIELD), name));

                return null;
            }
        }

        // Also check the pre-requisite expression - only return a composite database name if it's met

        if (StringUtils.hasText(namePrerequisitesExpression)) {
            final ExpressionParser parser = new SpelExpressionParser();

            final Map<String, Object> values = new HashMap<String, Object>();

            for (Map.Entry<String, SolrInputField> entry : document.entrySet()) {
                // XXX: Always get just the first value

                /* if (entry.getValue().getValueCount() > 1)
                   values.put(entry.getKey(), entry.getValue().getValues());
                else */
                values.put(entry.getKey(), entry.getValue().getFirstValue());
            }

            StandardEvaluationContext context = new StandardEvaluationContext(new Object() {
                public Map<String, Object> getValues() {
                    return values;
                }
            });

            if (!parser.parseExpression(namePrerequisitesExpression).getValue(context, Boolean.class)) {
                if (logger.isDebugEnabled())
                    logger.debug(String.format(
                            "Pre-requisite expression '%s' failed to match against document with ID '%s' - will revert back to default collection '%s'",
                            namePrerequisitesExpression, document.get(REFERENCE_FIELD).toString(), name));

                return null;
            }
        }
    }

    return result;
}

From source file:fr.paris.lutece.plugins.document.modules.solr.indexer.SolrDocIndexer.java

/**
 * Get item//from w w  w  .  j a  va2s.c om
 * @param portlet The portlet
 * @param document The document
 * @return The item
 * @throws IOException
 */
private SolrItem getItem(Portlet portlet, Document document) throws IOException {
    // the item
    SolrItem item = new SolrItem();
    item.setUid(getResourceUid(Integer.valueOf(document.getId()).toString(),
            DocumentIndexerUtils.CONSTANT_TYPE_RESOURCE));
    item.setDate(document.getDateModification());
    item.setType(document.getType());
    item.setSummary(document.getSummary());
    item.setTitle(document.getTitle());
    item.setSite(SolrIndexerService.getWebAppName());
    item.setRole("none");

    if (portlet != null) {
        item.setDocPortletId(document.getId() + SolrConstants.CONSTANT_AND + portlet.getId());
    }

    item.setXmlContent(document.getXmlValidatedContent());

    // Reload the full object to get all its searchable attributes
    UrlItem url = new UrlItem(SolrIndexerService.getBaseUrl());
    url.addParameter(PARAMETER_DOCUMENT_ID, document.getId());
    url.addParameter(PARAMETER_PORTLET_ID, portlet.getId());
    item.setUrl(url.getUrl());

    // Date Hierarchy
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(document.getDateModification());
    item.setHieDate(calendar.get(GregorianCalendar.YEAR) + "/" + (calendar.get(GregorianCalendar.MONTH) + 1)
            + "/" + calendar.get(GregorianCalendar.DAY_OF_MONTH) + "/");

    List<String> categorie = new ArrayList<String>();

    for (Category cat : document.getCategories()) {
        categorie.add(cat.getName());
    }

    item.setCategorie(categorie);

    // The content
    String strContentToIndex = getContentToIndex(document, item);
    ContentHandler handler = null;
    if (PARAMETER_DOCUMENT_MAX_CHARS != null) {
        handler = new BodyContentHandler(PARAMETER_DOCUMENT_MAX_CHARS);
    } else {
        handler = new BodyContentHandler();
    }

    Metadata metadata = new Metadata();

    try {
        new HtmlParser().parse(new ByteArrayInputStream(strContentToIndex.getBytes()), handler, metadata,
                new ParseContext());
    } catch (SAXException e) {
        throw new AppException("Error during document parsing.");
    } catch (TikaException e) {
        throw new AppException("Error during document parsing.");
    }

    item.setContent(handler.toString());

    return item;
}

From source file:org.openhab.binding.powermax.internal.message.PowerMaxCommDriver.java

/**
 * Send a message to set the alarm time and date using the system time and date
 *
 * @return true if the message was sent or false if not
 *///from   w ww. jav a 2 s . c  o  m
public boolean sendSetTime() {
    logger.debug("sendSetTime()");

    boolean done = false;

    GregorianCalendar cal = new GregorianCalendar();
    if (cal.get(Calendar.YEAR) >= 2000) {
        logger.debug(String.format("sendSetTime(): sync time %02d/%02d/%04d %02d:%02d:%02d",
                cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR),
                cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)));

        byte[] dynPart = new byte[6];
        dynPart[0] = (byte) cal.get(Calendar.SECOND);
        dynPart[1] = (byte) cal.get(Calendar.MINUTE);
        dynPart[2] = (byte) cal.get(Calendar.HOUR_OF_DAY);
        dynPart[3] = (byte) cal.get(Calendar.DAY_OF_MONTH);
        dynPart[4] = (byte) (cal.get(Calendar.MONTH) + 1);
        dynPart[5] = (byte) (cal.get(Calendar.YEAR) - 2000);

        done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.SETTIME, dynPart), false, 0);

        cal.set(Calendar.MILLISECOND, 0);
        syncTimeCheck = cal.getTimeInMillis();
    } else {
        logger.warn(
                "PowerMax alarm binding: time not synchronized; please correct the date/time of your openHAB server");
        syncTimeCheck = null;
    }
    return done;
}

From source file:TimePeriod.java

/**
 * Krzt den zeitraum, so das nur ganze Monate brig bleiben
 *///from w w w . j a  v a 2 s .  co m
public void setOnlyCompleteMonth() {
    // Auf den Beginn des nchsten monats setzen
    if (from.get(Calendar.DAY_OF_MONTH) != 1) {
        while (from.get(Calendar.DAY_OF_MONTH) != 1) {
            from.setTimeInMillis(from.getTimeInMillis() + ONE_DAY);
        }
        setMidnight(from);
    }
    // Auf das Ende des Vorherigen Monats setzen
    GregorianCalendar temp = new GregorianCalendar();
    temp.setTimeInMillis(to.getTimeInMillis() + ONE_DAY);
    if (temp.get(Calendar.MONTH) == to.get(Calendar.MONTH)) {
        while (to.get(Calendar.MONTH) == temp.get(Calendar.MONTH)) {
            to.setTimeInMillis(to.getTimeInMillis() - ONE_DAY);
        }
        set2359(to);
    }
}

From source file:mekhq.campaign.finances.Finances.java

public void newDay(Campaign campaign) {
    DecimalFormat formatter = new DecimalFormat();
    CampaignOptions campaignOptions = campaign.getCampaignOptions();
    GregorianCalendar calendar = campaign.getCalendar();

    // check for a new year
    if (calendar.get(Calendar.MONTH) == 0 && calendar.get(Calendar.DAY_OF_MONTH) == 1) {
        // clear the ledger
        newFiscalYear(calendar.getTime());
    }/*from  ww  w.  ja  v  a  2  s  .c  o m*/

    // Handle contract payments
    if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
        for (Contract contract : campaign.getActiveContracts()) {
            credit(contract.getMonthlyPayOut(), Transaction.C_CONTRACT,
                    String.format(resourceMap.getString("MonthlyContractPayment.text"), contract.getName()),
                    calendar.getTime());
            campaign.addReport(String.format(resourceMap.getString("ContractPaymentCredit.text"),
                    formatter.format(contract.getMonthlyPayOut()), contract.getName()));

            if (campaignOptions.getUseAtB() && campaignOptions.getUseShareSystem()
                    && contract instanceof AtBContract) {
                long shares = contract.getMonthlyPayOut() * ((AtBContract) contract).getSharesPct() / 100;
                if (debit(shares, Transaction.C_SALARY,
                        String.format(resourceMap.getString("ContractSharePayment.text"), contract.getName()),
                        calendar.getTime())) {
                    campaign.addReport(String.format(resourceMap.getString("DistributedShares.text"),
                            formatter.format(shares)));
                } else {
                    /*
                     * This should not happen, as the shares payment is less than the contract
                     * payment that has just been made.
                     */
                    campaign.addReport(String.format(resourceMap.getString("NotImplemented.text"), "shares"));
                }
            }
        }
    }

    // Handle assets
    for (Asset asset : assets) {
        if (asset.getSchedule() == SCHEDULE_YEARLY && campaign.calendar.get(Calendar.DAY_OF_YEAR) == 1) {
            credit(asset.getIncome(), Transaction.C_MISC, "income from " + asset.getName(),
                    campaign.getCalendar().getTime());
            campaign.addReport(String.format(resourceMap.getString("AssetPayment.text"),
                    DecimalFormat.getInstance().format(asset.getIncome()), asset.getName()));
        } else if (asset.getSchedule() == SCHEDULE_MONTHLY
                && campaign.calendar.get(Calendar.DAY_OF_MONTH) == 1) {
            credit(asset.getIncome(), Transaction.C_MISC, "income from " + asset.getName(),
                    campaign.getCalendar().getTime());
            campaign.addReport(String.format(resourceMap.getString("AssetPayment.text"),
                    DecimalFormat.getInstance().format(asset.getIncome()), asset.getName()));
        }
    }

    // Handle peacetime operating expenses, payroll, and loan payments
    if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
        if (campaignOptions.usePeacetimeCost()) {
            if (!campaignOptions.showPeacetimeCost()) {
                if (debit(campaign.getPeacetimeCost(), Transaction.C_MAINTAIN,
                        resourceMap.getString("PeacetimeCosts.title"), calendar.getTime())) {
                    campaign.addReport(String.format(resourceMap.getString("PeacetimeCosts.text"),
                            formatter.format(campaign.getPeacetimeCost())));
                } else {
                    campaign.addReport(
                            String.format(resourceMap.getString("NotImplemented.text"), "for operating costs"));
                }
            } else {
                if (debit(campaign.getMonthlySpareParts(), Transaction.C_MAINTAIN,
                        resourceMap.getString("PeacetimeCostsParts.title"), calendar.getTime())) {
                    campaign.addReport(String.format(resourceMap.getString("PeacetimeCostsParts.text"),
                            formatter.format(campaign.getMonthlySpareParts())));
                } else {
                    campaign.addReport(
                            String.format(resourceMap.getString("NotImplemented.text"), "for spare parts"));
                }
                if (debit(campaign.getMonthlyAmmo(), Transaction.C_MAINTAIN,
                        resourceMap.getString("PeacetimeCostsAmmunition.title"), calendar.getTime())) {
                    campaign.addReport(String.format(resourceMap.getString("PeacetimeCostsAmmunition.text"),
                            formatter.format(campaign.getMonthlySpareParts())));
                } else {
                    campaign.addReport(String.format(resourceMap.getString("NotImplemented.text"),
                            "for training munitions"));
                }
                if (debit(campaign.getMonthlyFuel(), Transaction.C_MAINTAIN,
                        resourceMap.getString("PeacetimeCostsFuel.title"), calendar.getTime())) {
                    campaign.addReport(String.format(resourceMap.getString("PeacetimeCostsFuel.text"),
                            formatter.format(campaign.getMonthlySpareParts())));
                } else {
                    campaign.addReport(String.format(resourceMap.getString("NotImplemented.text"), "for fuel"));
                }
            }
        }
        if (campaignOptions.payForSalaries()) {
            if (debit(campaign.getPayRoll(), Transaction.C_SALARY, resourceMap.getString("Salaries.title"),
                    calendar.getTime())) {
                campaign.addReport(String.format(resourceMap.getString("Salaries.text"),
                        formatter.format(campaign.getPayRoll())));
            } else {
                campaign.addReport(
                        String.format(resourceMap.getString("NotImplemented.text"), "payroll costs"));
            }
        }

        // Handle overhead expenses
        if (campaignOptions.payForOverhead()) {
            if (debit(campaign.getOverheadExpenses(), Transaction.C_OVERHEAD,
                    resourceMap.getString("Overhead.title"), calendar.getTime())) {
                campaign.addReport(String.format(resourceMap.getString("Overhead.text"),
                        formatter.format(campaign.getOverheadExpenses())));
            } else {
                campaign.addReport(
                        String.format(resourceMap.getString("NotImplemented.text"), "overhead costs"));
            }
        }
    }

    ArrayList<Loan> newLoans = new ArrayList<Loan>();
    for (Loan loan : loans) {
        if (loan.checkLoanPayment(campaign.getCalendar())) {
            if (debit(loan.getPaymentAmount(), Transaction.C_LOAN_PAYMENT,
                    String.format(resourceMap.getString("Loan.title"), loan.getDescription()),
                    campaign.getCalendar().getTime())) {
                campaign.addReport(String.format(resourceMap.getString("Loan.text"),
                        DecimalFormat.getInstance().format(loan.getPaymentAmount()), loan.getDescription()));
                loan.paidLoan();
            } else {
                campaign.addReport(String.format(resourceMap.getString("Loan.insufficient"),
                        loan.getDescription(), DecimalFormat.getInstance().format(loan.getPaymentAmount())));
                loan.setOverdue(true);
            }
        }
        if (loan.getRemainingPayments() > 0) {
            newLoans.add(loan);
        } else {
            campaign.addReport(String.format(resourceMap.getString("Loan.paid"), loan.getDescription()));
        }
    }
    if (null != wentIntoDebt && !isInDebt()) {
        wentIntoDebt = null;
    }
    loans = newLoans;
}

From source file:com.mb.framework.util.DateTimeUtil.java

/**
 * Method called to convert a GregorianCalendar object to a date field of
 * the format of YYYYMMDD./*from  w  ww. ja  va2 s.  c om*/
 * 
 * @param anotherDt
 *            GregorianCalendar object to be converted.
 * @return Date created, must be in YYYYMMDD format.
 */
public static String convertGregorianToString(GregorianCalendar anotherDt) {
    StringBuffer buffy = new StringBuffer();
    String sDate = null;

    try {
        String day = String.valueOf(anotherDt.get(Calendar.DAY_OF_MONTH));
        String month = String.valueOf(anotherDt.get(Calendar.MONTH));
        String year = String.valueOf(anotherDt.get(Calendar.YEAR));
        buffy.append(year);
        if (month.length() == 0) {
            month = "00";
        } else if (month.length() == 1) {
            month = "0" + month;
        }

        buffy.append(month);
        if (day.length() == 0) {
            day = "00";
        } else if (day.length() == 1) {
            day = "0" + month;
        }
        buffy.append(day);
        sDate = buffy.toString();
    } catch (NumberFormatException e) {
        logger.error("encounting error while convert Gregorian date to string .", e);
    }

    return sDate;
}

From source file:mekhq.Utilities.java

public static int getDiffPartialYears(Date date, GregorianCalendar b) {
    GregorianCalendar a = new GregorianCalendar();
    a.setTime(date);/*from  www.  j  a va2  s .  co  m*/
    int diff = b.get(GregorianCalendar.YEAR) - a.get(GregorianCalendar.YEAR);
    if (diff == 0 && countDaysBetween(a.getTime(), b.getTime()) > 0) {
        return 1;
    }
    return diff;
}

From source file:mekhq.Utilities.java

public static int getDiffFullYears(Date date, GregorianCalendar b) {
    GregorianCalendar a = new GregorianCalendar();
    a.setTime(date);// w  ww.  j a  va 2 s. c om
    int diff = b.get(GregorianCalendar.YEAR) - a.get(GregorianCalendar.YEAR);
    if (a.get(GregorianCalendar.MONTH) > b.get(GregorianCalendar.MONTH)
            || (a.get(GregorianCalendar.MONTH) == b.get(GregorianCalendar.MONTH)
                    && a.get(GregorianCalendar.DATE) > b.get(GregorianCalendar.DATE))) {
        diff--;
    }
    return diff;
}

From source file:com.sapienter.jbilling.client.payment.PaymentCrudAction.java

@Override
protected ForwardAndMessage doSetup() {
    CreditCardDTO ccDto = null;// www.ja va 2  s  .  c  o  m
    AchDTO achDto = null;
    PaymentInfoChequeDTO chequeDto = null;

    boolean isEdit = "edit".equals(request.getParameter("submode"));

    // if an invoice was selected, pre-populate the amount field
    InvoiceDTO invoiceDto = (InvoiceDTO) session.getAttribute(Constants.SESSION_INVOICE_DTO);
    PaymentDTOEx paymentDto = (PaymentDTOEx) session.getAttribute(Constants.SESSION_PAYMENT_DTO);

    if (invoiceDto != null) {
        LOG.debug("setting payment with invoice:" + invoiceDto.getId());

        myForm.set(FIELD_AMOUNT, invoiceDto.getBalance().toString());
        //paypal can't take i18n amounts
        session.setAttribute("jsp_paypay_amount", invoiceDto.getBalance());
        myForm.set(FIELD_CURRENCY, invoiceDto.getCurrency().getId());
    } else if (paymentDto != null) {
        // this works for both refunds and payouts
        LOG.debug("setting form with payment:" + paymentDto.getId());
        myForm.set(FIELD_ID, paymentDto.getId());
        myForm.set(FIELD_AMOUNT, paymentDto.getAmount().toString());
        setFormDate(FIELD_GROUP_DATE, paymentDto.getPaymentDate());
        myForm.set(FIELD_CURRENCY, paymentDto.getCurrency().getId());
        ccDto = paymentDto.getCreditCard();
        achDto = paymentDto.getAch();
        chequeDto = paymentDto.getCheque();
    } else { // this is not an invoice selected, it's the first call
        LOG.debug("setting payment without invoice");
        // the date might come handy
        setFormDate(FIELD_GROUP_DATE, Calendar.getInstance().getTime());
        // make the default real-time
        myForm.set(FIELD_PROCESS_NOW, new Boolean(true));
        // find out if this is a payment or a refund
    }

    boolean isRefund = session.getAttribute("jsp_is_refund") != null;

    // populate the credit card fields with the cc in file
    // if this is a payment creation only
    if (!isRefund && !isEdit && ((String) myForm.get(FIELD_CC_NUMBER)).length() == 0) {
        // normal payment, get the selected user cc
        // if the user has a credit card, put it (this is a waste for
        // cheques, but it really doesn't hurt)
        LOG.debug("getting this user's cc");
        UserDTOEx user = getSessionUser();
        ccDto = user.getCreditCard();
        achDto = user.getAch();
    }

    if (ccDto != null) {
        String ccNumber = ccDto.getNumber();
        // mask cc number
        ccNumber = maskCreditCard(ccNumber);
        myForm.set(FIELD_CC_NUMBER, ccNumber);
        myForm.set(FIELD_CC_NAME, ccDto.getName());
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(ccDto.getCcExpiry());
        myForm.set(FIELD_GROUP_CC_EXPIRY + "_month", String.valueOf(cal.get(GregorianCalendar.MONTH) + 1));
        myForm.set(FIELD_GROUP_CC_EXPIRY + "_year", String.valueOf(cal.get(GregorianCalendar.YEAR)));
    }

    if (achDto != null) {
        myForm.set(FIELD_ACH_ABA_CODE, achDto.getAbaRouting());
        myForm.set(FIELD_ACH_ACCOUNT_NUMBER, achDto.getBankAccount());
        myForm.set(FIELD_ACH_BANK_NAME, achDto.getBankName());
        myForm.set(FIELD_ACH_ACCOUNT_NAME, achDto.getAccountName());
        myForm.set(FIELD_ACH_ACCOUNT_TYPE, achDto.getAccountType());
    }

    if (chequeDto != null) {
        myForm.set(FIELD_CHEQUE_BANK, chequeDto.getBank());
        myForm.set(FIELD_CHEQUE_NUMBER, chequeDto.getNumber());
        setFormDate(FIELD_GROUP_CHEQUE_DATE, chequeDto.getDate());
    }

    ForwardAndMessage result = new ForwardAndMessage(FORWARD_EDIT);
    // if this payment is direct from an order, continue with the
    // page without invoice list
    if (request.getParameter("direct") != null) {
        // the date won't be shown, and it has to be initialized
        setFormDate(FIELD_GROUP_DATE, Calendar.getInstance().getTime());
        myForm.set(FIELD_PAY_METHOD, "cc");
        result = new ForwardAndMessage(FORWARD_FROM_ORDER, MESSAGE_INVOICE_GENERATED);
    }

    // if this is a payout, it has its own page
    if (request.getParameter("payout") != null) {
        result = new ForwardAndMessage(FORWARD_PAYOUT);
    }

    // payment edition has a different layout
    if (isEdit) {
        result = new ForwardAndMessage(FORWARD_UPDATE);
    }

    return result;
}

From source file:ca.mudar.parkcatcher.ui.fragments.DetailsFragment.java

/**
 * Implementation of LoaderCallbacks// w w  w  .j a v a2 s. c o  m
 */
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {

    final GregorianCalendar parkingCalendar = parkingApp.getParkingCalendar();

    final int dayOfWeek = (parkingCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ? 7
            : parkingCalendar.get(Calendar.DAY_OF_WEEK) - 1);
    final double parkingHour = parkingCalendar.get(Calendar.HOUR_OF_DAY)
            + Math.round(parkingCalendar.get(Calendar.MINUTE) / 0.6) / 100.00d;

    final double hourOfWeek = parkingHour + (dayOfWeek - 1) * 24;

    // API uses values 0-365 (or 364)
    final int dayOfYear = parkingCalendar.get(Calendar.DAY_OF_YEAR) - 1;

    final int duration = parkingApp.getParkingDuration();

    final Uri uriPost = Posts.buildPostTimedUri(String.valueOf(mIdPost), String.valueOf(hourOfWeek),
            String.valueOf(hourOfWeek + duration), String.valueOf(dayOfYear));

    return new CursorLoader(getSherlockActivity().getApplicationContext(), uriPost, PostDetailsQuery.PROJECTION,
            null, new String[] { Double.toString(hourOfWeek), Integer.toString(duration),
                    Integer.toString(dayOfYear) },
            null);
}