Example usage for java.util Calendar clone

List of usage examples for java.util Calendar clone

Introduction

In this page you can find the example usage for java.util Calendar clone.

Prototype

@Override
public Object clone() 

Source Link

Document

Creates and returns a copy of this object.

Usage

From source file:nl.strohalm.cyclos.utils.TimePeriod.java

/**
 * Return a new calendar adding this time period
 *///  w  w w .  java 2 s .c o  m
public Calendar add(final Calendar date) {
    if (date == null) {
        return null;
    }
    if (!isValid()) {
        return date;
    }
    final Calendar ret = (Calendar) date.clone();
    ret.add(field.getCalendarValue(), number);
    return ret;
}

From source file:nl.strohalm.cyclos.utils.TimePeriod.java

/**
 * Return a new calendar removing this time period
 *///from  ww w  .j av a  2s  .  c o m
public Calendar remove(final Calendar date) {
    if (date == null) {
        return null;
    }
    if (!isValid()) {
        return date;
    }
    final Calendar ret = (Calendar) date.clone();
    ret.add(field.getCalendarValue(), -number);
    return ret;
}

From source file:nz.co.jsrsolutions.ds3.command.GetExchangeSymbolQuotesCommand.java

public boolean execute(Context context) throws Exception {

    logger.info("Executing: getexchangesymbolquotes");

    EodDataProvider eodDataProvider = (EodDataProvider) context.get(CommandContext.EODDATAPROVIDER_KEY);
    EodDataSink eodDataSink = (EodDataSink) context.get(CommandContext.EODDATASINK_KEY);
    String exchange = (String) context.get(CommandContext.EXCHANGE_KEY);
    String symbol = (String) context.get(CommandContext.SYMBOL_KEY);

    if (exchange == null) {
        throw new CommandException("Must supply --exchange [exchangecode]");
    }/*from www.j  a  va 2  s.  co m*/

    if (symbol == null) {
        throw new CommandException("Must supply --symbol [symbolcode]");
    }

    @SuppressWarnings("unused")
    long nQuotesWritten = 0;

    final int availableMonths = eodDataProvider.getExchangeMonths(exchange);
    // final SYMBOL[] symbols = eodDataProvider.getSymbols(exchange);
    final String[] symbols = eodDataSink.readExchangeSymbols(exchange);

    if (symbols == null) {
        logger.info("No symbols associated with this exchange...");
        return false;
    }

    final Calendar firstAvailableDateTime = Calendar.getInstance();

    if (availableMonths > 0) {
        firstAvailableDateTime.add(Calendar.MONTH, -1 * 1);
        firstAvailableDateTime.add(Calendar.DATE, 1);
    }

    final Calendar plusOneDay = (Calendar) firstAvailableDateTime.clone();
    plusOneDay.add(Calendar.DAY_OF_MONTH, 1);

    if (logger.isInfoEnabled()) {

        StringBuffer logMessageBuffer = new StringBuffer();
        logMessageBuffer.setLength(0);
        logMessageBuffer.append(" Attempting to retrieve quotes on [ ");
        logMessageBuffer.append(exchange);
        logMessageBuffer.append(" ] for [ ");
        logMessageBuffer.append(symbol);
        logMessageBuffer.append(" ] between [ ");
        logMessageBuffer.append(firstAvailableDateTime.getTime().toString());
        logMessageBuffer.append(" ] and [ ");
        logMessageBuffer.append(plusOneDay.getTime().toString());
        logMessageBuffer.append(" ] ");
        logger.info(logMessageBuffer.toString());

    }

    final QUOTE[] quotes = eodDataProvider.getQuotes(exchange, symbol, firstAvailableDateTime, plusOneDay,
            DEFAULT_FREQUENCY);

    if (quotes == null || quotes.length == 0) {
        logger.info("Quote array from provider was empty!");
        return false;
    }

    for (QUOTE quote : quotes) {
        StringBuffer logMessageBuffer = new StringBuffer();
        logMessageBuffer.append("Quote date: [ ");
        logMessageBuffer.append(quote.getDateTime().getTime().toString());
        logMessageBuffer.append(" ]");
        logger.info(logMessageBuffer.toString());

    }

    return false;

}

From source file:com.github.jgility.core.planning.AbstractPlan.java

@Override
public void setEnd(Calendar end) throws IllegalArgumentException {
    if (ObjectUtils.equals(null, end)) {
        throw new IllegalArgumentException("null-Object as start-time is not allowed");
    }/*from  ww w .ja v a 2 s . co m*/

    if (start.before(end)) {
        this.end = (Calendar) end.clone();
    } else {
        throw new IllegalArgumentException("start-time have to before end-time");
    }
}

From source file:de.conterra.suite.security.portal.gpx.EmbeddedSAMLTokenIntegrationContext.java

