Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:com.predic8.membrane.core.interceptor.apimanagement.quota.AMQuota.java

License:Apache License

private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
    //TODO do a better response here

    Header hd = new Header();

    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;//w  w w  .  j  a  v  a 2s  .  c  o  m
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "Quota Exceeded");
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }

    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd)
            .contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}

From source file:com.predic8.membrane.core.interceptor.apimanagement.rateLimiter.AMRateLimiter.java

License:Apache License

public void setResponseToServiceUnavailable(Exchange exc, PolicyRateLimit prl)
        throws UnsupportedEncodingException {
    Header hd = new Header();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC()
            .withLocale(Locale.US);
    hd.add("Date", dateFormatter.print(DateTime.now()));
    hd.add("X-LimitDuration", PeriodFormat.getDefault().print(prl.getInterval().toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(prl.getRequests()));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = prl.getNextCleanup();
    hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));

    /*StringBuilder bodyString = new StringBuilder();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    bodyString.append(ip).append(" exceeded the rate limit of ").append(prl.getRequests())
        .append(" requests per ")//from ww  w  . j  a  v  a  2s. com
        .append(PeriodFormat.getDefault().print(prl.getInterval().toPeriod()))
        .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));*/

    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message",
                "The rate limit of " + prl.getRequests() + " requests in "
                        + prl.getInterval().getStandardSeconds()
                        + " seconds is exceeded. The next requests can be made at "
                        + dtFormatter.print(availableAgainDateTime));
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }

    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd)
            .contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}

From source file:com.predic8.membrane.core.interceptor.ratelimit.RateLimitInterceptor.java

License:Apache License

public void setResponseToServiceUnavailable(Exchange exc) throws UnsupportedEncodingException {

    Header hd = new Header();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC()
            .withLocale(Locale.US);
    hd.add("Date", dateFormatter.print(DateTime.now()));
    hd.add("X-LimitDuration",
            PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(rateLimitStrategy.requestLimit));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = rateLimitStrategy.getServiceAvailableAgainTime(ip);
    hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));

    StringBuilder bodyString = new StringBuilder();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    bodyString.append(ip).append(" exceeded the rate limit of ").append(rateLimitStrategy.requestLimit)
            .append(" requests per ")
            .append(PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod()))
            .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));

    Response resp = ResponseBuilder.newInstance().status(429, "Too Many Requests.")
            .contentType(MimeType.TEXT_PLAIN_UTF8).header(hd).body(bodyString.toString()).build();
    exc.setResponse(resp);/*from www . jav a2s.co m*/
}

From source file:com.premiumminds.webapp.wicket.JodaInstantTextField.java

License:Open Source License

public JodaInstantTextField(String id, IModel<T> model, String pattern, final Class<T> type) {
    super(id, model, type);
    this.pattern = pattern;
    converter = new IConverter<T>() {
        private static final long serialVersionUID = 1L;

        public String convertToString(ReadableInstant value, Locale locale) {
            if (null == locale) {
                return DateTimeFormat.forPattern(JodaInstantTextField.this.pattern).print(value);
            } else {
                return DateTimeFormat.forPattern(JodaInstantTextField.this.pattern).withLocale(locale)
                        .print(value);/*from ww  w. j  a v  a 2  s  .c o  m*/
            }
        }

        public T convertToObject(String value, Locale locale) throws ConversionException {
            try {
                if (null == locale) {
                    return type.getConstructor(Long.TYPE).newInstance(DateTimeFormat
                            .forPattern(JodaInstantTextField.this.pattern).parseDateTime(value).getMillis());
                } else {
                    return type.getConstructor(Long.TYPE)
                            .newInstance(DateTimeFormat.forPattern(JodaInstantTextField.this.pattern)
                                    .withLocale(locale).parseDateTime(value).getMillis());
                }
            } catch (Exception e) {
                log.error("Could not convert [" + value + "] to a valid " + type.getSimpleName());
                return null;
            }
        }
    };
}

From source file:com.primovision.lutransport.service.ImportMainSheetServiceImpl.java

