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:org.geoserver.wms.map.MockHttpClientConnectionManager.java

@Override
public ConnectionRequest requestConnection(HttpRoute arg0, Object arg1) {
    return new ConnectionRequest() {

        @Override/* w w  w .ja  va 2  s.c o m*/
        public boolean cancel() {
            return false;
        }

        @Override
        public HttpClientConnection get(long arg0, TimeUnit arg1)
                throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            connections++;
            return new HttpClientConnection() {

                @Override
                public void shutdown() throws IOException {
                }

                @Override
                public void setSocketTimeout(int arg0) {
                }

                @Override
                public boolean isStale() {
                    return false;
                }

                @Override
                public boolean isOpen() {
                    return true;
                }

                @Override
                public int getSocketTimeout() {
                    return 0;
                }

                @Override
                public HttpConnectionMetrics getMetrics() {
                    return null;
                }

                @Override
                public void close() throws IOException {
                }

                @Override
                public void sendRequestHeader(HttpRequest arg0) throws HttpException, IOException {
                }

                @Override
                public void sendRequestEntity(HttpEntityEnclosingRequest arg0)
                        throws HttpException, IOException {
                }

                @Override
                public HttpResponse receiveResponseHeader() throws HttpException, IOException {
                    return new HttpResponse() {

                        List<Header> headers = new ArrayList<Header>();

                        @Override
                        public void addHeader(Header arg0) {
                        }

                        @Override
                        public void addHeader(String arg0, String arg1) {
                        }

                        @Override
                        public boolean containsHeader(String arg0) {
                            return false;
                        }

                        @Override
                        public Header[] getAllHeaders() {
                            return headers.toArray(new Header[] {});
                        }

                        public Header getHeader(String header) {
                            if ("transfer-encoding".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "identity");
                            }
                            if ("date".equalsIgnoreCase(header)) {

                                return new BasicHeader(header,
                                        dateFormat.format(new GregorianCalendar().getTime()));
                            }
                            if ("cache-control".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, enableCache ? "public" : "no-cache");
                            }
                            if ("content-length".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, response.length() + "");
                            }
                            if ("content-encoding".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "identity");
                            }
                            if ("age".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "0");
                            }
                            if ("expires".equalsIgnoreCase(header) && enableCache) {
                                GregorianCalendar expires = new GregorianCalendar();
                                expires.add(GregorianCalendar.MINUTE, 30);
                                return new BasicHeader(header, dateFormat.format(expires.getTime()));
                            }
                            return new BasicHeader(header, "");
                        }

                        @Override
                        public Header getFirstHeader(String header) {
                            Header value = getHeader(header);
                            headers.add(value);
                            return value;
                        }

                        @Override
                        public Header[] getHeaders(String header) {

                            return new Header[] { getFirstHeader(header) };
                        }

                        @Override
                        public Header getLastHeader(String header) {
                            return new BasicHeader(header, "");
                        }

                        @Override
                        public HttpParams getParams() {
                            // TODO Auto-generated method stub
                            return null;
                        }

                        @Override
                        public ProtocolVersion getProtocolVersion() {
                            return HttpVersion.HTTP_1_1;
                        }

                        @Override
                        public HeaderIterator headerIterator() {
                            return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock");
                        }

                        @Override
                        public HeaderIterator headerIterator(String header) {
                            return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock");
                        }

                        @Override
                        public void removeHeader(Header arg0) {
                        }

                        @Override
                        public void removeHeaders(String arg0) {
                        }

                        @Override
                        public void setHeader(Header arg0) {
                        }

                        @Override
                        public void setHeader(String arg0, String arg1) {
                        }

                        @Override
                        public void setHeaders(Header[] arg0) {
                        }

                        @Override
                        public void setParams(HttpParams arg0) {
                        }

                        @Override
                        public HttpEntity getEntity() {
                            BasicHttpEntity entity = new BasicHttpEntity();
                            entity.setContentLength(response.length());
                            entity.setContent(
                                    new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)));
                            return entity;
                        }

                        @Override
                        public Locale getLocale() {
                            return Locale.ENGLISH;
                        }

                        @Override
                        public StatusLine getStatusLine() {
                            return new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK");
                        }

                        @Override
                        public void setEntity(HttpEntity arg0) {
                        }

                        @Override
                        public void setLocale(Locale arg0) {
                        }

                        @Override
                        public void setReasonPhrase(String arg0) throws IllegalStateException {
                        }

                        @Override
                        public void setStatusCode(int arg0) throws IllegalStateException {
                        }

                        @Override
                        public void setStatusLine(StatusLine arg0) {
                        }

                        @Override
                        public void setStatusLine(ProtocolVersion arg0, int arg1) {
                        }

                        @Override
                        public void setStatusLine(ProtocolVersion arg0, int arg1, String arg2) {
                        }
                    };
                }

                @Override
                public void receiveResponseEntity(HttpResponse arg0) throws HttpException, IOException {
                }

                @Override
                public boolean isResponseAvailable(int arg0) throws IOException {
                    return true;
                }

                @Override
                public void flush() throws IOException {
                }
            };
        }
    };
}