private String createToken(User user) throws Exception {
    LOGGER.entering("EmbeddedSAMLTokenIntegrationContext", "createToken");
    // non authenticated users -> exception
    user.getAuthenticationStatus().assertLoggedIn();

    String username = user.getProfile().getUsername();
    RoleSet roles = user.getAuthenticationStatus().getAuthenticatedRoles();

    // we create a ticket with the users id and including the user roles

    Calendar now = Calendar.getInstance();
    Calendar timeout = (Calendar) now.clone();
    timeout.add(Calendar.SECOND, m_tokenTimout);

    SAMLNameIdentifier identifier = new SAMLNameIdentifier(username, null,
            "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");

    SAMLSubject samlSubject = new SAMLSubject(identifier, null, null, null);
    Collection<SAMLStatement> statements = new ArrayList<SAMLStatement>();
    SAMLAuthenticationStatement authnStatement = new SAMLAuthenticationStatement(
            (SAMLSubject) samlSubject.clone(), "urn:oasis:names:tc:SAML:1.0:am:password", now.getTime(), null,
            null, null);/*from  w  w  w .j ava  2  s  . co m*/
    statements.add(authnStatement);

    Collection<SAMLAttribute> samlAttributes = new ArrayList<SAMLAttribute>();
    if (!roles.isEmpty()) {
        // for (String role : roles) {
        SAMLAttribute roleAttribute = new SAMLAttribute(m_roleAttributeName, m_roleAttributeNamespace,
                new QName(org.opensaml.XML.XSD_NS, "string"), 0, roles);
        samlAttributes.add(roleAttribute);
        // }
    }
    if (!samlAttributes.isEmpty()) {
        SAMLAttributeStatement attributeStatement = new SAMLAttributeStatement(
                (SAMLSubject) samlSubject.clone(), samlAttributes);
        statements.add(attributeStatement);
    }

    // allow 5 seconds clock difference
    Date notBefore = new Date(now.getTime().getTime() - 5000);
    Date notOnOrAfter = new Date(timeout.getTime().getTime() + 5000);

    SAMLAssertion assertion = new SAMLAssertion(m_tokenIssuer, notBefore, notOnOrAfter, null, null, statements);

    SAMLResponse response = new SAMLResponse(null, null, Collections.singleton(assertion), null);
    // ensure canonicalization
    response.toString();

    Collection<Certificate> certificates = Collections.singleton(m_applicationCertificate);
    assertion.sign("http://www.w3.org/2000/09/xmldsig#rsa-sha1", m_applicationPrivateKey, certificates);
    if (m_tokenSignSAMLResponse) {
        response.sign("http://www.w3.org/2000/09/xmldsig#rsa-sha1", m_applicationPrivateKey, certificates);
    }
    return response.toString();
}

From source file:com.github.jgility.core.planning.AbstractPlan.java

@Override
public void setStart(Calendar start) throws IllegalArgumentException {
    if (ObjectUtils.equals(null, start)) {
        throw new IllegalArgumentException("null-Object as start-time is not allowed");
    }//ww w  .j a v a 2s  .c o  m

    if (end.after(start)) {
        this.start = (Calendar) start.clone();
    } else {
        throw new IllegalArgumentException("start-time have to before end-time");
    }
}

From source file:nl.strohalm.cyclos.entities.accounts.loans.LoanParameters.java

/**
 * Calculates the monthly interests for the given parameters
 * @return 0 if no monthly interests, or the applied interests otherwise (ie: if monthly interests = 1%, paymentCount = 1 and delay = 0, returns
 * 10 for amount = 1000)/*  ww  w  .ja v  a 2s .  c o  m*/
 */
public BigDecimal calculateMonthlyInterests(final BigDecimal amount, final int paymentCount, Calendar grantDate,
        Calendar firstExpirationDate, final MathContext mathContext) {
    if (monthlyInterest == null || amount.compareTo(BigDecimal.ZERO) != 1 || paymentCount < 1) {
        return BigDecimal.ZERO;
    }
    // Calculate the delay
    final Calendar now = Calendar.getInstance();
    grantDate = grantDate == null ? now : grantDate;
    firstExpirationDate = firstExpirationDate == null ? (Calendar) now.clone() : firstExpirationDate;
    final Calendar shouldBeFirstExpiration = (Calendar) grantDate.clone();
    shouldBeFirstExpiration.add(Calendar.MONTH, 1);
    int delay = DateHelper.daysBetween(shouldBeFirstExpiration, firstExpirationDate);
    if (delay < 0) {
        delay = 0;
    }

    final BigDecimal grantFee = calculateGrantFee(amount);
    final BigDecimal baseAmount = amount.add(grantFee);
    final BigDecimal interests = monthlyInterest.divide(new BigDecimal(100), mathContext);
    final BigDecimal numerator = new BigDecimal(
            Math.pow(1 + interests.doubleValue(), paymentCount + delay / 30F)).multiply(interests);
    final BigDecimal denominator = new BigDecimal(Math.pow(1 + interests.doubleValue(), paymentCount) - 1);
    final BigDecimal paymentAmount = baseAmount.multiply(numerator).divide(denominator, mathContext);
    final BigDecimal totalAmount = paymentAmount.multiply(new BigDecimal(paymentCount));
    return totalAmount.subtract(baseAmount);
}