private int calculateDuration(String startTime, String endTime) {
    if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
        return 0;
    }//from   w w w.j  a  v  a  2  s  .c om

    DateTimeFormatter durationFormat = DateTimeFormat.forPattern("HH:mm");

    DateTime dtStart = durationFormat.parseDateTime(startTime);
    DateTime dtStop = durationFormat.parseDateTime(endTime);
    if (dtStop.isBefore(dtStart)) {
        DateTime temp = dtStart;
        dtStart = dtStop;
        dtStop = temp;
    }

    /*System.out.print(Days.daysBetween(dtStart, dtStop).getDays() + " days, ");
    System.out.print(Hours.hoursBetween(dtStart, dtStop).getHours() % 24 + " hours, ");
    System.out.print(org.joda.time.Minutes.minutesBetween(dtStart, dtStop).getMinutes() % 60 + " minutes, ");
    System.out.println(Seconds.secondsBetween(dtStart, dtStop).getSeconds() % 60 + " seconds.");*/

    int hours = Hours.hoursBetween(dtStart, dtStop).getHours() % 24;
    int mins = org.joda.time.Minutes.minutesBetween(dtStart, dtStop).getMinutes() % 60;
    return mins + (hours * 60);
}

From source file:com.qatickets.domain.common.DateHelper.java

License:Open Source License

public static String currentDate(UserProfile user, String pattern) {
    DateTime dt = new DateTime(user.getDateTimeZone());
    DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
    return dtf.print(dt);
}

From source file:com.qatickets.domain.common.DateHelper.java

License:Open Source License

public static String format(UserProfile user, Date dateUTC, String pattern) {
    if (dateUTC == null) {
        return null;
    }//  w  w w.  ja v a  2s  .  c  o m
    DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
    return dtf.print(toUserTimeZone(user, dateUTC));
}

From source file:com.qcadoo.model.internal.types.DateTimeType.java

License:Open Source License

@Override
public ValueAndError toObject(final FieldDefinition fieldDefinition, final Object value) {
    if (value instanceof Date) {
        return ValueAndError.withoutError(value);
    }//from ww  w  .j  a v a2 s. c o  m
    try {
        DateTimeFormatter fmt = DateTimeFormat.forPattern(DateUtils.L_DATE_TIME_FORMAT);
        DateTime dt = fmt.parseDateTime(String.valueOf(value));
        int year = dt.getYear();
        if (year < 1500 || year > 2500) {
            return ValueAndError.withError("qcadooView.validate.field.error.invalidDateTimeFormat");
        }
        return ValueAndError.withoutError(dt.toDate());
    } catch (IllegalArgumentException e) {
        return ValueAndError.withError("qcadooView.validate.field.error.invalidDateTimeFormat");
    }
}

From source file:com.qcadoo.model.internal.types.DateType.java

License:Open Source License

@Override
public ValueAndError toObject(final FieldDefinition fieldDefinition, final Object value) {
    if (value instanceof Date) {
        return ValueAndError.withoutError(value);
    }//  w  ww .  java  2s . c om
    try {
        DateTimeFormatter fmt = DateTimeFormat.forPattern(DateUtils.L_DATE_FORMAT);
        DateTime dt = fmt.parseDateTime(String.valueOf(value));

        int year = dt.getYear();
        if (year < 1500 || year > 2500) {
            return ValueAndError.withError("qcadooView.validate.field.error.invalidDateFormat.range");
        }

        Date date = dt.toDate();

        if (year < 2000) {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, dt.getYear());
            c.set(Calendar.MONTH, dt.getMonthOfYear() - 1);
            c.set(Calendar.DAY_OF_MONTH, dt.getDayOfMonth());
            c.set(Calendar.HOUR_OF_DAY, dt.hourOfDay().get());
            c.set(Calendar.MINUTE, dt.getMinuteOfHour());
            c.set(Calendar.SECOND, dt.getSecondOfMinute());
            c.set(Calendar.MILLISECOND, dt.getMillisOfSecond());
            date = c.getTime();
        }

        return ValueAndError.withoutError(date);
    } catch (IllegalArgumentException e) {
        return ValueAndError.withError("qcadooView.validate.field.error.invalidDateFormat");
    }
}