Example usage for org.joda.time DateTime parse

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

Introduction

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

Prototype

@FromString
public static DateTime parse(String str) 

Source Link

Document

Parses a DateTime from the specified string.

Usage

From source file:org.graylog2.syslog4j.server.impl.event.SyslogServerEvent.java

License:Open Source License

protected void parseDate() {
    int datelength = 16;
    String dateFormatS = DATE_FORMAT;
    boolean isDate8601 = false;

    if (this.message.length() > datelength) {

        // http://jira.graylog2.org/browse/SERVER-287
        if (this.message.charAt(5) == ' ') {
            datelength = 15;/*from  w w  w  .  j a  v a  2 s  .  c o m*/
            dateFormatS = DATE_FORMAT_S;
        }

        if (Character.isDigit(this.message.charAt(0))) {
            datelength = this.message.indexOf(' ') + 1;
            isDate8601 = true;
        }

        String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
        String originalDate = this.message.substring(0, datelength - 1);
        String modifiedDate = originalDate + " " + year;

        DateFormat dateFormat = new SimpleDateFormat(dateFormatS, Locale.ENGLISH);
        try {
            if (!isDate8601) {
                this.date = dateFormat.parse(modifiedDate);
            } else {
                this.date = DateTime.parse(originalDate).toDate();
            }

            this.message = this.message.substring(datelength);

        } catch (ParseException pe) {
            this.date = new Date();
        }
    }

    parseHost();
}

From source file:org.grouchotools.jsrules.Operator.java

protected Number getNumber(Object obj) throws InvalidParameterException {
    Number number;//from w  ww  .j av a2  s  .c o  m
    if (obj instanceof Number) {
        number = (Number) obj;
    } else {
        // lets see if it's a DateTime instead
        try {
            DateTime dateTime = DateTime.parse(obj.toString());
            number = dateTime.getMillis();
        } catch (IllegalArgumentException ex) {
            throw new InvalidParameterException(obj.toString() + " is not a number or date. Unable to compare",
                    ex);
        }
    }
    return number;
}

From source file:org.icgc.dcc.portal.filter.CachingFilter.java

License:Open Source License

private static Date parseIndexDate(String value) {
    // Format used by the summarizer to create the release date
    return new Date(DateTime.parse(value).getMillis());
}

From source file:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java

License:Apache License

/**
 * Calculates the number of days left to the expiration date based on the
 * {@code expireDate} parameter./*from  w  w  w  . j a  v a2  s . c o  m*/
 * @param expireDate
 * @param userId
 * @return number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS}
 */
private long getDaysToExpirationDate(final String userId, final DateTime expireDate)
        throws LdapPasswordPolicyEnforcementException {

    log.debug("Calculating number of days left to the expiration date for user {}", userId);

    final DateTime currentTime = new DateTime(DEFAULT_TIME_ZONE);

    log.info("Current date is {}, expiration date is {}", currentTime.toString(), expireDate.toString());

    final Days d = Days.daysBetween(currentTime, expireDate);
    int daysToExpirationDate = d.getDays();

    if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) {
        String msgToLog = "Authentication failed because account password has expired with "
                + daysToExpirationDate + " to expiration date. ";
        msgToLog += "Verify the value of the " + this.dateAttribute
                + " attribute and make sure it's not before the current date, which is "
                + currentTime.toString();

        final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog);

        log.error(msgToLog, exc);

        throw exc;
    }

    /*
     * Warning period begins from X number of ways before the expiration date
     */
    DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), DEFAULT_TIME_ZONE);

    warnPeriod = warnPeriod.minusDays(this.warningDays);
    log.info("Warning period begins on {}", warnPeriod.toString());

    if (this.warnAll) {
        log.info("Warning all. The password for {} will expire in {} days.", userId, daysToExpirationDate);
    } else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) {
        log.info("Password will expire in {} days.", daysToExpirationDate);
    } else {
        log.info("Password is not expiring. {} days left to the warning", daysToExpirationDate);
        daysToExpirationDate = PASSWORD_STATUS_PASS;
    }

    return daysToExpirationDate;
}