From source file:org.eurekastreams.server.persistence.TabMapper.java

/**
 * Clean up deleted gadgets here using the expired date set earlier. Currently this is hard-coded to be at least 20
 * (configurable) minutes since the gadget was originally deleted, but could be much longer because it is dependent
 * on the next gadget that is deleted. If one gadget is deleted on Jan 1st and the next gadget is deleted on March
 * 1st, the 1st gadget will remain flagged as deleted in the database until March 1st so we definitely need a full
 * timestamp for this object.//from www  .j a  va 2s.co m
 */
private void cleanUpDeletedGadgets() {
    GregorianCalendar expiredDateTime = new GregorianCalendar();
    expiredDateTime.add(Calendar.MINUTE, -undeleteGadgetWindowInMinutes);

    entityManager
            .createQuery(
                    "delete from Gadget de where de.deleted = true " + "and de.dateDeleted < :expiredTimestamp")
            .setParameter("expiredTimestamp", expiredDateTime.getTime()).executeUpdate();
}

From source file:com.eryansky.common.utils.DateUtil.java

/**
 *  ?2009-08-01// w ww  .j a  va2  s  .c om
 */
public static String addDay(String strdate) {

    Date date = new Date(); // ??

    String dateresult = null; // 
    // ??
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    // ?
    GregorianCalendar gc = new GregorianCalendar();

    try {
        date = df.parse(strdate); // ?
    } catch (ParseException e) {
        e.printStackTrace();
    }

    gc.setTime(date); // gc?

    gc.add(5, 1); // 2?1?(....5)
    // ?
    gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
    // ?
    dateresult = df.format(gc.getTime());

    return dateresult;
}

From source file:com.eryansky.common.utils.DateUtil.java

/**
 * ? ?2009-08-01/* w  w w .  jav  a  2s  .c om*/
 */
public static String subDay(String strdate) {

    Date date = new Date(); // ??

    String dateresult = null; // 
    // ??
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    // ?
    GregorianCalendar gc = new GregorianCalendar();

    try {
        date = df.parse(strdate); // ?
    } catch (ParseException e) {
        e.printStackTrace();
    }

    gc.setTime(date); // gc?

    gc.add(5, -1); // 2?1?(....5)
    // ?
    gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
    // ?
    dateresult = df.format(gc.getTime());

    return dateresult;
}

From source file:org.xdi.oxauth.model.crypto.signature.ECDSAKeyFactory.java

