001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.integration.beans; 021 022import java.beans.PropertyEditor; 023import java.text.DateFormat; 024import java.text.ParseException; 025import java.text.SimpleDateFormat; 026import java.util.Date; 027import java.util.Locale; 028import java.util.regex.Pattern; 029 030/** 031 * A {@link PropertyEditor} which converts a {@link String} into 032 * a {@link Date} and vice versa. 033 * 034 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 035 */ 036public class DateEditor extends AbstractPropertyEditor { 037 private static final Pattern MILLIS = Pattern.compile("[0-9][0-9]*"); 038 039 private final DateFormat[] formats = new DateFormat[] { 040 new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH), 041 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH), 042 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH), 043 new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH), new SimpleDateFormat("yyyy-MM", Locale.ENGLISH), 044 new SimpleDateFormat("yyyy", Locale.ENGLISH), }; 045 046 public DateEditor() { 047 for (DateFormat f : formats) { 048 f.setLenient(true); 049 } 050 } 051 052 @Override 053 protected String toText(Object value) { 054 if (value instanceof Number) { 055 long time = ((Number) value).longValue(); 056 if (time <= 0) { 057 return null; 058 } 059 value = new Date(time); 060 } 061 return formats[0].format((Date) value); 062 } 063 064 @Override 065 protected Object toValue(String text) throws IllegalArgumentException { 066 if (MILLIS.matcher(text).matches()) { 067 long time = Long.parseLong(text); 068 if (time <= 0) { 069 return null; 070 } 071 return new Date(time); 072 } 073 074 for (DateFormat f : formats) { 075 try { 076 return f.parse(text); 077 } catch (ParseException e) { 078 } 079 } 080 081 throw new IllegalArgumentException("Wrong date: " + text); 082 } 083}