From source file:org.jasig.cas.adaptors.ldap.lppe.LPPEAuthenticationHandler.java

License:Apache License

/**
 * Calculates the number of days left to the expiration date.
 * @return Number of days left to the expiration date or -1 if the no expiration warning is
 * calculated based on the defined policy.
 *///from   w  ww  . j ava 2  s . c o m
protected int getDaysToExpirationDate(final DateTime expireDate, final PasswordPolicyResult result)
        throws LoginException {
    final DateTimeZone timezone = configuration.getDateConverter().getTimeZone();
    final DateTime currentTime = new DateTime(timezone);
    logger.debug("Current date is {}. Expiration date is {}", currentTime, expireDate);

    final Days d = Days.daysBetween(currentTime, expireDate);
    int daysToExpirationDate = d.getDays();

    logger.debug("[{}] days left to the expiration date.", daysToExpirationDate);
    if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) {
        final String msgToLog = String.format("Password expiration date %s is on/before the current time %s.",
                daysToExpirationDate, currentTime);
        logger.debug(msgToLog);
        throw new CredentialExpiredException(msgToLog);
    }

    // Warning period begins from X number of days before the expiration date
    final DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), timezone)
            .minusDays(result.getPasswordWarningNumberOfDays());
    logger.debug("Warning period begins on [{}]", warnPeriod);

    if (configuration.isAlwaysDisplayPasswordExpirationWarning()) {
        logger.debug("Warning all. The password for [{}] will expire in [{}] day(s).", result.getDn(),
                daysToExpirationDate);
    } else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) {
        logger.debug("Password will expire in [{}] day(s)", daysToExpirationDate);
    } else {
        logger.debug("Password is not expiring. [{}] day(s) left to the warning.", daysToExpirationDate);
        daysToExpirationDate = -1;
    }

    return daysToExpirationDate;
}

From source file:org.jasig.cas.services.DefaultRegisteredServiceAccessStrategy.java

License:Apache License

@Override
public boolean isServiceAccessAllowed() {
    if (!this.enabled) {
        logger.trace("Service is not enabled in service registry.");
    }/* ww w .  j  a v  a  2s  . co  m*/

    final DateTime now = DateTime.now();

    if (this.startingDateTime != null) {
        final DateTime st = DateTime.parse(this.startingDateTime);

        if (now.isBefore(st)) {
            logger.warn("Service access not allowed because it starts at {}. Now is {}", this.startingDateTime,
                    now);
            return false;
        }
    }

    if (this.endingDateTime != null) {
        final DateTime et = DateTime.parse(this.endingDateTime);
        if (now.isAfter(et)) {
            logger.warn("Service access not allowed because it ended at {}. Now is {}", this.endingDateTime,
                    now);
            return false;
        }
    }

    return this.enabled;
}

From source file:org.jasig.cas.services.TimeBasedRegisteredServiceAccessStrategy.java

License:Apache License

@Override
public boolean isServiceAccessAllowed() {
    final DateTime now = DateTime.now();

    if (this.startingDateTime != null) {
        final DateTime st = DateTime.parse(this.startingDateTime);

        if (now.isBefore(st)) {
            logger.warn("Service access not allowed because it starts at {}. Now is {}", this.startingDateTime,
                    now);// ww w.  j ava2  s.co m
            return false;
        }
    }

    if (this.endingDateTime != null) {
        final DateTime et = DateTime.parse(this.endingDateTime);
        if (now.isAfter(et)) {
            logger.warn("Service access not allowed because it ended at {}. Now is {}", this.endingDateTime,
                    now);
            return false;
        }
    }

    return super.isServiceAccessAllowed();
}

From source file:org.jasig.cas.support.saml.authentication.principal.GoogleAccountsService.java

License:Apache License

/**
 * Construct SAML response./*from w  w w  . j  a  v  a2s .c  o m*/
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 * @return the SAML response
 */
