Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

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

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:mekhq.campaign.mission.Contract.java

/**
 * Only do this at the time the contract is set up, otherwise amounts may change after
 * the ink is signed, which is a no-no.//from www .j  a v  a  2  s .c  o  m
 * @param c
 */
public void calculateContract(Campaign c) {

    //calculate base amount
    baseAmount = (long) (paymentMultiplier * getLength() * c.getContractBase());

    //calculate overhead
    switch (overheadComp) {
    case OH_HALF:
        overheadAmount = (long) (0.5 * c.getOverheadExpenses() * getLength());
        break;
    case OH_FULL:
        overheadAmount = 1 * c.getOverheadExpenses() * getLength();
        break;
    default:
        overheadAmount = 0;
    }

    //calculate support amount
    if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod()
            .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) {
        supportAmount = (long) ((straightSupport / 100.0) * c.getPeacetimeCost() * getLength());
    } else {
        long maintCosts = 0;
        for (Unit u : c.getUnits()) {
            if (u.getEntity() instanceof Infantry && !(u.getEntity() instanceof BattleArmor)) {
                continue;
            }
            maintCosts += u.getWeeklyMaintenanceCost();
        }
        maintCosts *= 4;
        supportAmount = (long) ((straightSupport / 100.0) * maintCosts * getLength());
    }

    //calculate transportation costs
    if (null != getPlanet()) {
        JumpPath jumpPath = c.calculateJumpPath(c.getCurrentPlanet(), getPlanet());

        // FM:Mercs transport payments take into account owned transports and do not use CampaignOps dropship costs.
        // CampaignOps doesn't care about owned transports and does use its own dropship costs.
        boolean campaignOps = c.getCampaignOptions().useEquipmentContractBase();
        transportAmount = (long) ((transportComp / 100.0) * 2 * c.calculateCostPerJump(campaignOps, campaignOps)
                * jumpPath.getJumps());
    }

    //calculate transit amount for CO
    if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod()
            .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) {
        //contract base * transport period * reputation * employer modifier
        transitAmount = (long) (c.getContractBase()
                * (((c.calculateJumpPath(c.getCurrentPlanet(), getPlanet()).getJumps()) * 2) / 4)
                * (c.getUnitRatingMod() * .2 + .5) * 1.2);
    } else {
        transitAmount = 0;
    }

    signingAmount = (long) ((signBonus / 100.0)
            * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));

    advanceAmount = (long) ((advancePct / 100.0)
            * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));

    if (mrbcFee) {
        feeAmount = (long) (0.05
                * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));
    } else {
        feeAmount = 0;
    }

    // only adjust the start date for travel if the start date is currently null
    boolean adjustStartDate = false;
    if (null == startDate) {
        startDate = c.getCalendar().getTime();
        adjustStartDate = true;
    }
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(startDate);
    if (adjustStartDate && null != c.getPlanet(planetId)) {
        int days = (int) Math.ceil(c.calculateJumpPath(c.getCurrentPlanet(), getPlanet())
                .getTotalTime(Utilities.getDateTimeDay(cal), c.getLocation().getTransitTime()));
        while (days > 0) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            days--;
        }
        startDate = cal.getTime();
    }
    int months = getLength();
    while (months > 0) {
        cal.add(Calendar.MONTH, 1);
        months--;
    }
    endDate = cal.getTime();
}

From source file:org.squale.squalix.core.Scheduler.java

/**
 * Ralise les tches de niveau application (cration des graphes, calculs,...)
 * // w  w w  . java2  s .  c  o  m
 * @param pCurrentAudit l'audit courant.
 * @param pApplicationBO l'application sur lequel calculer les rsultats.
 * @roseuid 42CE40E102B8
 */