From source file:info.raack.appliancelabeler.service.DefaultDataServiceTest.java

@Test
public void createSurroundingTransitionsForAnonymousTransitionCorrectly() {
    GenericStateTransition transition = mock(GenericStateTransition.class);
    UserAppliance userAppliance = mock(UserAppliance.class);

    Calendar cal = new GregorianCalendar();
    Calendar cal2 = (Calendar) cal.clone();
    Calendar cal3 = (Calendar) cal.clone();
    cal2.add(Calendar.SECOND, -2);
    cal3.add(Calendar.SECOND, 2);

    when(transition.getTime()).thenReturn(cal.getTime().getTime());

    int transitionId = 15;
    int userApplianceId = 16;

    when(database.getAnonymousApplianceStateTransitionById(transitionId)).thenReturn(transition);
    when(database.getUserApplianceById(userApplianceId)).thenReturn(userAppliance);

    dataService.createUserGeneratedLabelsSurroundingAnonymousTransition(transitionId, userApplianceId);

    verify(database, times(1))/*from ww  w  .  jav a  2s .c  o  m*/
            .storeUserOnOffLabels(argThat(new IsValidTransitionList(cal2, cal3, userAppliance)));
    verify(database, times(1)).removeTransition(transition);
}

From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java

public static String createRegularTimePeriodForJSON(int period, int year, int timeInterval) {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat;/*from  w w w .  java2s.c  o m*/
    switch (timeInterval) {
    case TIME_INTERVAL.DAY:
        calendar.setLenient(true);
        calendar.clone();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.DAY_OF_YEAR, period);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    case TIME_INTERVAL.WEEK:
        return period + "/" + year;
    default:
        period++;
        if (period < 10) {
            return year + "-0" + period;
        } else {
            return year + "-" + period;
        }
    }
}

From source file:com.gsma.mobileconnect.utils.JsonUtilsTest.java

@Test
public void parseRequestTokenResponse_withValidResponse_shouldReturnResponseData() throws IOException {
    // GIVEN/*from  w w w .  j a v  a  2s .  co m*/
    String expectedAccessToken = "EXPECTED ACCESS_TOKEN";
    String expectedTokenType = "EXPECTED TOKEN_TYPE";
    String expectedRefreshToken = "EXPECTED REFRESH_TOKEN";
    Integer expectedExpiresIn = new Integer("3600");
    String expectedIdToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJub25jZSI6Im5vbmNlXzAucDNvd3pxbmR5dyIsInN1YiI6ImMwY2Q3NjFmZDA3ZTVlMTk3NDk3NmZiMzVkYzA2MmRlIiwiYW1yIjoiU01TX1VSTCIsImF1dGhfdGltZSI6MTQ1MDg4NDczNCwiYWNyIjoiMiIsImF6cCI6IjBjOWRmMjE5IiwiaWF0IjoxNDUwODg0NzMzLCJleHAiOjE0NTA4ODgzMzMsImF1ZCI6WyIwYzlkZjIxOSJdLCJpc3MiOiJodHRwOi8vb3BlcmF0b3JfYS5zYW5kYm94Lm1vYmlsZWNvbm5lY3QuaW8vb2lkYy9hY2Nlc3N0b2tlbiJ9.wlkZgNtN8ezAia6dZ8l2dYQBryB9skcIVN_6XzZn2mI";
    String expectedJsonStr = "{ \"access_token\": \"" + expectedAccessToken + "\", " + " \"token_type\": \""
            + expectedTokenType + "\", " + " \"expires_in\": \"" + expectedExpiresIn + "\", "
            + " \"refresh_token\": \"" + expectedRefreshToken + "\", " + " \"id_token\": \"" + expectedIdToken
            + "\"}";

    Calendar expectedTime = Calendar.getInstance();
    Calendar expectedExpires = (Calendar) expectedTime.clone();
    expectedExpires.add(Calendar.SECOND, expectedExpiresIn);

    // WHEN
    RequestTokenResponse requestTokenResponse = JsonUtils.parseRequestTokenResponse(expectedTime,
            expectedJsonStr);

    // THEN
    assertFalse(requestTokenResponse.hasErrorResponse());
    assertTrue(requestTokenResponse.hasResponseData());
    assertEquals(expectedTime, requestTokenResponse.getResponseData().getTimeReceived());
    assertEquals(expectedAccessToken, requestTokenResponse.getResponseData().get_access_token());
    assertEquals(expectedTokenType, requestTokenResponse.getResponseData().get_token_type());
    assertEquals(expectedRefreshToken, requestTokenResponse.getResponseData().get_refresh_token());
    assertEquals(expectedJsonStr, requestTokenResponse.getResponseData().getOriginalResponse());
    assertEquals(expectedExpiresIn, requestTokenResponse.getResponseData().get_expires_in());
    assertEquals(expectedExpires, requestTokenResponse.getResponseData().getExpires());
    assertNotNull(requestTokenResponse.getResponseData().getParsedIdToken());
}