public ECDSAKeyFactory(SignatureAlgorithm signatureAlgorithm, String dnName) throws InvalidParameterException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        SignatureException, InvalidKeyException, CertificateEncodingException {
    if (signatureAlgorithm == null) {
        throw new InvalidParameterException("The signature algorithm cannot be null");
    }//from   ww  w  . j a v a 2 s .com

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(signatureAlgorithm.getCurve());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
    keyGen.initialize(ecSpec, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    JCEECPrivateKey privateKeySpec = (JCEECPrivateKey) keyPair.getPrivate();
    JCEECPublicKey publicKeySpec = (JCEECPublicKey) keyPair.getPublic();

    BigInteger x = publicKeySpec.getQ().getX().toBigInteger();
    BigInteger y = publicKeySpec.getQ().getY().toBigInteger();
    BigInteger d = privateKeySpec.getD();

    ecdsaPrivateKey = new ECDSAPrivateKey(d);
    ecdsaPublicKey = new ECDSAPublicKey(signatureAlgorithm, x, y);

    if (StringUtils.isNotBlank(dnName)) {
        // Create certificate
        GregorianCalendar startDate = new GregorianCalendar(); // time from which certificate is valid
        GregorianCalendar expiryDate = new GregorianCalendar(); // time after which certificate is not valid
        expiryDate.add(Calendar.YEAR, 1);
        BigInteger serialNumber = new BigInteger(1024, new Random()); // serial number for certificate

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal principal = new X500Principal(dnName);

        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(principal);
        certGen.setNotBefore(startDate.getTime());
        certGen.setNotAfter(expiryDate.getTime());
        certGen.setSubjectDN(principal); // note: same as issuer
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WITHECDSA");

        X509Certificate x509Certificate = certGen.generate(privateKeySpec, "BC");
        certificate = new Certificate(signatureAlgorithm, x509Certificate);
    }
}

From source file:org.xdi.oxauth.model.crypto.signature.RSAKeyFactory.java

public RSAKeyFactory(SignatureAlgorithm signatureAlgorithm, String dnName)
        throws InvalidParameterException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException,
        InvalidKeyException, CertificateEncodingException {
    if (signatureAlgorithm == null) {
        throw new InvalidParameterException("The signature algorithm cannot be null");
    }/* w w w  . j av  a 2s  . c  om*/

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(2048, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();

    JCERSAPrivateCrtKey jcersaPrivateCrtKey = (JCERSAPrivateCrtKey) keyPair.getPrivate();
    JCERSAPublicKey jcersaPublicKey = (JCERSAPublicKey) keyPair.getPublic();

    rsaPrivateKey = new RSAPrivateKey(jcersaPrivateCrtKey.getModulus(),
            jcersaPrivateCrtKey.getPrivateExponent());

    rsaPublicKey = new RSAPublicKey(jcersaPublicKey.getModulus(), jcersaPublicKey.getPublicExponent());

    if (StringUtils.isNotBlank(dnName)) {
        // Create certificate
        GregorianCalendar startDate = new GregorianCalendar(); // time from which certificate is valid
        GregorianCalendar expiryDate = new GregorianCalendar(); // time after which certificate is not valid
        expiryDate.add(Calendar.YEAR, 1);
        BigInteger serialNumber = new BigInteger(1024, new Random()); // serial number for certificate

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal principal = new X500Principal(dnName);

        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(principal);
        certGen.setNotBefore(startDate.getTime());
        certGen.setNotAfter(expiryDate.getTime());
        certGen.setSubjectDN(principal); // note: same as issuer
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm(signatureAlgorithm.getAlgorithm());

        X509Certificate x509Certificate = certGen.generate(jcersaPrivateCrtKey, "BC");
        certificate = new Certificate(signatureAlgorithm, x509Certificate);
    }
}

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public Map<Date, SynchronizedDescriptiveStatistics> getWeeklyTrailingSummaryStats(Date startDate, Date endDate,
        Long hospitalser, String filter, boolean includeWeekends, boolean ptflag, boolean scheduledFlag) {
    TreeMap<Date, SynchronizedDescriptiveStatistics> retval = new TreeMap();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(endDate);/*from  w  w  w  .  j av  a 2  s .co  m*/
    Date d;
    SynchronizedDescriptiveStatistics stats;
    while (gc.getTime().compareTo(startDate) > 0) {
        d = gc.getTime();
        gc.add(Calendar.DATE, -7);
        stats = getDailyStats(gc.getTime(), d, hospitalser, filter, includeWeekends, ptflag, scheduledFlag);
        retval.put(gc.getTime(), stats);
    }

    return retval;
}

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

/**
 * Get the number of months left in this contract after the given date. Partial months are counted as
 * full months.//w  w  w.  j a  va 2 s  .  c om
 *
 * @param date
 * @return
 */
public int getMonthsLeft(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    cal.add(Calendar.MONTH, 1);
    date = cal.getTime();
    int monthsLeft = 0;
    while (date.before(endDate) || date.equals(endDate)) {
        monthsLeft++;
        cal.add(Calendar.MONTH, 1);
        date = cal.getTime();
    }
    return monthsLeft;
}

From source file:net.alexjf.tmm.fragments.ImmedTransactionEditorFragment.java

@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
    GregorianCalendar calendar = new GregorianCalendar(year, month, day);
    executionDateButton.setText(dateFormat.format(calendar.getTime()));
}

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*from   ww w.  ja  v  a  2 s . com*/
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);

        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }

        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }

    // check that
    try {
        tx.setFtChargedAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();

        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);

        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        boolean found = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                found = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(found);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}