private void createNewAudit(final AuditBO pCurrentAudit, final ApplicationBO pApplicationBO) {
    ApplicationBO application = null;
    // on ne cre pas de nouvelles transactions car il faut faut que la transaction
    // pour cette mthode soit la meme que pour la mthode appelante de cette mthode
    try {
        Long applicationId = new Long(pApplicationBO.getId());
        application = (ApplicationBO) ApplicationDAOImpl.getInstance().get(mSession, applicationId);
        GregorianCalendar cal = new GregorianCalendar();
        // Cration d'un nouvel audit si il s'agit d'un audit de suivi
        if (pCurrentAudit.getType().equals(AuditBO.NORMAL)) {
            // Cration d'un nouvel audit
            AuditBO audit = new AuditBO();
            // Ajout de la frquence d'audit  la date courante
            cal.add(Calendar.DATE, pApplicationBO.getAuditFrequency());
            audit.setDate(cal.getTime());
            audit.setStatus(AuditBO.NOT_ATTEMPTED);
            audit.setType(pCurrentAudit.getType());
            AuditDAOImpl.getInstance().create(mSession, audit);
            // Ajout du nouvel audit  l'application
            application.addAudit(audit);
            ApplicationDAOImpl.getInstance().save(mSession, application);
        }
    } catch (Exception e) {
        LOGGER.error(CoreMessages.getString("exception"), e);
    }
}

From source file:org.novoj.utils.datePattern.DatePatternConverter.java

/**
 * Method returns date object with normalized time. When resetTime = true, time will be set to 0:0:0.0.
 * When date respresents current day (current date) and pattern doesn't contain appropriate pattern parts for
 * hour, minute, second, milliseconds - those values will be set to current time values, otherwise they will be
 * set to initial values (ie. 0).//from w w w . ja v a 2  s.c o  m
 */
private static Date normalizeHours(Calendar nowCld, Date date, Locale locale, String pattern,
        boolean resetTime) {
    GregorianCalendar dateCld = new GregorianCalendar();
    dateCld.setTime(date);
    boolean currentYear = nowCld.get(Calendar.YEAR) == dateCld.get(Calendar.YEAR);
    boolean currentMonth = nowCld.get(Calendar.MONTH) == dateCld.get(Calendar.MONTH);
    boolean currentDay = nowCld.get(Calendar.DAY_OF_MONTH) == dateCld.get(Calendar.DAY_OF_MONTH);
    //noinspection OverlyComplexBooleanExpression
    if (!resetTime && currentYear && currentMonth && currentDay) {
        //set current time
        if (pattern.toLowerCase(locale).indexOf('h') == -1) {
            dateCld.set(Calendar.HOUR, nowCld.get(Calendar.HOUR));
        }
        if (pattern.indexOf('m') == -1) {
            dateCld.set(Calendar.MINUTE, nowCld.get(Calendar.MINUTE));
        }
        if (pattern.indexOf('s') == -1) {
            dateCld.set(Calendar.SECOND, nowCld.get(Calendar.SECOND));
        }
        if (pattern.indexOf('S') == -1) {
            dateCld.set(Calendar.MILLISECOND, nowCld.get(Calendar.MILLISECOND));
        }
    } else {
        //set zero time
        if (pattern.toLowerCase(locale).indexOf('h') == -1) {
            dateCld.set(Calendar.HOUR, 0);
        }
        if (pattern.indexOf('m') == -1) {
            dateCld.set(Calendar.MINUTE, 0);
        }
        if (pattern.indexOf('s') == -1) {
            dateCld.set(Calendar.SECOND, 0);
        }
        if (pattern.indexOf('S') == -1) {
            dateCld.set(Calendar.MILLISECOND, 0);
        }
    }
    return dateCld.getTime();
}

From source file:org.kuali.continuity.admin.main.server.SimpleServiceImpl.java

Date getDateFromString(String dateString) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.set(Calendar.MONTH, Integer.parseInt(dateString.substring(0, 2)) - 1);
    gc.set(Calendar.DATE, Integer.parseInt(dateString.substring(3, 5)));
    gc.set(Calendar.YEAR, Integer.parseInt(dateString.substring(6, 10)));
    Date ret = gc.getTime();
    return ret;/*from  ww w  . j  a  v a2s. co m*/
}

From source file:net.sourceforge.eclipsetrader.yahoo.Feed.java