private String constructSamlResponse() {
    final DateTime currentDateTime = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());
    final DateTime notBeforeIssueInstant = DateTime.parse("2003-04-17T00:46:02Z");

    final RegisteredService svc = this.servicesManager.findServiceBy(this);
    final String userId = svc.getUsernameAttributeProvider().resolveUsername(getPrincipal(), this);

    final org.opensaml.saml2.core.Response response = BUILDER.newResponse(BUILDER.generateSecureRandomId(),
            currentDateTime, getId(), this);
    response.setStatus(BUILDER.newStatus(StatusCode.SUCCESS_URI, null));

    final AuthnStatement authnStatement = BUILDER.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX,
            currentDateTime);
    final Assertion assertion = BUILDER.newAssertion(authnStatement, "https://www.opensaml.org/IDP",
            notBeforeIssueInstant, BUILDER.generateSecureRandomId());

    final Conditions conditions = BUILDER.newConditions(notBeforeIssueInstant, currentDateTime, getId());
    assertion.setConditions(conditions);

    final Subject subject = BUILDER.newSubject(NameID.EMAIL, userId, getId(), currentDateTime, this.requestId);
    assertion.setSubject(subject);

    response.getAssertions().add(assertion);

    final StringWriter writer = new StringWriter();
    BUILDER.marshalSamlXmlObject(response, writer);

    logger.debug("Generated Google SAML response: {}", writer.toString());
    return writer.toString();
}

From source file:org.jasig.cas.support.saml.authentication.principal.GoogleAccountsServiceResponseBuilder.java

License:Apache License

/**
 * Construct SAML response.//w ww. j  a v  a 2  s .  c o  m
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 * @param service the service
 * @return the SAML response
 */
protected String constructSamlResponse(final GoogleAccountsService service) {
    final DateTime currentDateTime = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());
    final DateTime notBeforeIssueInstant = DateTime.parse("2003-04-17T00:46:02Z");

    /*
     * Must be looked up directly from the context
     * because the services manager is not serializable
     * and cannot be class field.
     */
    final ApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final ServicesManager servicesManager = context.getBean("servicesManager", ServicesManager.class);
    final RegisteredService registeredService = servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
    final String userId = registeredService.getUsernameAttributeProvider()
            .resolveUsername(service.getPrincipal(), service);

    final org.opensaml.saml.saml2.core.Response response = samlObjectBuilder
            .newResponse(samlObjectBuilder.generateSecureRandomId(), currentDateTime, service.getId(), service);
    response.setStatus(samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));

    final AuthnStatement authnStatement = samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX,
            currentDateTime);
    final Assertion assertion = samlObjectBuilder.newAssertion(authnStatement, "https://www.opensaml.org/IDP",
            notBeforeIssueInstant, samlObjectBuilder.generateSecureRandomId());

    final Conditions conditions = samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime,
            service.getId());
    assertion.setConditions(conditions);

    final Subject subject = samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime,
            service.getRequestId());
    assertion.setSubject(subject);

    response.getAssertions().add(assertion);

    final StringWriter writer = new StringWriter();
    samlObjectBuilder.marshalSamlXmlObject(response, writer);

    final String result = writer.toString();
    logger.debug("Generated Google SAML response: {}", result);
    return result;
}

From source file:org.jevis.jenotifier.notifier.SQL.DataPoint.java

License:Open Source License

public List<JEVisSample> selectSamples(JEVisAttribute attribute) {
    List<JEVisSample> samples;
    if (_periodStart != null && _periodEnd != null && !_periodStart.isEmpty() && !_periodEnd.isEmpty()) {
        samples = attribute.getSamples(DateTime.parse(timeformatAdjustment(_periodStart)),
                DateTime.parse(timeformatAdjustment(_periodEnd)));
    } else {/*  w  ww . java2  s.c  o m*/
        samples = attribute.getAllSamples();
    }
    return samples;
}