private void update() {
    // Builds the url for quotes download
    String host = "quote.yahoo.com"; //$NON-NLS-1$
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols="); //$NON-NLS-1$ //$NON-NLS-2$
    for (Iterator iter = map.values().iterator(); iter.hasNext();)
        url = url.append((String) iter.next() + "+"); //$NON-NLS-1$
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap"); //$NON-NLS-1$
    log.debug(url.toString());/*  www  . jav  a 2s.  co m*/

    // Read the last prices
    String line = ""; //$NON-NLS-1$
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(","); //$NON-NLS-1$
            if (line.indexOf(";") != -1) //$NON-NLS-1$
                item = line.split(";"); //$NON-NLS-1$

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US); //$NON-NLS-1$
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1) //$NON-NLS-1$
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1) //$NON-NLS-1$
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time)); //$NON-NLS-1$
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                log.error(e.getMessage() + ": " + line); //$NON-NLS-1$
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase((String) map.get(security))) {
                    security.setQuote(quote, open, high, low, close);
                }
            }
        }
        in.close();
    } catch (Exception e) {
        log.error(e);
    }
}

From source file:org.orcid.core.adapter.impl.Jaxb2JpaAdapterImpl.java

private Date toDate(XMLGregorianCalendar completionDate) {
    if (completionDate != null) {
        GregorianCalendar gregorianCalendar = completionDate.toGregorianCalendar();
        return gregorianCalendar.getTime();
    }//  w ww  . j  av a 2  s .c  o m
    return null;
}

From source file:org.agnitas.webservice.EmmWebservice.java

/**
 * Method for testing and sending a mailing
 * @param username Username from ws_admin_tbl
 * @param password Password from ws_admin_tbl
 * @param mailingID ID of mailing to be sent, normally returned by newEmailMailing(WithReply)
 * @param sendGroup Possible values:/*from ww w.ja v a  2 s  . c o  m*/
 * 'A': Only admin-subscribers (for testing)
 * 'T': Only test- and admin-subscribers (for testing)
 * 'W': All subscribers (only once for security reasons)
 * @param sendTime scheduled send-time in <B>seconds</B> since January 1, 1970, 00:00:00 GMT
 * @param stepping for artificially slowing down the send-process, seconds between deliviery of to mailing-blocks. Set to 0 unless you know what you are doing.
 * @param blocksize for artificially slowing down the send-process, number of mails in one mailing-block. Set to 0 unless you know what you are doing.
 * @return 1 == sucess
 * 0 == failure
 * @throws java.rmi.RemoteException needed by Apache Axis
 */
public int sendMailing(java.lang.String username, java.lang.String password, int mailingID,
        java.lang.String sendGroup, int sendTime, int stepping, int blocksize) throws java.rmi.RemoteException {
    ApplicationContext con = getWebApplicationContext();
    MailingDao dao = (MailingDao) con.getBean("MailingDao");
    int returnValue = 0;
    char mailingType = '\0';
    MessageContext msct = MessageContext.getCurrentContext();

    if (!authenticateUser(msct, username, password, 1)) {
        return returnValue;
    }

    try {
        Mailing aMailing = dao.getMailing(mailingID, 1);
        if (aMailing == null) {
            return returnValue;
        }

        if (sendGroup.equals("A")) {
            mailingType = MaildropEntry.STATUS_ADMIN;
        }

        if (sendGroup.equals("T")) {
            mailingType = MaildropEntry.STATUS_TEST;
        }

        if (sendGroup.equals("W")) {
            mailingType = MaildropEntry.STATUS_WORLD;
        }

        if (sendGroup.equals("R")) {
            mailingType = MaildropEntry.STATUS_DATEBASED;
        }

        if (sendGroup.equals("C")) {
            mailingType = MaildropEntry.STATUS_ACTIONBASED;
        }

        MaildropEntry drop = (MaildropEntry) con.getBean("MaildropEntry");
        GregorianCalendar aCal = new GregorianCalendar(TimeZone.getDefault());

        drop.setStatus(mailingType);
        drop.setGenDate(aCal.getTime());
        drop.setMailingID(aMailing.getId());
        drop.setCompanyID(aMailing.getCompanyID());
        if (sendTime != 0 && mailingType == MaildropEntry.STATUS_WORLD) {
            //set genstatus = 0, when senddate is in future
            drop.setGenStatus(0);
            //gendate is 3 hours before sendtime
            aCal.setTime(new java.util.Date(((long) sendTime - 10800) * 1000L));
            drop.setGenDate(aCal.getTime());
            aCal.setTime(new java.util.Date(((long) sendTime) * 1000L));
        } else {
            drop.setGenStatus(1);
        }
        drop.setSendDate(aCal.getTime());

        aMailing.getMaildropStatus().add(drop);
        dao.saveMailing(aMailing);
        if (drop.getGenStatus() == 1 && drop.getStatus() != MaildropEntry.STATUS_ACTIONBASED
                && drop.getStatus() != MaildropEntry.STATUS_DATEBASED) {
            aMailing.triggerMailing(drop.getId(), new Hashtable(), con);
        }
        returnValue = 1;
    } catch (Exception e) {
        AgnUtils.logger().info("soap prob send mail: " + e);
    }

    return returnValue;
}

From source file:org.agnitas.util.AgnUtils.java

/**
 * Getter for the system date./*w  w w . j  av  a  2 s .com*/
 *
 * @return Value of the system date.
 */
public static Date getSysdate(String sysdate) {
    int value = 0;
    char operator;
    GregorianCalendar result = new GregorianCalendar();

    if (sysdate.contains("now()")) {
        if ("now()".equals(sysdate)) {
            return result.getTime();
        }
        // handle date_add/ date_sub
        if (sysdate.startsWith("date_add") || sysdate.startsWith("date_sub")) {
            value = extractDayFromSysdate(sysdate);
            if (sysdate.startsWith("date_add")) {
                result.add(GregorianCalendar.DAY_OF_MONTH, value);
            }
            if (sysdate.startsWith("date_sub")) {
                result.add(GregorianCalendar.DAY_OF_MONTH, value * (-1));
            }
        }

        return result.getTime();
    }
    if (!sysdate.equals("sysdate")) { // +/- <days>
        operator = sysdate.charAt(7);

        try {
            value = Integer.parseInt(sysdate.substring(8));
        } catch (Exception e) {
            value = 0;
        }

        switch (operator) {
        case '+':
            result.add(GregorianCalendar.DAY_OF_MONTH, value);
            break;
        case '-':
            result.add(GregorianCalendar.DAY_OF_MONTH, value * (-1));
            break;
        }
    }

    return result.getTime();
}

From source file:net.sourceforge.eclipsetrader.opentick.Feed.java

public void snapshot() {
    SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma");
    SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma");
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);

    // Builds the url for quotes download
    String host = "quote.yahoo.com";
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols=");
    for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
        Security security = (Security) iter.next();
        url = url.append(security.getCode() + "+");
    }/*from w  w  w . jav  a2s. c o m*/
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap");

    // Read the last prices
    String line = "";
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = OpenTickPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(",");
            if (line.indexOf(";") != -1)
                item = line.split(";");

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1)
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1)
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time));
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                System.out.println(e.getMessage() + ": " + line);
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false)
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false)
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false)
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false)
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false)
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false)
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false)
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false)
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase(security.getCode()))
                    security.setQuote(quote, open, high, low, close);
            }
        }
        in.close();
    } catch (Exception e) {
        System.out.println(e.getMessage() + ": " + line);
        e.printStackTrace();
    }
}

From source file:com.activiti.android.ui.fragments.task.TaskDetailsFoundationFragment.java

@Override
public void onDatePicked(String dateId, GregorianCalendar gregorianCalendar) {
    dueAt = gregorianCalendar.getTime();
    edit(new UpdateTaskRepresentation(taskRepresentation.getName(), taskRepresentation.getDescription(),
            dueAt));// ww  w  . j a v a2s  .co  m
}