From 6cb044c943051d3e0ae9f45bf14541bff68cebc4 Mon Sep 17 00:00:00 2001 From: Imteyaz Khan Date: Sat, 19 Jan 2019 01:10:28 +0530 Subject: [PATCH 1/5] #3026 Access log related changed --- dubbo-common/pom.xml | 4 + .../apache/dubbo/common/utils/DateUtil.java | 43 +++ .../dubbo/rpc/filter/AccessLogFilter.java | 226 +++++++-------- .../dubbo/rpc/support/AccessLogData.java | 270 ++++++++++++++++++ 4 files changed, 426 insertions(+), 117 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 22a13222fe2..a474da3b7e4 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -39,6 +39,10 @@ commons-logging commons-logging + + org.apache.commons + commons-lang3 + log4j log4j diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java new file mode 100644 index 00000000000..97fe5751d4d --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.utils; + +import org.apache.commons.lang3.time.FastDateFormat; + +import java.util.Date; + +/** + * This class is utility to provide dubbo date formatting and parsing. + */ +public final class DateUtil { + + private DateUtil() { + + }; + + /** + * This method used to return a formatted string of a given date object. + * @param date Input data object + * @param format format of data. + * @return + */ + public static String format(Date date,String format) { + Assert.notNull(date,"Given date can't be null"); + Assert.notEmptyString(format,"Given date format can't be null or empty"); + return FastDateFormat.getInstance(format).format(date); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 2690dbf11b0..5043fc5e8ef 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.rpc.filter; +import static org.apache.dubbo.common.utils.DateUtil.format; + import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; @@ -30,12 +31,11 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; - -import com.alibaba.fastjson.JSON; +import org.apache.dubbo.rpc.support.AccessLogData; import java.io.File; import java.io.FileWriter; -import java.text.SimpleDateFormat; +import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.Map; @@ -44,7 +44,6 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** @@ -68,88 +67,39 @@ public class AccessLogFilter implements Filter { private static final String ACCESS_LOG_KEY = "dubbo.accesslog"; - private static final String FILE_DATE_FORMAT = "yyyyMMdd"; - - private static final String MESSAGE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; - private static final int LOG_MAX_BUFFER = 5000; private static final long LOG_OUTPUT_INTERVAL = 5000; - private final ConcurrentMap> logQueue = new ConcurrentHashMap>(); - - private final ScheduledExecutorService logScheduled = Executors.newScheduledThreadPool(2, new NamedThreadFactory("Dubbo-Access-Log", true)); + private static final String FILE_DATE_FORMAT = "yyyyMMdd"; - private volatile ScheduledFuture logFuture = null; + private static final ConcurrentMap> logQueue = new ConcurrentHashMap>(); - private void init() { - if (logFuture == null) { - synchronized (logScheduled) { - if (logFuture == null) { - logFuture = logScheduled.scheduleWithFixedDelay(new LogTask(), LOG_OUTPUT_INTERVAL, LOG_OUTPUT_INTERVAL, TimeUnit.MILLISECONDS); - } - } - } - } + private static final ScheduledExecutorService logScheduled = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Access-Log", true)); - private void log(String accesslog, String logmessage) { - init(); - Set logSet = logQueue.get(accesslog); - if (logSet == null) { - logQueue.putIfAbsent(accesslog, new ConcurrentHashSet()); - logSet = logQueue.get(accesslog); - } - if (logSet.size() < LOG_MAX_BUFFER) { - logSet.add(logmessage); - } + /** + * Default constructor initialize demon thread for writing into access log file with names with access log key + * defined in url accesslog + */ + public AccessLogFilter() { + logScheduled.scheduleWithFixedDelay(this::writeLogToFile, LOG_OUTPUT_INTERVAL, LOG_OUTPUT_INTERVAL, TimeUnit.MILLISECONDS); } + /** + * This method logs the access log for service method invocation call. + * + * @param invoker service + * @param inv Invocation service method. + * @return Result from service method. + * @throws RpcException + */ @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { try { - String accesslog = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); - if (ConfigUtils.isNotEmpty(accesslog)) { - RpcContext context = RpcContext.getContext(); - String serviceName = invoker.getInterface().getName(); - String version = invoker.getUrl().getParameter(Constants.VERSION_KEY); - String group = invoker.getUrl().getParameter(Constants.GROUP_KEY); - StringBuilder sn = new StringBuilder(); - sn.append("[").append(new SimpleDateFormat(MESSAGE_DATE_FORMAT).format(new Date())).append("] ").append(context.getRemoteHost()).append(":").append(context.getRemotePort()) - .append(" -> ").append(context.getLocalHost()).append(":").append(context.getLocalPort()) - .append(" - "); - if (null != group && group.length() > 0) { - sn.append(group).append("/"); - } - sn.append(serviceName); - if (null != version && version.length() > 0) { - sn.append(":").append(version); - } - sn.append(" "); - sn.append(inv.getMethodName()); - sn.append("("); - Class[] types = inv.getParameterTypes(); - if (types != null && types.length > 0) { - boolean first = true; - for (Class type : types) { - if (first) { - first = false; - } else { - sn.append(","); - } - sn.append(type.getName()); - } - } - sn.append(") "); - Object[] args = inv.getArguments(); - if (ArrayUtils.isNotEmpty(args)) { - sn.append(JSON.toJSONString(args)); - } - String msg = sn.toString(); - if (ConfigUtils.isDefault(accesslog)) { - LoggerFactory.getLogger(ACCESS_LOG_KEY + "." + invoker.getInterface().getName()).info(msg); - } else { - log(accesslog, msg); - } + String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); + if (ConfigUtils.isNotEmpty(accessLogKey)) { + AccessLogData logData = buildAccessLogData(invoker, inv); + log(accessLogKey, logData); } } catch (Throwable t) { logger.warn("Exception in AcessLogFilter of service(" + invoker + " -> " + inv + ")", t); @@ -157,52 +107,94 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { return invoker.invoke(inv); } - private class LogTask implements Runnable { - @Override - public void run() { - try { - if (logQueue != null && logQueue.size() > 0) { - for (Map.Entry> entry : logQueue.entrySet()) { - try { - String accesslog = entry.getKey(); - Set logSet = entry.getValue(); - File file = new File(accesslog); - File dir = file.getParentFile(); - if (null != dir && !dir.exists()) { - dir.mkdirs(); - } - if (logger.isDebugEnabled()) { - logger.debug("Append log to " + accesslog); - } - if (file.exists()) { - String now = new SimpleDateFormat(FILE_DATE_FORMAT).format(new Date()); - String last = new SimpleDateFormat(FILE_DATE_FORMAT).format(new Date(file.lastModified())); - if (!now.equals(last)) { - File archive = new File(file.getAbsolutePath() + "." + last); - file.renameTo(archive); - } - } - FileWriter writer = new FileWriter(file, true); - try { - for (Iterator iterator = logSet.iterator(); - iterator.hasNext(); - iterator.remove()) { - writer.write(iterator.next()); - writer.write("\r\n"); - } - writer.flush(); - } finally { - writer.close(); - } - } catch (Exception e) { - logger.error(e.getMessage(), e); + private void log(String accessLog, AccessLogData accessLogData) { + Set logSet = logQueue.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); + + if (logSet.size() < LOG_MAX_BUFFER) { + logSet.add(accessLogData); + } else { + //TODO we needs use force writing to file so that buffer gets clear and new log can be written. + logger.warn("AccessLog buffer is full skipping buffer "); + } + } + + private void writeLogToFile() { + if (!logQueue.isEmpty()) { + for (Map.Entry> entry : logQueue.entrySet()) { + try { + String accessLog = entry.getKey(); + Set logSet = entry.getValue(); + if (ConfigUtils.isDefault(accessLog)) { + processWithServiceLogger(logSet); + } else { + File file = new File(accessLog); + createIfLogDirAbsent(file); + if (logger.isDebugEnabled()) { + logger.debug("Append log to " + accessLog); } + renameFile(file); + processWithAccessKeyLogger(logSet, file); } + + } catch (Exception e) { + logger.error(e.getMessage(), e); } - } catch (Exception e) { - logger.error(e.getMessage(), e); } } } -} + private void processWithAccessKeyLogger(Set logSet, File file) throws IOException { + FileWriter writer = new FileWriter(file, true); + try { + for (Iterator iterator = logSet.iterator(); + iterator.hasNext(); + iterator.remove()) { + writer.write(iterator.next().getLogMessage()); + writer.write("\r\n"); + } + writer.flush(); + } finally { + writer.close(); + } + } + + private AccessLogData buildAccessLogData(Invoker invoker, Invocation inv) { + RpcContext context = RpcContext.getContext(); + AccessLogData logData = AccessLogData.newLogData(); + logData.setServiceName(invoker.getInterface().getName()); + logData.setMethodName(inv.getMethodName()); + logData.setVersion(invoker.getUrl().getParameter(Constants.VERSION_KEY)); + logData.setGroup(invoker.getUrl().getParameter(Constants.GROUP_KEY)); + logData.setInvocationTime(new Date()); + logData.setTypes(inv.getParameterTypes()); + logData.setArguments(inv.getArguments()); + return logData; + } + + private void processWithServiceLogger(Set logSet) { + for (Iterator iterator = logSet.iterator(); + iterator.hasNext(); + iterator.remove()) { + AccessLogData logData = iterator.next(); + LoggerFactory.getLogger(ACCESS_LOG_KEY + "." + logData.getServiceName()).info(logData.getLogMessage()); + } + } + + private void createIfLogDirAbsent(File file) { + File dir = file.getParentFile(); + if (null != dir && !dir.exists()) { + dir.mkdirs(); + } + } + + private void renameFile(File file) { + if (file.exists()) { + String now = format(new Date(), FILE_DATE_FORMAT); + String last = format(new Date(file.lastModified()), FILE_DATE_FORMAT); + if (!now.equals(last)) { + File archive = new File(file.getAbsolutePath() + "." + last); + file.renameTo(archive); + } + } + } +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java new file mode 100644 index 00000000000..049a90a63af --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java @@ -0,0 +1,270 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.rpc.support; + +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.RpcContext; + +import com.alibaba.fastjson.JSON; + +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.apache.dubbo.common.utils.DateUtil.format; + +/** + * AccessLogData is a container for log event data. In internally uses map and store each filed of log as value. It does not generate any + * dynamic value e.g. time stamp, local jmv machine host address etc. It does not allow any null or empty key. + */ +public final class AccessLogData { + + private static final String MESSAGE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + private static final String VERSION = "version"; + private static final String GROUP = "group"; + private static final String SERVICE = "service"; + private static final String METHOD_NAME = "method-name"; + private static final String INVOCATION_TIME = "invocation-time"; + private static final String TYPES = "types"; + private static final String ARGUMENTS = "arguments"; + private static final String REMOTE_HOST = "remote-host"; + private static final String REMOTE_PORT = "remote-port"; + private static final String LOCAL_HOST = "localhost"; + private static final String LOCAL_PORT = "local-port"; + + /** + * This is used to store log data in key val format. + */ + private Map data; + + /** + * Default constructor. + */ + private AccessLogData() { + RpcContext context = RpcContext.getContext(); + data = new HashMap<>(); + setLocalHost(context.getLocalHost()); + setLocalPort(context.getLocalPort()); + setRemoteHost(context.getRemoteHost()); + setRemotePort(context.getRemotePort()); + } + + /** + * Get new instance of log data. + * + * @return instance of AccessLogData + */ + public static AccessLogData newLogData() { + return new AccessLogData(); + } + + /** + * Sets the access log key + * + * @param accessLogKey + */ + public void setAccessLogKey(String accessLogKey) { + + } + + /** + * Add version information. + * + * @param version + */ + public void setVersion(String version) { + set(VERSION, version); + } + + /** + * Add service name. + * + * @param serviceName + */ + public void setServiceName(String serviceName) { + set(SERVICE, serviceName); + } + + /** + * Add group name + * + * @param group + */ + public void setGroup(String group) { + set(GROUP, group); + } + + /** + * Set the invocation date. As an argument it accept date string. + * + * @param invocationTime + */ + public void setInvocationTime(Date invocationTime) { + set(INVOCATION_TIME, invocationTime); + } + + /** + * Set caller remote host + * + * @param remoteHost + */ + private void setRemoteHost(String remoteHost) { + set(REMOTE_HOST, remoteHost); + } + + /** + * Set caller remote port. + * + * @param remotePort + */ + private void setRemotePort(Integer remotePort) { + set(REMOTE_PORT, remotePort); + } + + /** + * Set local host + * + * @param localHost + */ + private void setLocalHost(String localHost) { + set(LOCAL_HOST, localHost); + } + + /** + * Set local port of exported service + * + * @param localPort + */ + private void setLocalPort(Integer localPort) { + set(LOCAL_PORT, localPort); + } + + /** + * Set target method name. + * + * @param methodName + */ + public void setMethodName(String methodName) { + set(METHOD_NAME, methodName); + } + + /** + * Set invocation's method's input parameter's types + * + * @param types + */ + public void setTypes(Class[] types) { + set(TYPES, types != null ? Arrays.copyOf(types, types.length) : null); + } + + /** + * Sets invocation arguments + * + * @param arguments + */ + public void setArguments(Object[] arguments) { + set(ARGUMENTS, arguments != null ? Arrays.copyOf(arguments, arguments.length) : null); + } + + /** + * Return gthe service of access log entry + * + * @return + */ + public String getServiceName() { + return get(SERVICE).toString(); + } + + + public String getLogMessage() { + StringBuilder sn = new StringBuilder(); + + sn.append("[") + .append(format(getInvocationTime(), MESSAGE_DATE_FORMAT)) + .append("] ") + .append(get(REMOTE_HOST)) + .append(":") + .append(get(REMOTE_PORT)) + .append(" -> ") + .append(get(LOCAL_HOST)) + .append(":") + .append(get(LOCAL_PORT)) + .append(" - "); + + String group = get(GROUP) != null ? get(GROUP).toString() : ""; + if (StringUtils.isNotEmpty(group.toString())) { + sn.append(group).append("/"); + } + + sn.append(get(SERVICE)); + + String version = get(VERSION) != null ? get(VERSION).toString() : ""; + if (StringUtils.isNotEmpty(version.toString())) { + sn.append(":").append(version); + } + + sn.append(" "); + sn.append(get(METHOD_NAME)); + + sn.append("("); + Class[] types = get(TYPES) != null ? (Class[]) get(TYPES) : new Class[0]; + boolean first = true; + for (Class type : types) { + if (first) { + first = false; + } else { + sn.append(","); + } + sn.append(type.getName()); + } + sn.append(") "); + + + Object[] args = get(ARGUMENTS) != null ? (Object[]) get(ARGUMENTS) : null; + if (args != null && args.length > 0) { + sn.append(JSON.toJSONString(args)); + } + + return sn.toString(); + } + + private Date getInvocationTime() { + return (Date)get(INVOCATION_TIME); + } + /** + * Return value of key + * + * @param key + * @return + */ + private Object get(String key) { + return data.get(key); + } + + /** + * Add log key along with his value. + * + * @param key Any not null or non empty string + * @param value Any object including null. + */ + private void set(String key, Object value) { + data.put(key, value); + } + +} \ No newline at end of file From bf6e9abf46abab3582d4dfb3b84672550a104d53 Mon Sep 17 00:00:00 2001 From: khanimteyaz Date: Sat, 19 Jan 2019 11:50:02 +0530 Subject: [PATCH 2/5] Reviwe comment incorporated given by @satansk and removed unuded method --- .../org/apache/dubbo/common/utils/DateUtil.java | 6 +++--- .../apache/dubbo/rpc/filter/AccessLogFilter.java | 14 +++++--------- .../apache/dubbo/rpc/support/AccessLogData.java | 8 -------- 3 files changed, 8 insertions(+), 20 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java index 97fe5751d4d..11d5a7606a4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java @@ -35,9 +35,9 @@ private DateUtil() { * @param format format of data. * @return */ - public static String format(Date date,String format) { - Assert.notNull(date,"Given date can't be null"); - Assert.notEmptyString(format,"Given date format can't be null or empty"); + public static String format(Date date, String format) { + Assert.notNull(date, "Given date can't be null"); + Assert.notEmptyString(format, "Given date format can't be null or empty"); return FastDateFormat.getInstance(format).format(date); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 5043fc5e8ef..a3eb0bb251b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -41,7 +41,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -73,7 +72,7 @@ public class AccessLogFilter implements Filter { private static final String FILE_DATE_FORMAT = "yyyyMMdd"; - private static final ConcurrentMap> logQueue = new ConcurrentHashMap>(); + private static final Map> logEntries = new ConcurrentHashMap>(); private static final ScheduledExecutorService logScheduled = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Access-Log", true)); @@ -108,7 +107,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } private void log(String accessLog, AccessLogData accessLogData) { - Set logSet = logQueue.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); + Set logSet = logEntries.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); if (logSet.size() < LOG_MAX_BUFFER) { logSet.add(accessLogData); @@ -119,8 +118,8 @@ private void log(String accessLog, AccessLogData accessLogData) { } private void writeLogToFile() { - if (!logQueue.isEmpty()) { - for (Map.Entry> entry : logQueue.entrySet()) { + if (!logEntries.isEmpty()) { + for (Map.Entry> entry : logEntries.entrySet()) { try { String accessLog = entry.getKey(); Set logSet = entry.getValue(); @@ -144,8 +143,7 @@ private void writeLogToFile() { } private void processWithAccessKeyLogger(Set logSet, File file) throws IOException { - FileWriter writer = new FileWriter(file, true); - try { + try (FileWriter writer = new FileWriter(file, true)) { for (Iterator iterator = logSet.iterator(); iterator.hasNext(); iterator.remove()) { @@ -153,8 +151,6 @@ private void processWithAccessKeyLogger(Set logSet, File file) th writer.write("\r\n"); } writer.flush(); - } finally { - writer.close(); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java index 049a90a63af..852381c94ff 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java @@ -74,14 +74,6 @@ public static AccessLogData newLogData() { return new AccessLogData(); } - /** - * Sets the access log key - * - * @param accessLogKey - */ - public void setAccessLogKey(String accessLogKey) { - - } /** * Add version information. From 9a98de6a2f58c6bdcb5dbab1c71e9da97f43343f Mon Sep 17 00:00:00 2001 From: Imteyaz Khan Date: Mon, 21 Jan 2019 22:18:42 +0530 Subject: [PATCH 3/5] Incorporated @beiwei30 review comment, incorporated common-lang3 time package modified version --- LICENSE | 12 + dubbo-common/pom.xml | 4 - .../apache/dubbo/common/time/DateParser.java | 120 ++ .../apache/dubbo/common/time/DatePrinter.java | 171 ++ .../dubbo/common/time/FastDateFormat.java | 380 +++++ .../dubbo/common/time/FastDateParser.java | 954 +++++++++++ .../dubbo/common/time/FastDatePrinter.java | 1514 +++++++++++++++++ .../dubbo/common/time/FastTimeZone.java | 97 ++ .../apache/dubbo/common/time/FormatCache.java | 211 +++ .../apache/dubbo/common/time/GmtTimeZone.java | 104 ++ .../apache/dubbo/common/utils/DateUtil.java | 2 +- 11 files changed, 3564 insertions(+), 5 deletions(-) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java diff --git a/LICENSE b/LICENSE index b85622380cf..9c706ace39a 100644 --- a/LICENSE +++ b/LICENSE @@ -229,3 +229,15 @@ This product contains a modified portion of 'Netty', an event-driven asynchronou * io.netty.util.Timeout * io.netty.util.HashedWheelTimer + This product contains modified portion of common-lang3 org.apache.commons.lang3.time package java file, an thread safe date format utility, which + is under a "Apache License 2.0" license, see https://github.com/apache/commons-lang/blob/master/LICENSE.txt + + * org.apache.commons.lang3.time.DateParser + * org.apache.commons.lang3.time.DatePrinter + * org.apache.commons.lang3.time.FastDateFormat + * org.apache.commons.lang3.FastDateParser + * org.apache.commons.lang3.FastDatePrinter + * org.apache.commons.lang3.FastTimeZone + * org.apache.commons.lang3.FormatCache + * org.apache.commons.lang3.GmtTimeZone + diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index a474da3b7e4..22a13222fe2 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -39,10 +39,6 @@ commons-logging commons-logging - - org.apache.commons - commons-lang3 - log4j log4j diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java new file mode 100644 index 00000000000..36b6b0c2c39 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.time; + +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * DateParser interface + */ +public interface DateParser { + + /** + * Equivalent to DateFormat.parse(String). + * + * See {@link java.text.DateFormat#parse(String)} for more information. + * @param source A String whose beginning should be parsed. + * @return A Date parsed from the string + * @throws ParseException if the beginning of the specified string cannot be parsed. + */ + Date parse(String source) throws ParseException; + + /** + * Equivalent to DateFormat.parse(String, ParsePosition). + * + * See {@link java.text.DateFormat#parse(String, ParsePosition)} for more information. + * + * @param source A String, part of which should be parsed. + * @param pos A ParsePosition object with index and error index information + * as described above. + * @return A Date parsed from the string. In case of error, returns null. + * @throws NullPointerException if text or pos is null. + */ + Date parse(String source, ParsePosition pos); + + /** + * Parses a formatted date string according to the format. Updates the Calendar with parsed fields. + * Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. + * Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to + * the offset of the source text which does not match the supplied format. + * + * @param source The text to parse. + * @param pos On input, the position in the source to start parsing, on output, updated position. + * @param calendar The calendar into which to set parsed fields. + * @return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated) + * @throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is + * out of range. + * + * @since 3.5 + */ + boolean parse(String source, ParsePosition pos, Calendar calendar); + + // Accessors + //----------------------------------------------------------------------- + /** + *

Gets the pattern used by this parser.

+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *

+ * Gets the time zone used by this parser. + *

+ * + *

+ * The default {@link TimeZone} used to create a {@link Date} when the {@link TimeZone} is not specified by + * the format pattern. + *

+ * + * @return the time zone + */ + TimeZone getTimeZone(); + + /** + *

Gets the locale used by this parser.

+ * + * @return the locale + */ + Locale getLocale(); + + /** + * Parses text from a string to produce a Date. + * + * @param source A String whose beginning should be parsed. + * @return a java.util.Date object + * @throws ParseException if the beginning of the specified string cannot be parsed. + * @see java.text.DateFormat#parseObject(String) + */ + Object parseObject(String source) throws ParseException; + + /** + * Parses a date/time string according to the given parse position. + * + * @param source A String whose beginning should be parsed. + * @param pos the parse position + * @return a java.util.Date object + * @see java.text.DateFormat#parseObject(String, ParsePosition) + */ + Object parseObject(String source, ParsePosition pos); +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java new file mode 100644 index 00000000000..8b3b5e4645c --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java @@ -0,0 +1,171 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.time; + +import java.text.FieldPosition; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * DatePrinter interface + */ +public interface DatePrinter { + + /** + *

Formats a millisecond {@code long} value.

+ * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + String format(long millis); + + /** + *

Formats a {@code Date} object using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @return the formatted string + */ + String format(Date date); + + /** + *

Formats a {@code Calendar} object.

+ * The TimeZone set on the Calendar is only used to adjust the time offset. + * The TimeZone specified during the construction of the Parser will determine the TimeZone + * used in the formatted string. + * + * @param calendar the calendar to format. + * @return the formatted string + */ + String format(Calendar calendar); + + /** + *

Formats a millisecond {@code long} value into the + * supplied {@code StringBuffer}.

+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(long, Appendable)}. + */ + @Deprecated + StringBuffer format(long millis, StringBuffer buf); + + /** + *

Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Date, Appendable)}. + */ + @Deprecated + StringBuffer format(Date date, StringBuffer buf); + + /** + *

Formats a {@code Calendar} object into the supplied {@code StringBuffer}.

+ * The TimeZone set on the Calendar is only used to adjust the time offset. + * The TimeZone specified during the construction of the Parser will determine the TimeZone + * used in the formatted string. + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Calendar, Appendable)}. + */ + @Deprecated + StringBuffer format(Calendar calendar, StringBuffer buf); + + /** + *

Formats a millisecond {@code long} value into the + * supplied {@code Appendable}.

+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or StringBuffer. + * @return the specified string buffer + * @since 3.5 + */ + B format(long millis, B buf); + + /** + *

Formats a {@code Date} object into the + * supplied {@code Appendable} using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or StringBuffer. + * @return the specified string buffer + * @since 3.5 + */ + B format(Date date, B buf); + + /** + *

Formats a {@code Calendar} object into the supplied {@code Appendable}.

+ * The TimeZone set on the Calendar is only used to adjust the time offset. + * The TimeZone specified during the construction of the Parser will determine the TimeZone + * used in the formatted string. + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or StringBuffer. + * @return the specified string buffer + * @since 3.5 + */ + B format(Calendar calendar, B buf); + + + // Accessors + //----------------------------------------------------------------------- + /** + *

Gets the pattern used by this printer.

+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *

Gets the time zone used by this printer.

+ * + *

This zone is always used for {@code Date} printing.

+ * + * @return the time zone + */ + TimeZone getTimeZone(); + + /** + *

Gets the locale used by this printer.

+ * + * @return the locale + */ + Locale getLocale(); + + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + * @see java.text.DateFormat#format(Object, StringBuffer, FieldPosition) + */ + StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java new file mode 100644 index 00000000000..99b492d9c49 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java @@ -0,0 +1,380 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.time; + +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +/** + * FastDateFormat + */ +public class FastDateFormat extends Format implements DateParser, DatePrinter { + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 2L; + + private static final FormatCache cache= new FormatCache() { + @Override + protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) { + return new FastDateFormat(pattern, timeZone, locale); + } + }; + + private final FastDatePrinter printer; + private final FastDateParser parser; + + //----------------------------------------------------------------------- + /** + *

Gets a formatter instance using the default pattern in the + * default locale.

+ * + * @return a date/time formatter + */ + public static FastDateFormat getInstance() { + return cache.getInstance(); + } + + /** + *

Gets a formatter instance using the specified pattern in the + * default locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern) { + return cache.getInstance(pattern, null, null); + } + + + // Constructor + //----------------------------------------------------------------------- + /** + *

Constructs a new FastDateFormat.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale) { + this(pattern, timeZone, locale, null); + } + + // Constructor + //----------------------------------------------------------------------- + /** + *

Constructs a new FastDateFormat.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @param centuryStart The start of the 100 year period to use as the "default century" for 2 digit year parsing. If centuryStart is null, defaults to now - 80 years + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { + printer= new FastDatePrinter(pattern, timeZone, locale); + parser= new FastDateParser(pattern, timeZone, locale, centuryStart); + } + + // Format methods + //----------------------------------------------------------------------- + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ * This method is an implementation of {@link Format#format(Object, StringBuffer, FieldPosition)} + * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + return toAppendTo.append(printer.format(obj)); + } + + /** + *

Formats a millisecond {@code long} value.

+ * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + @Override + public String format(final long millis) { + return printer.format(millis); + } + + /** + *

Formats a {@code Date} object using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @return the formatted string + */ + @Override + public String format(final Date date) { + return printer.format(date); + } + + /** + *

Formats a {@code Calendar} object.

+ * + * @param calendar the calendar to format + * @return the formatted string + */ + @Override + public String format(final Calendar calendar) { + return printer.format(calendar); + } + + /** + *

Formats a millisecond {@code long} value into the + * supplied {@code StringBuffer}.

+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 2.1 + * @deprecated Use {{@link #format(long, Appendable)}. + */ + @Deprecated + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + return printer.format(millis, buf); + } + + /** + *

Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Date, Appendable)}. + */ + @Deprecated + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + return printer.format(date, buf); + } + + /** + *

Formats a {@code Calendar} object into the + * supplied {@code StringBuffer}.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Calendar, Appendable)}. + */ + @Deprecated + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + return printer.format(calendar, buf); + } + + /** + *

Formats a millisecond {@code long} value into the + * supplied {@code StringBuffer}.

+ * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 3.5 + */ + @Override + public B format(final long millis, final B buf) { + return printer.format(millis, buf); + } + + /** + *

Formats a {@code Date} object into the + * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

+ * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 3.5 + */ + @Override + public B format(final Date date, final B buf) { + return printer.format(date, buf); + } + + /** + *

Formats a {@code Calendar} object into the + * supplied {@code StringBuffer}.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 3.5 + */ + @Override + public B format(final Calendar calendar, final B buf) { + return printer.format(calendar, buf); + } + + // Parsing + //----------------------------------------------------------------------- + + + /* (non-Javadoc) + * @see DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + return parser.parse(source); + } + + /* (non-Javadoc) + * @see DateParser#parse(java.lang.String, java.text.ParsePosition) + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + return parser.parse(source, pos); + } + + /* + * (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition, java.util.Calendar) + */ + @Override + public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { + return parser.parse(source, pos, calendar); + } + + /* (non-Javadoc) + * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parser.parseObject(source, pos); + } + + // Accessors + //----------------------------------------------------------------------- + /** + *

Gets the pattern used by this formatter.

+ * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + @Override + public String getPattern() { + return printer.getPattern(); + } + + /** + *

Gets the time zone used by this formatter.

+ * + *

This zone is always used for {@code Date} formatting.

+ * + * @return the time zone + */ + @Override + public TimeZone getTimeZone() { + return printer.getTimeZone(); + } + + /** + *

Gets the locale used by this formatter.

+ * + * @return the locale + */ + @Override + public Locale getLocale() { + return printer.getLocale(); + } + + /** + *

Gets an estimate for the maximum string length that the + * formatter will produce.

+ * + *

The actual formatted length will almost always be less than or + * equal to this amount.

+ * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return printer.getMaxLengthEstimate(); + } + + // Basics + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality.

+ * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateFormat)) { + return false; + } + final FastDateFormat other = (FastDateFormat) obj; + // no need to check parser, as it has same invariants as printer + return printer.equals(other.printer); + } + + /** + *

Returns a hash code compatible with equals.

+ * + * @return a hash code compatible with equals + */ + @Override + public int hashCode() { + return printer.hashCode(); + } + + /** + *

Gets a debugging string version of this formatter.

+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; + } + + /** + *

Performs the formatting by applying the rules to the + * specified calendar.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {@link #format(Calendar, Appendable)} + */ + @Deprecated + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + return printer.applyRules(calendar, buf); + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java new file mode 100644 index 00000000000..62a64f8d8b4 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java @@ -0,0 +1,954 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.time; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.text.DateFormatSymbols; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *

FastDateParser is a fast and thread-safe version of SimpleDateFormat + */ +public class FastDateParser implements DateParser, Serializable { + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 3L; + + static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP"); + + // defining fields + private final String pattern; + private final TimeZone timeZone; + private final Locale locale; + private final int century; + private final int startYear; + + // derived fields + private transient List patterns; + + // comparator used to sort regex alternatives + // alternatives should be ordered longer first, and shorter last. ('february' before 'feb') + // all entries must be lowercase by locale. + private static final Comparator LONGER_FIRST_LOWERCASE = new Comparator() { + @Override + public int compare(final String left, final String right) { + return right.compareTo(left); + } + }; + + /** + *

Constructs a new FastDateParser.

+ * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + * @param centuryStart The start of the century for 2 digit year parsing + * + * @since 3.5 + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { + this.pattern = pattern; + this.timeZone = timeZone; + this.locale = locale; + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + + int centuryStartYear; + if (centuryStart!=null) { + definingCalendar.setTime(centuryStart); + centuryStartYear= definingCalendar.get(Calendar.YEAR); + } else if (locale.equals(JAPANESE_IMPERIAL)) { + centuryStartYear= 0; + } else { + // from 80 years ago to 20 years from now + definingCalendar.setTime(new Date()); + centuryStartYear= definingCalendar.get(Calendar.YEAR)-80; + } + century= centuryStartYear / 100 * 100; + startYear= centuryStartYear - century; + + init(definingCalendar); + } + + /** + * Initialize derived fields from defining fields. + * This is called from constructor and from readObject (de-serialization) + * + * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser + */ + private void init(final Calendar definingCalendar) { + patterns = new ArrayList<>(); + + final StrategyParser fm = new StrategyParser(definingCalendar); + for (;;) { + final StrategyAndWidth field = fm.getNextStrategy(); + if (field==null) { + break; + } + patterns.add(field); + } + } + + // helper classes to parse the format string + //----------------------------------------------------------------------- + + /** + * Holds strategy and field width + */ + private static class StrategyAndWidth { + final Strategy strategy; + final int width; + + StrategyAndWidth(final Strategy strategy, final int width) { + this.strategy = strategy; + this.width = width; + } + + int getMaxWidth(final ListIterator lt) { + if (!strategy.isNumber() || !lt.hasNext()) { + return 0; + } + final Strategy nextStrategy = lt.next().strategy; + lt.previous(); + return nextStrategy.isNumber() ?width :0; + } + } + + /** + * Parse format into Strategies + */ + private class StrategyParser { + private final Calendar definingCalendar; + private int currentIdx; + + StrategyParser(final Calendar definingCalendar) { + this.definingCalendar = definingCalendar; + } + + StrategyAndWidth getNextStrategy() { + if (currentIdx >= pattern.length()) { + return null; + } + + final char c = pattern.charAt(currentIdx); + if (isFormatLetter(c)) { + return letterPattern(c); + } + return literal(); + } + + private StrategyAndWidth letterPattern(final char c) { + final int begin = currentIdx; + while (++currentIdx < pattern.length()) { + if (pattern.charAt(currentIdx) != c) { + break; + } + } + + final int width = currentIdx - begin; + return new StrategyAndWidth(getStrategy(c, width, definingCalendar), width); + } + + private StrategyAndWidth literal() { + boolean activeQuote = false; + + final StringBuilder sb = new StringBuilder(); + while (currentIdx < pattern.length()) { + final char c = pattern.charAt(currentIdx); + if (!activeQuote && isFormatLetter(c)) { + break; + } else if (c == '\'' && (++currentIdx == pattern.length() || pattern.charAt(currentIdx) != '\'')) { + activeQuote = !activeQuote; + continue; + } + ++currentIdx; + sb.append(c); + } + + if (activeQuote) { + throw new IllegalArgumentException("Unterminated quote"); + } + + final String formatField = sb.toString(); + return new StrategyAndWidth(new CopyQuotedStrategy(formatField), formatField.length()); + } + } + + private static boolean isFormatLetter(final char c) { + return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; + } + + // Accessors + //----------------------------------------------------------------------- + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#getPattern() + */ + @Override + public String getPattern() { + return pattern; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return timeZone; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#getLocale() + */ + @Override + public Locale getLocale() { + return locale; + } + + + // Basics + //----------------------------------------------------------------------- + /** + *

Compare another object for equality with this object.

+ * + * @param obj the object to compare to + * @return trueif equal to this instance + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateParser)) { + return false; + } + final FastDateParser other = (FastDateParser) obj; + return pattern.equals(other.pattern) + && timeZone.equals(other.timeZone) + && locale.equals(other.locale); + } + + /** + *

Return a hash code compatible with equals.

+ * + * @return a hash code compatible with equals + */ + @Override + public int hashCode() { + return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); + } + + /** + *

Get a string version of this formatter.

+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]"; + } + + // Serializing + //----------------------------------------------------------------------- + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + init(definingCalendar); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String) + */ + @Override + public Object parseObject(final String source) throws ParseException { + return parse(source); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + final ParsePosition pp = new ParsePosition(0); + final Date date= parse(source, pp); + if (date == null) { + // Add a note re supported date range + if (locale.equals(JAPANESE_IMPERIAL)) { + throw new ParseException( + "(The " +locale + " locale does not support dates before 1868 AD)\n" + + "Unparseable date: \""+source, pp.getErrorIndex()); + } + throw new ParseException("Unparseable date: "+source, pp.getErrorIndex()); + } + return date; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parse(source, pos); + } + + /** + * This implementation updates the ParsePosition if the parse succeeds. + * However, it sets the error index to the position before the failed field unlike + * the method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)} which sets + * the error index to after the failed field. + *

+ * To determine if the parse has succeeded, the caller must check if the current parse position + * given by {@link ParsePosition#getIndex()} has been updated. If the input buffer has been fully + * parsed, then the index will point to just after the end of the input buffer. + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + // timing tests indicate getting new instance is 19% faster than cloning + final Calendar cal= Calendar.getInstance(timeZone, locale); + cal.clear(); + + return parse(source, pos, cal) ? cal.getTime() : null; + } + + /** + * Parse a formatted date string according to the format. Updates the Calendar with parsed fields. + * Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. + * Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to + * the offset of the source text which does not match the supplied format. + * + * @param source The text to parse. + * @param pos On input, the position in the source to start parsing, on output, updated position. + * @param calendar The calendar into which to set parsed fields. + * @return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated) + * @throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is + * out of range. + */ + @Override + public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { + final ListIterator lt = patterns.listIterator(); + while (lt.hasNext()) { + final StrategyAndWidth strategyAndWidth = lt.next(); + final int maxWidth = strategyAndWidth.getMaxWidth(lt); + if (!strategyAndWidth.strategy.parse(this, calendar, source, pos, maxWidth)) { + return false; + } + } + return true; + } + + // Support for strategies + //----------------------------------------------------------------------- + + private static StringBuilder simpleQuote(final StringBuilder sb, final String value) { + for (int i = 0; i < value.length(); ++i) { + final char c = value.charAt(i); + switch (c) { + case '\\': + case '^': + case '$': + case '.': + case '|': + case '?': + case '*': + case '+': + case '(': + case ')': + case '[': + case '{': + sb.append('\\'); + default: + sb.append(c); + } + } + if (sb.charAt(sb.length() - 1) == '.') { + // trailing '.' is optional + sb.append('?'); + } + return sb; + } + + /** + * Get the short and long values displayed for a field + * @param cal The calendar to obtain the short and long values + * @param locale The locale of display names + * @param field The field of interest + * @param regex The regular expression to build + * @return The map of string display names to field values + */ + private static Map appendDisplayNames(final Calendar cal, final Locale locale, final int field, final StringBuilder regex) { + final Map values = new HashMap<>(); + + final Map displayNames = cal.getDisplayNames(field, Calendar.ALL_STYLES, locale); + final TreeSet sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); + for (final Map.Entry displayName : displayNames.entrySet()) { + final String key = displayName.getKey().toLowerCase(locale); + if (sorted.add(key)) { + values.put(key, displayName.getValue()); + } + } + for (final String symbol : sorted) { + simpleQuote(regex, symbol).append('|'); + } + return values; + } + + /** + * Adjust dates to be within appropriate century + * @param twoDigitYear The year to adjust + * @return A value between centuryStart(inclusive) to centuryStart+100(exclusive) + */ + private int adjustYear(final int twoDigitYear) { + final int trial = century + twoDigitYear; + return twoDigitYear >= startYear ? trial : trial + 100; + } + + /** + * A strategy to parse a single field from the parsing pattern + */ + private abstract static class Strategy { + /** + * Is this field a number? + * The default implementation returns false. + * + * @return true, if field is a number + */ + boolean isNumber() { + return false; + } + + abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos, int maxWidth); + } + + /** + * A strategy to parse a single field from the parsing pattern + */ + private abstract static class PatternStrategy extends Strategy { + + private Pattern pattern; + + void createPattern(final StringBuilder regex) { + createPattern(regex.toString()); + } + + void createPattern(final String regex) { + this.pattern = Pattern.compile(regex); + } + + /** + * Is this field a number? + * The default implementation returns false. + * + * @return true, if field is a number + */ + @Override + boolean isNumber() { + return false; + } + + @Override + boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) { + final Matcher matcher = pattern.matcher(source.substring(pos.getIndex())); + if (!matcher.lookingAt()) { + pos.setErrorIndex(pos.getIndex()); + return false; + } + pos.setIndex(pos.getIndex() + matcher.end(1)); + setCalendar(parser, calendar, matcher.group(1)); + return true; + } + + abstract void setCalendar(FastDateParser parser, Calendar cal, String value); + } + + /** + * Obtain a Strategy given a field from a SimpleDateFormat pattern + * @param f A sub-sequence of the SimpleDateFormat pattern + * @param definingCalendar The calendar to obtain the short and long values + * @return The Strategy that will handle parsing for the field + */ + private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) { + switch(f) { + default: + throw new IllegalArgumentException("Format '"+f+"' not supported"); + case 'D': + return DAY_OF_YEAR_STRATEGY; + case 'E': + return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); + case 'F': + return DAY_OF_WEEK_IN_MONTH_STRATEGY; + case 'G': + return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); + case 'H': // Hour in day (0-23) + return HOUR_OF_DAY_STRATEGY; + case 'K': // Hour in am/pm (0-11) + return HOUR_STRATEGY; + case 'M': + return width>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY; + case 'S': + return MILLISECOND_STRATEGY; + case 'W': + return WEEK_OF_MONTH_STRATEGY; + case 'a': + return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); + case 'd': + return DAY_OF_MONTH_STRATEGY; + case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 + return HOUR12_STRATEGY; + case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0 + return HOUR24_OF_DAY_STRATEGY; + case 'm': + return MINUTE_STRATEGY; + case 's': + return SECOND_STRATEGY; + case 'u': + return DAY_OF_WEEK_STRATEGY; + case 'w': + return WEEK_OF_YEAR_STRATEGY; + case 'y': + case 'Y': + return width>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY; + case 'X': + return ISO8601TimeZoneStrategy.getStrategy(width); + case 'Z': + if (width==2) { + return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY; + } + //$FALL-THROUGH$ + case 'z': + return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); + } + } + + @SuppressWarnings("unchecked") // OK because we are creating an array with no entries + private static final ConcurrentMap[] caches = new ConcurrentMap[Calendar.FIELD_COUNT]; + + /** + * Get a cache of Strategies for a particular field + * @param field The Calendar field + * @return a cache of Locale to Strategy + */ + private static ConcurrentMap getCache(final int field) { + synchronized (caches) { + if (caches[field] == null) { + caches[field] = new ConcurrentHashMap<>(3); + } + return caches[field]; + } + } + + /** + * Construct a Strategy that parses a Text field + * @param field The Calendar field + * @param definingCalendar The calendar to obtain the short and long values + * @return a TextStrategy for the field and Locale + */ + private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) { + final ConcurrentMap cache = getCache(field); + Strategy strategy = cache.get(locale); + if (strategy == null) { + strategy = field == Calendar.ZONE_OFFSET + ? new TimeZoneStrategy(locale) + : new CaseInsensitiveTextStrategy(field, definingCalendar, locale); + final Strategy inCache = cache.putIfAbsent(locale, strategy); + if (inCache != null) { + return inCache; + } + } + return strategy; + } + + /** + * A strategy that copies the static or quoted field in the parsing pattern + */ + private static class CopyQuotedStrategy extends Strategy { + + private final String formatField; + + /** + * Construct a Strategy that ensures the formatField has literal text + * @param formatField The literal text to match + */ + CopyQuotedStrategy(final String formatField) { + this.formatField = formatField; + } + + /** + * {@inheritDoc} + */ + @Override + boolean isNumber() { + return false; + } + + @Override + boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) { + for (int idx = 0; idx < formatField.length(); ++idx) { + final int sIdx = idx + pos.getIndex(); + if (sIdx == source.length()) { + pos.setErrorIndex(sIdx); + return false; + } + if (formatField.charAt(idx) != source.charAt(sIdx)) { + pos.setErrorIndex(sIdx); + return false; + } + } + pos.setIndex(formatField.length() + pos.getIndex()); + return true; + } + } + + /** + * A strategy that handles a text field in the parsing pattern + */ + private static class CaseInsensitiveTextStrategy extends PatternStrategy { + private final int field; + final Locale locale; + private final Map lKeyValues; + + /** + * Construct a Strategy that parses a Text field + * @param field The Calendar field + * @param definingCalendar The Calendar to use + * @param locale The Locale to use + */ + CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) { + this.field = field; + this.locale = locale; + + final StringBuilder regex = new StringBuilder(); + regex.append("((?iu)"); + lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex); + regex.setLength(regex.length()-1); + regex.append(")"); + createPattern(regex); + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + final String lowerCase = value.toLowerCase(locale); + Integer iVal = lKeyValues.get(lowerCase); + if (iVal == null) { + // match missing the optional trailing period + iVal = lKeyValues.get(lowerCase + '.'); + } + cal.set(field, iVal.intValue()); + } + } + + + /** + * A strategy that handles a number field in the parsing pattern + */ + private static class NumberStrategy extends Strategy { + private final int field; + + /** + * Construct a Strategy that parses a Number field + * @param field The Calendar field + */ + NumberStrategy(final int field) { + this.field= field; + } + + /** + * {@inheritDoc} + */ + @Override + boolean isNumber() { + return true; + } + + @Override + boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) { + int idx = pos.getIndex(); + int last = source.length(); + + if (maxWidth == 0) { + // if no maxWidth, strip leading white space + for (; idx < last; ++idx) { + final char c = source.charAt(idx); + if (!Character.isWhitespace(c)) { + break; + } + } + pos.setIndex(idx); + } else { + final int end = idx + maxWidth; + if (last > end) { + last = end; + } + } + + for (; idx < last; ++idx) { + final char c = source.charAt(idx); + if (!Character.isDigit(c)) { + break; + } + } + + if (pos.getIndex() == idx) { + pos.setErrorIndex(idx); + return false; + } + + final int value = Integer.parseInt(source.substring(pos.getIndex(), idx)); + pos.setIndex(idx); + + calendar.set(field, modify(parser, value)); + return true; + } + + /** + * Make any modifications to parsed integer + * @param parser The parser + * @param iValue The parsed integer + * @return The modified value + */ + int modify(final FastDateParser parser, final int iValue) { + return iValue; + } + + } + + private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) { + /** + * {@inheritDoc} + */ + @Override + int modify(final FastDateParser parser, final int iValue) { + return iValue < 100 ? parser.adjustYear(iValue) : iValue; + } + }; + + /** + * A strategy that handles a timezone field in the parsing pattern + */ + static class TimeZoneStrategy extends PatternStrategy { + private static final String RFC_822_TIME_ZONE = "[+-]\\d{4}"; + private static final String GMT_OPTION = FastTimeZone.GMT_ID + "[+-]\\d{1,2}:\\d{2}"; + + private final Locale locale; + private final Map tzNames= new HashMap<>(); + + private static class TzInfo { + TimeZone zone; + int dstOffset; + + TzInfo(final TimeZone tz, final boolean useDst) { + zone = tz; + dstOffset = useDst ?tz.getDSTSavings() :0; + } + } + + /** + * Index of zone id + */ + private static final int ID = 0; + + /** + * Construct a Strategy that parses a TimeZone + * @param locale The Locale + */ + TimeZoneStrategy(final Locale locale) { + this.locale = locale; + + final StringBuilder sb = new StringBuilder(); + sb.append("((?iu)" + RFC_822_TIME_ZONE + "|" + GMT_OPTION ); + + final Set sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); + + final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings(); + for (final String[] zoneNames : zones) { + // offset 0 is the time zone ID and is not localized + final String tzId = zoneNames[ID]; + if (tzId.equalsIgnoreCase(FastTimeZone.GMT_ID)) { + continue; + } + final TimeZone tz = TimeZone.getTimeZone(tzId); + // offset 1 is long standard name + // offset 2 is short standard name + final TzInfo standard = new TzInfo(tz, false); + TzInfo tzInfo = standard; + for (int i = 1; i < zoneNames.length; ++i) { + switch (i) { + case 3: // offset 3 is long daylight savings (or summertime) name + // offset 4 is the short summertime name + tzInfo = new TzInfo(tz, true); + break; + case 5: // offset 5 starts additional names, probably standard time + tzInfo = standard; + break; + default: + break; + } + if (zoneNames[i] != null) { + final String key = zoneNames[i].toLowerCase(locale); + // ignore the data associated with duplicates supplied in + // the additional names + if (sorted.add(key)) { + tzNames.put(key, tzInfo); + } + } + } + } + // order the regex alternatives with longer strings first, greedy + // match will ensure longest string will be consumed + for (final String zoneName : sorted) { + simpleQuote(sb.append('|'), zoneName); + } + sb.append(")"); + createPattern(sb); + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String timeZone) { + final TimeZone tz = FastTimeZone.getGmtTimeZone(timeZone); + if (tz != null) { + cal.setTimeZone(tz); + } else { + final String lowerCase = timeZone.toLowerCase(locale); + TzInfo tzInfo = tzNames.get(lowerCase); + if (tzInfo == null) { + // match missing the optional trailing period + tzInfo = tzNames.get(lowerCase + '.'); + } + cal.set(Calendar.DST_OFFSET, tzInfo.dstOffset); + cal.set(Calendar.ZONE_OFFSET, tzInfo.zone.getRawOffset()); + } + } + } + + private static class ISO8601TimeZoneStrategy extends PatternStrategy { + // Z, +hh, -hh, +hhmm, -hhmm, +hh:mm or -hh:mm + + /** + * Construct a Strategy that parses a TimeZone + * @param pattern The Pattern + */ + ISO8601TimeZoneStrategy(final String pattern) { + createPattern(pattern); + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { + cal.setTimeZone(FastTimeZone.getGmtTimeZone(value)); + } + + private static final Strategy ISO_8601_1_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}))"); + private static final Strategy ISO_8601_2_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}\\d{2}))"); + private static final Strategy ISO_8601_3_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}(?::)\\d{2}))"); + + /** + * Factory method for ISO8601TimeZoneStrategies. + * + * @param tokenLen a token indicating the length of the TimeZone String to be formatted. + * @return a ISO8601TimeZoneStrategy that can format TimeZone String of length {@code tokenLen}. If no such + * strategy exists, an IllegalArgumentException will be thrown. + */ + static Strategy getStrategy(final int tokenLen) { + switch(tokenLen) { + case 1: + return ISO_8601_1_STRATEGY; + case 2: + return ISO_8601_2_STRATEGY; + case 3: + return ISO_8601_3_STRATEGY; + default: + throw new IllegalArgumentException("invalid number of X"); + } + } + } + + private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) { + @Override + int modify(final FastDateParser parser, final int iValue) { + return iValue-1; + } + }; + + private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR); + private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR); + private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH); + private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR); + private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH); + private static final Strategy DAY_OF_WEEK_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK) { + @Override + int modify(final FastDateParser parser, final int iValue) { + return iValue == 7 ? Calendar.SUNDAY : iValue + 1; + } + }; + + private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH); + private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY); + private static final Strategy HOUR24_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) { + @Override + int modify(final FastDateParser parser, final int iValue) { + return iValue == 24 ? 0 : iValue; + } + }; + + private static final Strategy HOUR12_STRATEGY = new NumberStrategy(Calendar.HOUR) { + @Override + int modify(final FastDateParser parser, final int iValue) { + return iValue == 12 ? 0 : iValue; + } + }; + + private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR); + private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE); + private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND); + private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND); +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java new file mode 100644 index 00000000000..ee9644f082e --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java @@ -0,0 +1,1514 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.time; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.text.DateFormatSymbols; +import java.text.FieldPosition; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + *

FastDatePrinter is a fast and thread-safe version

+ */ +public class FastDatePrinter implements DatePrinter, Serializable { + // A lot of the speed in this class comes from caching, but some comes + // from the special int to StringBuffer conversion. + // + // The following produces a padded 2 digit number: + // buffer.append((char)(value / 10 + '0')); + // buffer.append((char)(value % 10 + '0')); + // + // Note that the fastest append to StringBuffer is a single char (used here). + // Note that Integer.toString() is not called, the conversion is simply + // taking the value and adding (mathematically) the ASCII value for '0'. + // So, don't change this code! It works and is very fast. + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + + /** + * The pattern. + */ + private final String mPattern; + /** + * The time zone. + */ + private final TimeZone mTimeZone; + /** + * The locale. + */ + private final Locale mLocale; + /** + * The parsed rules. + */ + private transient Rule[] mRules; + /** + * The estimated maximum length. + */ + private transient int mMaxLengthEstimate; + + // Constructor + //----------------------------------------------------------------------- + /** + *

Constructs a new FastDatePrinter.

+ * factory methods of {@link FastDateFormat} to get a cached FastDatePrinter instance. + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale to use + * @throws NullPointerException if pattern, timeZone, or locale is null. + */ + protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) { + mPattern = pattern; + mTimeZone = timeZone; + mLocale = locale; + + init(); + } + + /** + *

Initializes the instance for first use.

+ */ + private void init() { + final List rulesList = parsePattern(); + mRules = rulesList.toArray(new Rule[rulesList.size()]); + + int len = 0; + for (int i=mRules.length; --i >= 0; ) { + len += mRules[i].estimateLength(); + } + + mMaxLengthEstimate = len; + } + + // Parse the pattern + //----------------------------------------------------------------------- + /** + *

Returns a list of Rules given a pattern.

+ * + * @return a {@code List} of Rule objects + * @throws IllegalArgumentException if pattern is invalid + */ + protected List parsePattern() { + final DateFormatSymbols symbols = new DateFormatSymbols(mLocale); + final List rules = new ArrayList<>(); + + final String[] ERAs = symbols.getEras(); + final String[] months = symbols.getMonths(); + final String[] shortMonths = symbols.getShortMonths(); + final String[] weekdays = symbols.getWeekdays(); + final String[] shortWeekdays = symbols.getShortWeekdays(); + final String[] AmPmStrings = symbols.getAmPmStrings(); + + final int length = mPattern.length(); + final int[] indexRef = new int[1]; + + for (int i = 0; i < length; i++) { + indexRef[0] = i; + final String token = parseToken(mPattern, indexRef); + i = indexRef[0]; + + final int tokenLen = token.length(); + if (tokenLen == 0) { + break; + } + + Rule rule; + final char c = token.charAt(0); + + switch (c) { + case 'G': // era designator (text) + rule = new TextField(Calendar.ERA, ERAs); + break; + case 'y': // year (number) + case 'Y': // week year + if (tokenLen == 2) { + rule = TwoDigitYearField.INSTANCE; + } else { + rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); + } + if (c == 'Y') { + rule = new WeekYear((NumberRule) rule); + } + break; + case 'M': // month in year (text and number) + if (tokenLen >= 4) { + rule = new TextField(Calendar.MONTH, months); + } else if (tokenLen == 3) { + rule = new TextField(Calendar.MONTH, shortMonths); + } else if (tokenLen == 2) { + rule = TwoDigitMonthField.INSTANCE; + } else { + rule = UnpaddedMonthField.INSTANCE; + } + break; + case 'd': // day in month (number) + rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); + break; + case 'h': // hour in am/pm (number, 1..12) + rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); + break; + case 'H': // hour in day (number, 0..23) + rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); + break; + case 'm': // minute in hour (number) + rule = selectNumberRule(Calendar.MINUTE, tokenLen); + break; + case 's': // second in minute (number) + rule = selectNumberRule(Calendar.SECOND, tokenLen); + break; + case 'S': // millisecond (number) + rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); + break; + case 'E': // day in week (text) + rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); + break; + case 'u': // day in week (number) + rule = new DayInWeekField(selectNumberRule(Calendar.DAY_OF_WEEK, tokenLen)); + break; + case 'D': // day in year (number) + rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); + break; + case 'F': // day of week in month (number) + rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); + break; + case 'w': // week in year (number) + rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); + break; + case 'W': // week in month (number) + rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); + break; + case 'a': // am/pm marker (text) + rule = new TextField(Calendar.AM_PM, AmPmStrings); + break; + case 'k': // hour in day (1..24) + rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); + break; + case 'K': // hour in am/pm (0..11) + rule = selectNumberRule(Calendar.HOUR, tokenLen); + break; + case 'X': // ISO 8601 + rule = Iso8601_Rule.getRule(tokenLen); + break; + case 'z': // time zone (text) + if (tokenLen >= 4) { + rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); + } else { + rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); + } + break; + case 'Z': // time zone (value) + if (tokenLen == 1) { + rule = TimeZoneNumberRule.INSTANCE_NO_COLON; + } else if (tokenLen == 2) { + rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES; + } else { + rule = TimeZoneNumberRule.INSTANCE_COLON; + } + break; + case '\'': // literal text + final String sub = token.substring(1); + if (sub.length() == 1) { + rule = new CharacterLiteral(sub.charAt(0)); + } else { + rule = new StringLiteral(sub); + } + break; + default: + throw new IllegalArgumentException("Illegal pattern component: " + token); + } + + rules.add(rule); + } + + return rules; + } + + /** + *

Performs the parsing of tokens.

+ * + * @param pattern the pattern + * @param indexRef index references + * @return parsed token + */ + protected String parseToken(final String pattern, final int[] indexRef) { + final StringBuilder buf = new StringBuilder(); + + int i = indexRef[0]; + final int length = pattern.length(); + + char c = pattern.charAt(i); + if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { + // Scan a run of the same character, which indicates a time + // pattern. + buf.append(c); + + while (i + 1 < length) { + final char peek = pattern.charAt(i + 1); + if (peek == c) { + buf.append(c); + i++; + } else { + break; + } + } + } else { + // This will identify token as text. + buf.append('\''); + + boolean inLiteral = false; + + for (; i < length; i++) { + c = pattern.charAt(i); + + if (c == '\'') { + if (i + 1 < length && pattern.charAt(i + 1) == '\'') { + // '' is treated as escaped ' + i++; + buf.append(c); + } else { + inLiteral = !inLiteral; + } + } else if (!inLiteral && + (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { + i--; + break; + } else { + buf.append(c); + } + } + } + + indexRef[0] = i; + return buf.toString(); + } + + /** + *

Gets an appropriate rule for the padding required.

+ * + * @param field the field to get a rule for + * @param padding the padding required + * @return a new rule with the correct padding + */ + protected NumberRule selectNumberRule(final int field, final int padding) { + switch (padding) { + case 1: + return new UnpaddedNumberField(field); + case 2: + return new TwoDigitNumberField(field); + default: + return new PaddedNumberField(field, padding); + } + } + + // Format methods + //----------------------------------------------------------------------- + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ * @deprecated Use {{@link #format(Date)}, {{@link #format(Calendar)}, {{@link #format(long)}, or {{@link #format(Object)} + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Deprecated + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + if (obj instanceof Date) { + return format((Date) obj, toAppendTo); + } else if (obj instanceof Calendar) { + return format((Calendar) obj, toAppendTo); + } else if (obj instanceof Long) { + return format(((Long) obj).longValue(), toAppendTo); + } else { + throw new IllegalArgumentException("Unknown class: " + + (obj == null ? "" : obj.getClass().getName())); + } + } + + /** + *

Formats a {@code Date}, {@code Calendar} or + * {@code Long} (milliseconds) object.

+ * @since 3.5 + * @param obj the object to format + * @return The formatted value. + */ + String format(final Object obj) { + if (obj instanceof Date) { + return format((Date) obj); + } else if (obj instanceof Calendar) { + return format((Calendar) obj); + } else if (obj instanceof Long) { + return format(((Long) obj).longValue()); + } else { + throw new IllegalArgumentException("Unknown class: " + + (obj == null ? "" : obj.getClass().getName())); + } + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(long) + */ + @Override + public String format(final long millis) { + final Calendar c = newCalendar(); + c.setTimeInMillis(millis); + return applyRulesToString(c); + } + + /** + * Creates a String representation of the given Calendar by applying the rules of this printer to it. + * @param c the Calender to apply the rules to. + * @return a String representation of the given Calendar. + */ + private String applyRulesToString(final Calendar c) { + return applyRules(c, new StringBuilder(mMaxLengthEstimate)).toString(); + } + + /** + * Creation method for new calender instances. + * @return a new Calendar instance. + */ + private Calendar newCalendar() { + return Calendar.getInstance(mTimeZone, mLocale); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) + */ + @Override + public String format(final Date date) { + final Calendar c = newCalendar(); + c.setTime(date); + return applyRulesToString(c); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) + */ + @Override + public String format(final Calendar calendar) { + return format(calendar, new StringBuilder(mMaxLengthEstimate)).toString(); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + final Calendar c = newCalendar(); + c.setTimeInMillis(millis); + return (StringBuffer) applyRules(c, (Appendable) buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + final Calendar c = newCalendar(); + c.setTime(date); + return (StringBuffer) applyRules(c, (Appendable) buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored + return format(calendar.getTime(), buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.Appendable) + */ + @Override + public B format(final long millis, final B buf) { + final Calendar c = newCalendar(); + c.setTimeInMillis(millis); + return applyRules(c, buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.Appendable) + */ + @Override + public B format(final Date date, final B buf) { + final Calendar c = newCalendar(); + c.setTime(date); + return applyRules(c, buf); + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.Appendable) + */ + @Override + public B format(Calendar calendar, final B buf) { + // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored + if (!calendar.getTimeZone().equals(mTimeZone)) { + calendar = (Calendar) calendar.clone(); + calendar.setTimeZone(mTimeZone); + } + return applyRules(calendar, buf); + } + + /** + * Performs the formatting by applying the rules to the + * specified calendar. + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * + * @deprecated use {@link #format(Calendar)} or {@link #format(Calendar, Appendable)} + */ + @Deprecated + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + return (StringBuffer) applyRules(calendar, (Appendable) buf); + } + + /** + *

Performs the formatting by applying the rules to the + * specified calendar.

+ * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or StringBuffer. + * @return the specified string buffer + */ + private B applyRules(final Calendar calendar, final B buf) { + try { + for (final Rule rule : mRules) { + rule.appendTo(buf, calendar); + } + } catch (final IOException ioe) { + throw new RuntimeException(ioe); + } + return buf; + } + + // Accessors + //----------------------------------------------------------------------- + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getPattern() + */ + @Override + public String getPattern() { + return mPattern; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return mTimeZone; + } + + /* (non-Javadoc) + * @see org.apache.commons.lang3.time.DatePrinter#getLocale() + */ + @Override + public Locale getLocale() { + return mLocale; + } + + /** + *

Gets an estimate for the maximum string length that the + * formatter will produce.

+ * + *

The actual formatted length will almost always be less than or + * equal to this amount.

+ * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return mMaxLengthEstimate; + } + + // Basics + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality.

+ * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDatePrinter)) { + return false; + } + final FastDatePrinter other = (FastDatePrinter) obj; + return mPattern.equals(other.mPattern) + && mTimeZone.equals(other.mTimeZone) + && mLocale.equals(other.mLocale); + } + + /** + *

Returns a hash code compatible with equals.

+ * + * @return a hash code compatible with equals + */ + @Override + public int hashCode() { + return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); + } + + /** + *

Gets a debugging string version of this formatter.

+ * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; + } + + // Serializing + //----------------------------------------------------------------------- + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + init(); + } + + /** + * Appends two digits to the given buffer. + * + * @param buffer the buffer to append to. + * @param value the value to append digits from. + */ + private static void appendDigits(final Appendable buffer, final int value) throws IOException { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + + private static final int MAX_DIGITS = 10; // log10(Integer.MAX_VALUE) ~= 9.3 + + /** + * Appends all digits to the given buffer. + * + * @param buffer the buffer to append to. + * @param value the value to append digits from. + */ + private static void appendFullDigits(final Appendable buffer, int value, int minFieldWidth) throws IOException { + // specialized paths for 1 to 4 digits -> avoid the memory allocation from the temporary work array + // see LANG-1248 + if (value < 10000) { + // less memory allocation path works for four digits or less + + int nDigits = 4; + if (value < 1000) { + --nDigits; + if (value < 100) { + --nDigits; + if (value < 10) { + --nDigits; + } + } + } + // left zero pad + for (int i = minFieldWidth - nDigits; i > 0; --i) { + buffer.append('0'); + } + + switch (nDigits) { + case 4: + buffer.append((char) (value / 1000 + '0')); + value %= 1000; + case 3: + if (value >= 100) { + buffer.append((char) (value / 100 + '0')); + value %= 100; + } else { + buffer.append('0'); + } + case 2: + if (value >= 10) { + buffer.append((char) (value / 10 + '0')); + value %= 10; + } else { + buffer.append('0'); + } + case 1: + buffer.append((char) (value + '0')); + } + } else { + // more memory allocation path works for any digits + + // build up decimal representation in reverse + final char[] work = new char[MAX_DIGITS]; + int digit = 0; + while (value != 0) { + work[digit++] = (char) (value % 10 + '0'); + value = value / 10; + } + + // pad with zeros + while (digit < minFieldWidth) { + buffer.append('0'); + --minFieldWidth; + } + + // reverse + while (--digit >= 0) { + buffer.append(work[digit]); + } + } + } + + // Rules + //----------------------------------------------------------------------- + /** + *

Inner class defining a rule.

+ */ + private interface Rule { + /** + * Returns the estimated length of the result. + * + * @return the estimated length + */ + int estimateLength(); + + /** + * Appends the value of the specified calendar to the output buffer based on the rule implementation. + * + * @param buf the output buffer + * @param calendar calendar to be appended + * @throws IOException if an I/O error occurs + */ + void appendTo(Appendable buf, Calendar calendar) throws IOException; + } + + /** + *

Inner class defining a numeric rule.

+ */ + private interface NumberRule extends Rule { + /** + * Appends the specified value to the output buffer based on the rule implementation. + * + * @param buffer the output buffer + * @param value the value to be appended + * @throws IOException if an I/O error occurs + */ + void appendTo(Appendable buffer, int value) throws IOException; + } + + /** + *

Inner class to output a constant single character.

+ */ + private static class CharacterLiteral implements Rule { + private final char mValue; + + /** + * Constructs a new instance of {@code CharacterLiteral} + * to hold the specified value. + * + * @param value the character literal + */ + CharacterLiteral(final char value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 1; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + buffer.append(mValue); + } + } + + /** + *

Inner class to output a constant string.

+ */ + private static class StringLiteral implements Rule { + private final String mValue; + + /** + * Constructs a new instance of {@code StringLiteral} + * to hold the specified value. + * + * @param value the string literal + */ + StringLiteral(final String value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mValue.length(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + buffer.append(mValue); + } + } + + /** + *

Inner class to output one of a set of values.

+ */ + private static class TextField implements Rule { + private final int mField; + private final String[] mValues; + + /** + * Constructs an instance of {@code TextField} + * with the specified field and values. + * + * @param field the field + * @param values the field values + */ + TextField(final int field, final String[] values) { + mField = field; + mValues = values; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + int max = 0; + for (int i=mValues.length; --i >= 0; ) { + final int len = mValues[i].length(); + if (len > max) { + max = len; + } + } + return max; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + buffer.append(mValues[calendar.get(mField)]); + } + } + + /** + *

Inner class to output an unpadded number.

+ */ + private static class UnpaddedNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code UnpadedNumberField} with the specified field. + * + * @param field the field + */ + UnpaddedNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 4; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + if (value < 10) { + buffer.append((char) (value + '0')); + } else if (value < 100) { + appendDigits(buffer, value); + } else { + appendFullDigits(buffer, value, 1); + } + } + } + + /** + *

Inner class to output an unpadded month.

+ */ + private static class UnpaddedMonthField implements NumberRule { + static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); + + /** + * Constructs an instance of {@code UnpaddedMonthField}. + * + */ + UnpaddedMonthField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + if (value < 10) { + buffer.append((char) (value + '0')); + } else { + appendDigits(buffer, value); + } + } + } + + /** + *

Inner class to output a padded number.

+ */ + private static class PaddedNumberField implements NumberRule { + private final int mField; + private final int mSize; + + /** + * Constructs an instance of {@code PaddedNumberField}. + * + * @param field the field + * @param size size of the output field + */ + PaddedNumberField(final int field, final int size) { + if (size < 3) { + // Should use UnpaddedNumberField or TwoDigitNumberField. + throw new IllegalArgumentException(); + } + mField = field; + mSize = size; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mSize; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + appendFullDigits(buffer, value, mSize); + } + } + + /** + *

Inner class to output a two digit number.

+ */ + private static class TwoDigitNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code TwoDigitNumberField} with the specified field. + * + * @param field the field + */ + TwoDigitNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + if (value < 100) { + appendDigits(buffer, value); + } else { + appendFullDigits(buffer, value, 2); + } + } + } + + /** + *

Inner class to output a two digit year.

+ */ + private static class TwoDigitYearField implements NumberRule { + static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); + + /** + * Constructs an instance of {@code TwoDigitYearField}. + */ + TwoDigitYearField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(Calendar.YEAR) % 100); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + appendDigits(buffer, value); + } + } + + /** + *

Inner class to output a two digit month.

+ */ + private static class TwoDigitMonthField implements NumberRule { + static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); + + /** + * Constructs an instance of {@code TwoDigitMonthField}. + */ + TwoDigitMonthField() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + appendDigits(buffer, value); + } + } + + /** + *

Inner class to output the twelve hour field.

+ */ + private static class TwelveHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwelveHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwelveHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + int value = calendar.get(Calendar.HOUR); + if (value == 0) { + value = calendar.getLeastMaximum(Calendar.HOUR) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + } + + /** + *

Inner class to output the twenty four hour field.

+ */ + private static class TwentyFourHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwentyFourHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwentyFourHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + int value = calendar.get(Calendar.HOUR_OF_DAY); + if (value == 0) { + value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + } + + /** + *

Inner class to output the numeric day in week.

+ */ + private static class DayInWeekField implements NumberRule { + private final NumberRule mRule; + + DayInWeekField(final NumberRule rule) { + mRule = rule; + } + + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + final int value = calendar.get(Calendar.DAY_OF_WEEK); + mRule.appendTo(buffer, value == Calendar.SUNDAY ? 7 : value - 1); + } + + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + } + + /** + *

Inner class to output the numeric day in week.

+ */ + private static class WeekYear implements NumberRule { + private final NumberRule mRule; + + WeekYear(final NumberRule rule) { + mRule = rule; + } + + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + mRule.appendTo(buffer, calendar.getWeekYear()); + } + + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + } + + //----------------------------------------------------------------------- + + private static final ConcurrentMap cTimeZoneDisplayCache = + new ConcurrentHashMap<>(7); + /** + *

Gets the time zone display name, using a cache for performance.

+ * + * @param tz the zone to query + * @param daylight true if daylight savings + * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT} + * @param locale the locale to use + * @return the textual name of the time zone + */ + static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { + final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); + String value = cTimeZoneDisplayCache.get(key); + if (value == null) { + // This is a very slow call, so cache the results. + value = tz.getDisplayName(daylight, style, locale); + final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); + if (prior != null) { + value= prior; + } + } + return value; + } + + /** + *

Inner class to output a time zone name.

+ */ + private static class TimeZoneNameRule implements Rule { + private final Locale mLocale; + private final int mStyle; + private final String mStandard; + private final String mDaylight; + + /** + * Constructs an instance of {@code TimeZoneNameRule} with the specified properties. + * + * @param timeZone the time zone + * @param locale the locale + * @param style the style + */ + TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { + mLocale = locale; + mStyle = style; + + mStandard = getTimeZoneDisplay(timeZone, false, style, locale); + mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + // We have no access to the Calendar object that will be passed to + // appendTo so base estimate on the TimeZone passed to the + // constructor + return Math.max(mStandard.length(), mDaylight.length()); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + final TimeZone zone = calendar.getTimeZone(); + if (calendar.get(Calendar.DST_OFFSET) == 0) { + buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); + } else { + buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); + } + } + } + + /** + *

Inner class to output a time zone as a number {@code +/-HHMM} + * or {@code +/-HH:MM}.

+ */ + private static class TimeZoneNumberRule implements Rule { + static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); + static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); + + final boolean mColon; + + /** + * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties. + * + * @param colon add colon between HH and MM in the output if {@code true} + */ + TimeZoneNumberRule(final boolean colon) { + mColon = colon; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 5; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + + if (offset < 0) { + buffer.append('-'); + offset = -offset; + } else { + buffer.append('+'); + } + + final int hours = offset / (60 * 60 * 1000); + appendDigits(buffer, hours); + + if (mColon) { + buffer.append(':'); + } + + final int minutes = offset / (60 * 1000) - 60 * hours; + appendDigits(buffer, minutes); + } + } + + /** + *

Inner class to output a time zone as a number {@code +/-HHMM} + * or {@code +/-HH:MM}.

+ */ + private static class Iso8601_Rule implements Rule { + + // Sign TwoDigitHours or Z + static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); + // Sign TwoDigitHours Minutes or Z + static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); + // Sign TwoDigitHours : Minutes or Z + static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); + + /** + * Factory method for Iso8601_Rules. + * + * @param tokenLen a token indicating the length of the TimeZone String to be formatted. + * @return a Iso8601_Rule that can format TimeZone String of length {@code tokenLen}. If no such + * rule exists, an IllegalArgumentException will be thrown. + */ + static Iso8601_Rule getRule(final int tokenLen) { + switch(tokenLen) { + case 1: + return ISO8601_HOURS; + case 2: + return ISO8601_HOURS_MINUTES; + case 3: + return ISO8601_HOURS_COLON_MINUTES; + default: + throw new IllegalArgumentException("invalid number of X"); + } + } + + final int length; + + /** + * Constructs an instance of {@code Iso8601_Rule} with the specified properties. + * + * @param length The number of characters in output (unless Z is output) + */ + Iso8601_Rule(final int length) { + this.length = length; + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return length; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + if (offset == 0) { + buffer.append("Z"); + return; + } + + if (offset < 0) { + buffer.append('-'); + offset = -offset; + } else { + buffer.append('+'); + } + + final int hours = offset / (60 * 60 * 1000); + appendDigits(buffer, hours); + + if (length<5) { + return; + } + + if (length==6) { + buffer.append(':'); + } + + final int minutes = offset / (60 * 1000) - 60 * hours; + appendDigits(buffer, minutes); + } + } + + // ---------------------------------------------------------------------- + /** + *

Inner class that acts as a compound key for time zone names.

+ */ + private static class TimeZoneDisplayKey { + private final TimeZone mTimeZone; + private final int mStyle; + private final Locale mLocale; + + /** + * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. + * + * @param timeZone the time zone + * @param daylight adjust the style for daylight saving time if {@code true} + * @param style the timezone style + * @param locale the timezone locale + */ + TimeZoneDisplayKey(final TimeZone timeZone, + final boolean daylight, final int style, final Locale locale) { + mTimeZone = timeZone; + if (daylight) { + mStyle = style | 0x80000000; + } else { + mStyle = style; + } + mLocale = locale; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof TimeZoneDisplayKey) { + final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; + return + mTimeZone.equals(other.mTimeZone) && + mStyle == other.mStyle && + mLocale.equals(other.mLocale); + } + return false; + } + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java new file mode 100644 index 00000000000..9babe929048 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.time; + +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Faster methods to produce custom time zones. + * + * @since 3.7 + */ +public class FastTimeZone { + public static final String GMT_ID = "GMT"; + private static final Pattern GMT_PATTERN = Pattern.compile("^(?:(?i)GMT)?([+-])?(\\d\\d?)?(:?(\\d\\d?))?$"); + + private static final TimeZone GREENWICH = new GmtTimeZone(false, 0, 0); + + /** + * Gets the GMT TimeZone. + * + * @return A TimeZone with a raw offset of zero. + */ + public static TimeZone getGmtTimeZone() { + return GREENWICH; + } + + /** + * Gets a TimeZone with GMT offsets. A GMT offset must be either 'Z', or 'UTC', or match + * (GMT)? hh?(:?mm?)?, where h and m are digits representing hours and minutes. + * + * @param pattern The GMT offset + * @return A TimeZone with offset from GMT or null, if pattern does not match. + */ + public static TimeZone getGmtTimeZone(final String pattern) { + if ("Z".equals(pattern) || "UTC".equals(pattern)) { + return GREENWICH; + } + + final Matcher m = GMT_PATTERN.matcher(pattern); + if (m.matches()) { + final int hours = parseInt(m.group(2)); + final int minutes = parseInt(m.group(4)); + if (hours == 0 && minutes == 0) { + return GREENWICH; + } + return new GmtTimeZone(parseSign(m.group(1)), hours, minutes); + } + return null; + } + + /** + * Gets a TimeZone, looking first for GMT custom ids, then falling back to Olson ids. + * A GMT custom id can be 'Z', or 'UTC', or has an optional prefix of GMT, + * followed by sign, hours digit(s), optional colon(':'), and optional minutes digits. + * i.e. [GMT] (+|-) Hours [[:] Minutes] + * + * @param id A GMT custom id (or Olson id + * @return A timezone + */ + public static TimeZone getTimeZone(final String id) { + final TimeZone tz = getGmtTimeZone(id); + if (tz != null) { + return tz; + } + return TimeZone.getTimeZone(id); + } + + private static int parseInt(final String group) { + return group != null ? Integer.parseInt(group) : 0; + } + + private static boolean parseSign(final String group) { + return group != null && group.charAt(0) == '-'; + } + + // do not instantiate + private FastTimeZone() { + } + + +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java new file mode 100644 index 00000000000..8aa1f908f59 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java @@ -0,0 +1,211 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.common.time; + +import org.apache.dubbo.common.utils.Assert; + +import java.text.DateFormat; +import java.text.Format; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + *

FormatCache is a cache and factory for {@link Format}s.

+ */ +// TODO: Before making public move from getDateTimeInstance(Integer, ...) to int; or some other approach. +abstract class FormatCache { + + /** + * No date or no time. Used in same parameters as DateFormat.SHORT or DateFormat.LONG + */ + static final int NONE= -1; + + private final ConcurrentMap cInstanceCache + = new ConcurrentHashMap<>(7); + + private static final ConcurrentMap cDateTimeInstanceCache + = new ConcurrentHashMap<>(7); + + /** + *

Gets a formatter instance using the default pattern in the + * default timezone and locale.

+ * + * @return a date/time formatter + */ + public F getInstance() { + return getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TimeZone.getDefault(), Locale.getDefault()); + } + + /** + *

Gets a formatter instance using the specified pattern, time zone + * and locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible + * pattern, non-null + * @param timeZone the time zone, null means use the default TimeZone + * @param locale the locale, null means use the default Locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * or null + */ + public F getInstance(final String pattern, TimeZone timeZone, Locale locale) { + Assert.notNull(pattern, "Pattern must not be null"); + if (timeZone == null) { + timeZone = TimeZone.getDefault(); + } + if (locale == null) { + locale = Locale.getDefault(); + } + final MultipartKey key = new MultipartKey(pattern, timeZone, locale); + F format = cInstanceCache.get(key); + if (format == null) { + format = createInstance(pattern, timeZone, locale); + final F previousValue= cInstanceCache.putIfAbsent(key, format); + if (previousValue != null) { + // another thread snuck in and did the same work + // we should return the instance that is in ConcurrentMap + format= previousValue; + } + } + return format; + } + + /** + *

Create a format instance using the specified pattern, time zone + * and locale.

+ * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this will not be null. + * @param timeZone time zone, this will not be null. + * @param locale locale, this will not be null. + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + * or null + */ + protected abstract F createInstance(String pattern, TimeZone timeZone, Locale locale); + + /** + *

Gets a date/time formatter instance using the specified style, + * time zone and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format + * @param timeZone optional time zone, overrides time zone of + * formatted date, null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time + * pattern defined + */ + // This must remain private, see LANG-884 + private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + final String pattern = getPatternForStyle(dateStyle, timeStyle, locale); + return getInstance(pattern, timeZone, locale); + } + + + /** + *

Gets a date/time format for the specified styles and locale.

+ * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format + * @param locale The non-null locale of the desired format + * @return a localized standard date/time format + * @throws IllegalArgumentException if the Locale has no date/time pattern defined + */ + // package protected, for access from test code; do not make public or protected + static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) { + final MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale); + + String pattern = cDateTimeInstanceCache.get(key); + if (pattern == null) { + try { + DateFormat formatter; + if (dateStyle == null) { + formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale); + } else if (timeStyle == null) { + formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale); + } else { + formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale); + } + pattern = ((SimpleDateFormat) formatter).toPattern(); + final String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern); + if (previous != null) { + // even though it doesn't matter if another thread put the pattern + // it's still good practice to return the String instance that is + // actually in the ConcurrentMap + pattern= previous; + } + } catch (final ClassCastException ex) { + throw new IllegalArgumentException("No date time pattern for locale: " + locale); + } + } + return pattern; + } + + // ---------------------------------------------------------------------- + /** + *

Helper class to hold multi-part Map keys

+ */ + private static class MultipartKey { + private final Object[] keys; + private int hashCode; + + /** + * Constructs an instance of MultipartKey to hold the specified objects. + * @param keys the set of objects that make up the key. Each key may be null. + */ + MultipartKey(final Object... keys) { + this.keys = keys; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object obj) { + // Eliminate the usual boilerplate because + // this inner static class is only used in a generic ConcurrentHashMap + // which will not compare against other Object types + return Arrays.equals(keys, ((MultipartKey) obj).keys); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + if (hashCode==0) { + int rc= 0; + for (final Object key : keys) { + if (key!=null) { + rc= rc*7 + key.hashCode(); + } + } + hashCode= rc; + } + return hashCode; + } + } + +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java new file mode 100644 index 00000000000..da0ba8b4afa --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.dubbo.common.time; + +import java.util.Date; +import java.util.TimeZone; + +/** + * Custom timezone that contains offset from GMT. + */ +class GmtTimeZone extends TimeZone { + + private static final int MILLISECONDS_PER_MINUTE = 60 * 1000; + private static final int MINUTES_PER_HOUR = 60; + private static final int HOURS_PER_DAY = 24; + + // Serializable! + static final long serialVersionUID = 1L; + + private final int offset; + private final String zoneId; + + GmtTimeZone(final boolean negate, final int hours, final int minutes) { + if (hours >= HOURS_PER_DAY) { + throw new IllegalArgumentException(hours + " hours out of range"); + } + if (minutes >= MINUTES_PER_HOUR) { + throw new IllegalArgumentException(minutes + " minutes out of range"); + } + final int milliseconds = (minutes + (hours * MINUTES_PER_HOUR)) * MILLISECONDS_PER_MINUTE; + offset = negate ? -milliseconds : milliseconds; + zoneId = twoDigits( + twoDigits(new StringBuilder(9).append("GMT").append(negate ? '-' : '+'), hours) + .append(':'), minutes).toString(); + + } + + private static StringBuilder twoDigits(final StringBuilder sb, final int n) { + return sb.append((char) ('0' + (n / 10))).append((char) ('0' + (n % 10))); + } + + @Override + public int getOffset(final int era, final int year, final int month, final int day, final int dayOfWeek, final int milliseconds) { + return offset; + } + + @Override + public void setRawOffset(final int offsetMillis) { + throw new UnsupportedOperationException(); + } + + @Override + public int getRawOffset() { + return offset; + } + + @Override + public String getID() { + return zoneId; + } + + @Override + public boolean useDaylightTime() { + return false; + } + + @Override + public boolean inDaylightTime(final Date date) { + return false; + } + + @Override + public String toString() { + return "[GmtTimeZone id=\"" + zoneId + "\",offset=" + offset + ']'; + } + + @Override + public int hashCode() { + return offset; + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof GmtTimeZone)) { + return false; + } + return zoneId == ((GmtTimeZone) other).zoneId; + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java index 97fe5751d4d..613ac843566 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.common.utils; -import org.apache.commons.lang3.time.FastDateFormat; +import org.apache.dubbo.common.time.FastDateFormat; import java.util.Date; From 896066d583fb23af75b0be6bc1f27060d6b8c483 Mon Sep 17 00:00:00 2001 From: Imteyaz Khan Date: Tue, 22 Jan 2019 12:13:01 +0530 Subject: [PATCH 4/5] Added rat entry for common lang3 FastDateFormat related java files --- pom.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pom.xml b/pom.xml index 3b7f89e3ad6..a6c351ff6d2 100644 --- a/pom.xml +++ b/pom.xml @@ -493,6 +493,15 @@ **/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java **/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java + + **/org/apache/dubbo/common/time/DateParser.java + **/org/apache/dubbo/common/time/DatePrinter.java + **/org/apache/dubbo/common/time/FastDateFormat.java + **/org/apache/dubbo/common/time/FastDateParser.java + **/org/apache/dubbo/common/time/FastDatePrinter.java + **/org/apache/dubbo/common/time/FastTimeZone.java + **/org/apache/dubbo/common/time/FormatCache.java + **/org/apache/dubbo/common/time/GmtTimeZone.java From 52b33534faae43a79872da15039abb14495a73cf Mon Sep 17 00:00:00 2001 From: Ian Luo Date: Thu, 31 Jan 2019 17:04:53 +0800 Subject: [PATCH 5/5] switch back to jdk's dateformatter --- LICENSE | 12 - .../apache/dubbo/common/time/DateParser.java | 120 -- .../apache/dubbo/common/time/DatePrinter.java | 171 -- .../dubbo/common/time/FastDateFormat.java | 380 ----- .../dubbo/common/time/FastDateParser.java | 954 ----------- .../dubbo/common/time/FastDatePrinter.java | 1514 ----------------- .../dubbo/common/time/FastTimeZone.java | 97 -- .../apache/dubbo/common/time/FormatCache.java | 211 --- .../apache/dubbo/common/time/GmtTimeZone.java | 104 -- .../apache/dubbo/common/utils/DateUtil.java | 43 - .../dubbo/rpc/filter/AccessLogFilter.java | 13 +- .../dubbo/rpc/support/AccessLogData.java | 16 +- pom.xml | 9 - 13 files changed, 18 insertions(+), 3626 deletions(-) delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java delete mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java diff --git a/LICENSE b/LICENSE index 67f34d42b82..a35e3b94fe0 100644 --- a/LICENSE +++ b/LICENSE @@ -220,15 +220,3 @@ This product contains a modified portion of 'Netty', an event-driven asynchronou * io.netty.util.Timeout * io.netty.util.HashedWheelTimer - This product contains modified portion of common-lang3 org.apache.commons.lang3.time package java file, an thread safe date format utility, which - is under a "Apache License 2.0" license, see https://github.com/apache/commons-lang/blob/master/LICENSE.txt - - * org.apache.commons.lang3.time.DateParser - * org.apache.commons.lang3.time.DatePrinter - * org.apache.commons.lang3.time.FastDateFormat - * org.apache.commons.lang3.FastDateParser - * org.apache.commons.lang3.FastDatePrinter - * org.apache.commons.lang3.FastTimeZone - * org.apache.commons.lang3.FormatCache - * org.apache.commons.lang3.GmtTimeZone - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java deleted file mode 100644 index 36b6b0c2c39..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/DateParser.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.time; - -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -/** - * DateParser interface - */ -public interface DateParser { - - /** - * Equivalent to DateFormat.parse(String). - * - * See {@link java.text.DateFormat#parse(String)} for more information. - * @param source A String whose beginning should be parsed. - * @return A Date parsed from the string - * @throws ParseException if the beginning of the specified string cannot be parsed. - */ - Date parse(String source) throws ParseException; - - /** - * Equivalent to DateFormat.parse(String, ParsePosition). - * - * See {@link java.text.DateFormat#parse(String, ParsePosition)} for more information. - * - * @param source A String, part of which should be parsed. - * @param pos A ParsePosition object with index and error index information - * as described above. - * @return A Date parsed from the string. In case of error, returns null. - * @throws NullPointerException if text or pos is null. - */ - Date parse(String source, ParsePosition pos); - - /** - * Parses a formatted date string according to the format. Updates the Calendar with parsed fields. - * Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. - * Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to - * the offset of the source text which does not match the supplied format. - * - * @param source The text to parse. - * @param pos On input, the position in the source to start parsing, on output, updated position. - * @param calendar The calendar into which to set parsed fields. - * @return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated) - * @throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is - * out of range. - * - * @since 3.5 - */ - boolean parse(String source, ParsePosition pos, Calendar calendar); - - // Accessors - //----------------------------------------------------------------------- - /** - *

Gets the pattern used by this parser.

- * - * @return the pattern, {@link java.text.SimpleDateFormat} compatible - */ - String getPattern(); - - /** - *

- * Gets the time zone used by this parser. - *

- * - *

- * The default {@link TimeZone} used to create a {@link Date} when the {@link TimeZone} is not specified by - * the format pattern. - *

- * - * @return the time zone - */ - TimeZone getTimeZone(); - - /** - *

Gets the locale used by this parser.

- * - * @return the locale - */ - Locale getLocale(); - - /** - * Parses text from a string to produce a Date. - * - * @param source A String whose beginning should be parsed. - * @return a java.util.Date object - * @throws ParseException if the beginning of the specified string cannot be parsed. - * @see java.text.DateFormat#parseObject(String) - */ - Object parseObject(String source) throws ParseException; - - /** - * Parses a date/time string according to the given parse position. - * - * @param source A String whose beginning should be parsed. - * @param pos the parse position - * @return a java.util.Date object - * @see java.text.DateFormat#parseObject(String, ParsePosition) - */ - Object parseObject(String source, ParsePosition pos); -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java deleted file mode 100644 index 8b3b5e4645c..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/DatePrinter.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.time; - -import java.text.FieldPosition; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -/** - * DatePrinter interface - */ -public interface DatePrinter { - - /** - *

Formats a millisecond {@code long} value.

- * - * @param millis the millisecond value to format - * @return the formatted string - * @since 2.1 - */ - String format(long millis); - - /** - *

Formats a {@code Date} object using a {@code GregorianCalendar}.

- * - * @param date the date to format - * @return the formatted string - */ - String format(Date date); - - /** - *

Formats a {@code Calendar} object.

- * The TimeZone set on the Calendar is only used to adjust the time offset. - * The TimeZone specified during the construction of the Parser will determine the TimeZone - * used in the formatted string. - * - * @param calendar the calendar to format. - * @return the formatted string - */ - String format(Calendar calendar); - - /** - *

Formats a millisecond {@code long} value into the - * supplied {@code StringBuffer}.

- * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(long, Appendable)}. - */ - @Deprecated - StringBuffer format(long millis, StringBuffer buf); - - /** - *

Formats a {@code Date} object into the - * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

- * - * @param date the date to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Date, Appendable)}. - */ - @Deprecated - StringBuffer format(Date date, StringBuffer buf); - - /** - *

Formats a {@code Calendar} object into the supplied {@code StringBuffer}.

- * The TimeZone set on the Calendar is only used to adjust the time offset. - * The TimeZone specified during the construction of the Parser will determine the TimeZone - * used in the formatted string. - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Calendar, Appendable)}. - */ - @Deprecated - StringBuffer format(Calendar calendar, StringBuffer buf); - - /** - *

Formats a millisecond {@code long} value into the - * supplied {@code Appendable}.

- * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or StringBuffer. - * @return the specified string buffer - * @since 3.5 - */ - B format(long millis, B buf); - - /** - *

Formats a {@code Date} object into the - * supplied {@code Appendable} using a {@code GregorianCalendar}.

- * - * @param date the date to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or StringBuffer. - * @return the specified string buffer - * @since 3.5 - */ - B format(Date date, B buf); - - /** - *

Formats a {@code Calendar} object into the supplied {@code Appendable}.

- * The TimeZone set on the Calendar is only used to adjust the time offset. - * The TimeZone specified during the construction of the Parser will determine the TimeZone - * used in the formatted string. - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or StringBuffer. - * @return the specified string buffer - * @since 3.5 - */ - B format(Calendar calendar, B buf); - - - // Accessors - //----------------------------------------------------------------------- - /** - *

Gets the pattern used by this printer.

- * - * @return the pattern, {@link java.text.SimpleDateFormat} compatible - */ - String getPattern(); - - /** - *

Gets the time zone used by this printer.

- * - *

This zone is always used for {@code Date} printing.

- * - * @return the time zone - */ - TimeZone getTimeZone(); - - /** - *

Gets the locale used by this printer.

- * - * @return the locale - */ - Locale getLocale(); - - /** - *

Formats a {@code Date}, {@code Calendar} or - * {@code Long} (milliseconds) object.

- * - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - * @see java.text.DateFormat#format(Object, StringBuffer, FieldPosition) - */ - StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java deleted file mode 100644 index 99b492d9c49..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateFormat.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.common.time; - -import java.text.FieldPosition; -import java.text.Format; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -/** - * FastDateFormat - */ -public class FastDateFormat extends Format implements DateParser, DatePrinter { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 2L; - - private static final FormatCache cache= new FormatCache() { - @Override - protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) { - return new FastDateFormat(pattern, timeZone, locale); - } - }; - - private final FastDatePrinter printer; - private final FastDateParser parser; - - //----------------------------------------------------------------------- - /** - *

Gets a formatter instance using the default pattern in the - * default locale.

- * - * @return a date/time formatter - */ - public static FastDateFormat getInstance() { - return cache.getInstance(); - } - - /** - *

Gets a formatter instance using the specified pattern in the - * default locale.

- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(final String pattern) { - return cache.getInstance(pattern, null, null); - } - - - // Constructor - //----------------------------------------------------------------------- - /** - *

Constructs a new FastDateFormat.

- * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale to use - * @throws NullPointerException if pattern, timeZone, or locale is null. - */ - protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale) { - this(pattern, timeZone, locale, null); - } - - // Constructor - //----------------------------------------------------------------------- - /** - *

Constructs a new FastDateFormat.

- * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale to use - * @param centuryStart The start of the 100 year period to use as the "default century" for 2 digit year parsing. If centuryStart is null, defaults to now - 80 years - * @throws NullPointerException if pattern, timeZone, or locale is null. - */ - protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { - printer= new FastDatePrinter(pattern, timeZone, locale); - parser= new FastDateParser(pattern, timeZone, locale, centuryStart); - } - - // Format methods - //----------------------------------------------------------------------- - /** - *

Formats a {@code Date}, {@code Calendar} or - * {@code Long} (milliseconds) object.

- * This method is an implementation of {@link Format#format(Object, StringBuffer, FieldPosition)} - * - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - */ - @Override - public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { - return toAppendTo.append(printer.format(obj)); - } - - /** - *

Formats a millisecond {@code long} value.

- * - * @param millis the millisecond value to format - * @return the formatted string - * @since 2.1 - */ - @Override - public String format(final long millis) { - return printer.format(millis); - } - - /** - *

Formats a {@code Date} object using a {@code GregorianCalendar}.

- * - * @param date the date to format - * @return the formatted string - */ - @Override - public String format(final Date date) { - return printer.format(date); - } - - /** - *

Formats a {@code Calendar} object.

- * - * @param calendar the calendar to format - * @return the formatted string - */ - @Override - public String format(final Calendar calendar) { - return printer.format(calendar); - } - - /** - *

Formats a millisecond {@code long} value into the - * supplied {@code StringBuffer}.

- * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 2.1 - * @deprecated Use {{@link #format(long, Appendable)}. - */ - @Deprecated - @Override - public StringBuffer format(final long millis, final StringBuffer buf) { - return printer.format(millis, buf); - } - - /** - *

Formats a {@code Date} object into the - * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

- * - * @param date the date to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Date, Appendable)}. - */ - @Deprecated - @Override - public StringBuffer format(final Date date, final StringBuffer buf) { - return printer.format(date, buf); - } - - /** - *

Formats a {@code Calendar} object into the - * supplied {@code StringBuffer}.

- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Calendar, Appendable)}. - */ - @Deprecated - @Override - public StringBuffer format(final Calendar calendar, final StringBuffer buf) { - return printer.format(calendar, buf); - } - - /** - *

Formats a millisecond {@code long} value into the - * supplied {@code StringBuffer}.

- * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 3.5 - */ - @Override - public B format(final long millis, final B buf) { - return printer.format(millis, buf); - } - - /** - *

Formats a {@code Date} object into the - * supplied {@code StringBuffer} using a {@code GregorianCalendar}.

- * - * @param date the date to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 3.5 - */ - @Override - public B format(final Date date, final B buf) { - return printer.format(date, buf); - } - - /** - *

Formats a {@code Calendar} object into the - * supplied {@code StringBuffer}.

- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 3.5 - */ - @Override - public B format(final Calendar calendar, final B buf) { - return printer.format(calendar, buf); - } - - // Parsing - //----------------------------------------------------------------------- - - - /* (non-Javadoc) - * @see DateParser#parse(java.lang.String) - */ - @Override - public Date parse(final String source) throws ParseException { - return parser.parse(source); - } - - /* (non-Javadoc) - * @see DateParser#parse(java.lang.String, java.text.ParsePosition) - */ - @Override - public Date parse(final String source, final ParsePosition pos) { - return parser.parse(source, pos); - } - - /* - * (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition, java.util.Calendar) - */ - @Override - public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { - return parser.parse(source, pos, calendar); - } - - /* (non-Javadoc) - * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) - */ - @Override - public Object parseObject(final String source, final ParsePosition pos) { - return parser.parseObject(source, pos); - } - - // Accessors - //----------------------------------------------------------------------- - /** - *

Gets the pattern used by this formatter.

- * - * @return the pattern, {@link java.text.SimpleDateFormat} compatible - */ - @Override - public String getPattern() { - return printer.getPattern(); - } - - /** - *

Gets the time zone used by this formatter.

- * - *

This zone is always used for {@code Date} formatting.

- * - * @return the time zone - */ - @Override - public TimeZone getTimeZone() { - return printer.getTimeZone(); - } - - /** - *

Gets the locale used by this formatter.

- * - * @return the locale - */ - @Override - public Locale getLocale() { - return printer.getLocale(); - } - - /** - *

Gets an estimate for the maximum string length that the - * formatter will produce.

- * - *

The actual formatted length will almost always be less than or - * equal to this amount.

- * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return printer.getMaxLengthEstimate(); - } - - // Basics - //----------------------------------------------------------------------- - /** - *

Compares two objects for equality.

- * - * @param obj the object to compare to - * @return {@code true} if equal - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof FastDateFormat)) { - return false; - } - final FastDateFormat other = (FastDateFormat) obj; - // no need to check parser, as it has same invariants as printer - return printer.equals(other.printer); - } - - /** - *

Returns a hash code compatible with equals.

- * - * @return a hash code compatible with equals - */ - @Override - public int hashCode() { - return printer.hashCode(); - } - - /** - *

Gets a debugging string version of this formatter.

- * - * @return a debugging string - */ - @Override - public String toString() { - return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; - } - - /** - *

Performs the formatting by applying the rules to the - * specified calendar.

- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {@link #format(Calendar, Appendable)} - */ - @Deprecated - protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { - return printer.applyRules(calendar, buf); - } -} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java deleted file mode 100644 index 62a64f8d8b4..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDateParser.java +++ /dev/null @@ -1,954 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.time; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.text.DateFormatSymbols; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - *

FastDateParser is a fast and thread-safe version of SimpleDateFormat - */ -public class FastDateParser implements DateParser, Serializable { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 3L; - - static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP"); - - // defining fields - private final String pattern; - private final TimeZone timeZone; - private final Locale locale; - private final int century; - private final int startYear; - - // derived fields - private transient List patterns; - - // comparator used to sort regex alternatives - // alternatives should be ordered longer first, and shorter last. ('february' before 'feb') - // all entries must be lowercase by locale. - private static final Comparator LONGER_FIRST_LOWERCASE = new Comparator() { - @Override - public int compare(final String left, final String right) { - return right.compareTo(left); - } - }; - - /** - *

Constructs a new FastDateParser.

- * - * @param pattern non-null {@link java.text.SimpleDateFormat} compatible - * pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale - * @param centuryStart The start of the century for 2 digit year parsing - * - * @since 3.5 - */ - protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) { - this.pattern = pattern; - this.timeZone = timeZone; - this.locale = locale; - - final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); - - int centuryStartYear; - if (centuryStart!=null) { - definingCalendar.setTime(centuryStart); - centuryStartYear= definingCalendar.get(Calendar.YEAR); - } else if (locale.equals(JAPANESE_IMPERIAL)) { - centuryStartYear= 0; - } else { - // from 80 years ago to 20 years from now - definingCalendar.setTime(new Date()); - centuryStartYear= definingCalendar.get(Calendar.YEAR)-80; - } - century= centuryStartYear / 100 * 100; - startYear= centuryStartYear - century; - - init(definingCalendar); - } - - /** - * Initialize derived fields from defining fields. - * This is called from constructor and from readObject (de-serialization) - * - * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser - */ - private void init(final Calendar definingCalendar) { - patterns = new ArrayList<>(); - - final StrategyParser fm = new StrategyParser(definingCalendar); - for (;;) { - final StrategyAndWidth field = fm.getNextStrategy(); - if (field==null) { - break; - } - patterns.add(field); - } - } - - // helper classes to parse the format string - //----------------------------------------------------------------------- - - /** - * Holds strategy and field width - */ - private static class StrategyAndWidth { - final Strategy strategy; - final int width; - - StrategyAndWidth(final Strategy strategy, final int width) { - this.strategy = strategy; - this.width = width; - } - - int getMaxWidth(final ListIterator lt) { - if (!strategy.isNumber() || !lt.hasNext()) { - return 0; - } - final Strategy nextStrategy = lt.next().strategy; - lt.previous(); - return nextStrategy.isNumber() ?width :0; - } - } - - /** - * Parse format into Strategies - */ - private class StrategyParser { - private final Calendar definingCalendar; - private int currentIdx; - - StrategyParser(final Calendar definingCalendar) { - this.definingCalendar = definingCalendar; - } - - StrategyAndWidth getNextStrategy() { - if (currentIdx >= pattern.length()) { - return null; - } - - final char c = pattern.charAt(currentIdx); - if (isFormatLetter(c)) { - return letterPattern(c); - } - return literal(); - } - - private StrategyAndWidth letterPattern(final char c) { - final int begin = currentIdx; - while (++currentIdx < pattern.length()) { - if (pattern.charAt(currentIdx) != c) { - break; - } - } - - final int width = currentIdx - begin; - return new StrategyAndWidth(getStrategy(c, width, definingCalendar), width); - } - - private StrategyAndWidth literal() { - boolean activeQuote = false; - - final StringBuilder sb = new StringBuilder(); - while (currentIdx < pattern.length()) { - final char c = pattern.charAt(currentIdx); - if (!activeQuote && isFormatLetter(c)) { - break; - } else if (c == '\'' && (++currentIdx == pattern.length() || pattern.charAt(currentIdx) != '\'')) { - activeQuote = !activeQuote; - continue; - } - ++currentIdx; - sb.append(c); - } - - if (activeQuote) { - throw new IllegalArgumentException("Unterminated quote"); - } - - final String formatField = sb.toString(); - return new StrategyAndWidth(new CopyQuotedStrategy(formatField), formatField.length()); - } - } - - private static boolean isFormatLetter(final char c) { - return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; - } - - // Accessors - //----------------------------------------------------------------------- - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#getPattern() - */ - @Override - public String getPattern() { - return pattern; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#getTimeZone() - */ - @Override - public TimeZone getTimeZone() { - return timeZone; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#getLocale() - */ - @Override - public Locale getLocale() { - return locale; - } - - - // Basics - //----------------------------------------------------------------------- - /** - *

Compare another object for equality with this object.

- * - * @param obj the object to compare to - * @return trueif equal to this instance - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof FastDateParser)) { - return false; - } - final FastDateParser other = (FastDateParser) obj; - return pattern.equals(other.pattern) - && timeZone.equals(other.timeZone) - && locale.equals(other.locale); - } - - /** - *

Return a hash code compatible with equals.

- * - * @return a hash code compatible with equals - */ - @Override - public int hashCode() { - return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); - } - - /** - *

Get a string version of this formatter.

- * - * @return a debugging string - */ - @Override - public String toString() { - return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]"; - } - - // Serializing - //----------------------------------------------------------------------- - /** - * Create the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - - final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); - init(definingCalendar); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String) - */ - @Override - public Object parseObject(final String source) throws ParseException { - return parse(source); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String) - */ - @Override - public Date parse(final String source) throws ParseException { - final ParsePosition pp = new ParsePosition(0); - final Date date= parse(source, pp); - if (date == null) { - // Add a note re supported date range - if (locale.equals(JAPANESE_IMPERIAL)) { - throw new ParseException( - "(The " +locale + " locale does not support dates before 1868 AD)\n" + - "Unparseable date: \""+source, pp.getErrorIndex()); - } - throw new ParseException("Unparseable date: "+source, pp.getErrorIndex()); - } - return date; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition) - */ - @Override - public Object parseObject(final String source, final ParsePosition pos) { - return parse(source, pos); - } - - /** - * This implementation updates the ParsePosition if the parse succeeds. - * However, it sets the error index to the position before the failed field unlike - * the method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)} which sets - * the error index to after the failed field. - *

- * To determine if the parse has succeeded, the caller must check if the current parse position - * given by {@link ParsePosition#getIndex()} has been updated. If the input buffer has been fully - * parsed, then the index will point to just after the end of the input buffer. - */ - @Override - public Date parse(final String source, final ParsePosition pos) { - // timing tests indicate getting new instance is 19% faster than cloning - final Calendar cal= Calendar.getInstance(timeZone, locale); - cal.clear(); - - return parse(source, pos, cal) ? cal.getTime() : null; - } - - /** - * Parse a formatted date string according to the format. Updates the Calendar with parsed fields. - * Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. - * Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to - * the offset of the source text which does not match the supplied format. - * - * @param source The text to parse. - * @param pos On input, the position in the source to start parsing, on output, updated position. - * @param calendar The calendar into which to set parsed fields. - * @return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated) - * @throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is - * out of range. - */ - @Override - public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { - final ListIterator lt = patterns.listIterator(); - while (lt.hasNext()) { - final StrategyAndWidth strategyAndWidth = lt.next(); - final int maxWidth = strategyAndWidth.getMaxWidth(lt); - if (!strategyAndWidth.strategy.parse(this, calendar, source, pos, maxWidth)) { - return false; - } - } - return true; - } - - // Support for strategies - //----------------------------------------------------------------------- - - private static StringBuilder simpleQuote(final StringBuilder sb, final String value) { - for (int i = 0; i < value.length(); ++i) { - final char c = value.charAt(i); - switch (c) { - case '\\': - case '^': - case '$': - case '.': - case '|': - case '?': - case '*': - case '+': - case '(': - case ')': - case '[': - case '{': - sb.append('\\'); - default: - sb.append(c); - } - } - if (sb.charAt(sb.length() - 1) == '.') { - // trailing '.' is optional - sb.append('?'); - } - return sb; - } - - /** - * Get the short and long values displayed for a field - * @param cal The calendar to obtain the short and long values - * @param locale The locale of display names - * @param field The field of interest - * @param regex The regular expression to build - * @return The map of string display names to field values - */ - private static Map appendDisplayNames(final Calendar cal, final Locale locale, final int field, final StringBuilder regex) { - final Map values = new HashMap<>(); - - final Map displayNames = cal.getDisplayNames(field, Calendar.ALL_STYLES, locale); - final TreeSet sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); - for (final Map.Entry displayName : displayNames.entrySet()) { - final String key = displayName.getKey().toLowerCase(locale); - if (sorted.add(key)) { - values.put(key, displayName.getValue()); - } - } - for (final String symbol : sorted) { - simpleQuote(regex, symbol).append('|'); - } - return values; - } - - /** - * Adjust dates to be within appropriate century - * @param twoDigitYear The year to adjust - * @return A value between centuryStart(inclusive) to centuryStart+100(exclusive) - */ - private int adjustYear(final int twoDigitYear) { - final int trial = century + twoDigitYear; - return twoDigitYear >= startYear ? trial : trial + 100; - } - - /** - * A strategy to parse a single field from the parsing pattern - */ - private abstract static class Strategy { - /** - * Is this field a number? - * The default implementation returns false. - * - * @return true, if field is a number - */ - boolean isNumber() { - return false; - } - - abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos, int maxWidth); - } - - /** - * A strategy to parse a single field from the parsing pattern - */ - private abstract static class PatternStrategy extends Strategy { - - private Pattern pattern; - - void createPattern(final StringBuilder regex) { - createPattern(regex.toString()); - } - - void createPattern(final String regex) { - this.pattern = Pattern.compile(regex); - } - - /** - * Is this field a number? - * The default implementation returns false. - * - * @return true, if field is a number - */ - @Override - boolean isNumber() { - return false; - } - - @Override - boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) { - final Matcher matcher = pattern.matcher(source.substring(pos.getIndex())); - if (!matcher.lookingAt()) { - pos.setErrorIndex(pos.getIndex()); - return false; - } - pos.setIndex(pos.getIndex() + matcher.end(1)); - setCalendar(parser, calendar, matcher.group(1)); - return true; - } - - abstract void setCalendar(FastDateParser parser, Calendar cal, String value); - } - - /** - * Obtain a Strategy given a field from a SimpleDateFormat pattern - * @param f A sub-sequence of the SimpleDateFormat pattern - * @param definingCalendar The calendar to obtain the short and long values - * @return The Strategy that will handle parsing for the field - */ - private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) { - switch(f) { - default: - throw new IllegalArgumentException("Format '"+f+"' not supported"); - case 'D': - return DAY_OF_YEAR_STRATEGY; - case 'E': - return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); - case 'F': - return DAY_OF_WEEK_IN_MONTH_STRATEGY; - case 'G': - return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); - case 'H': // Hour in day (0-23) - return HOUR_OF_DAY_STRATEGY; - case 'K': // Hour in am/pm (0-11) - return HOUR_STRATEGY; - case 'M': - return width>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY; - case 'S': - return MILLISECOND_STRATEGY; - case 'W': - return WEEK_OF_MONTH_STRATEGY; - case 'a': - return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); - case 'd': - return DAY_OF_MONTH_STRATEGY; - case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 - return HOUR12_STRATEGY; - case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0 - return HOUR24_OF_DAY_STRATEGY; - case 'm': - return MINUTE_STRATEGY; - case 's': - return SECOND_STRATEGY; - case 'u': - return DAY_OF_WEEK_STRATEGY; - case 'w': - return WEEK_OF_YEAR_STRATEGY; - case 'y': - case 'Y': - return width>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY; - case 'X': - return ISO8601TimeZoneStrategy.getStrategy(width); - case 'Z': - if (width==2) { - return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY; - } - //$FALL-THROUGH$ - case 'z': - return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); - } - } - - @SuppressWarnings("unchecked") // OK because we are creating an array with no entries - private static final ConcurrentMap[] caches = new ConcurrentMap[Calendar.FIELD_COUNT]; - - /** - * Get a cache of Strategies for a particular field - * @param field The Calendar field - * @return a cache of Locale to Strategy - */ - private static ConcurrentMap getCache(final int field) { - synchronized (caches) { - if (caches[field] == null) { - caches[field] = new ConcurrentHashMap<>(3); - } - return caches[field]; - } - } - - /** - * Construct a Strategy that parses a Text field - * @param field The Calendar field - * @param definingCalendar The calendar to obtain the short and long values - * @return a TextStrategy for the field and Locale - */ - private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) { - final ConcurrentMap cache = getCache(field); - Strategy strategy = cache.get(locale); - if (strategy == null) { - strategy = field == Calendar.ZONE_OFFSET - ? new TimeZoneStrategy(locale) - : new CaseInsensitiveTextStrategy(field, definingCalendar, locale); - final Strategy inCache = cache.putIfAbsent(locale, strategy); - if (inCache != null) { - return inCache; - } - } - return strategy; - } - - /** - * A strategy that copies the static or quoted field in the parsing pattern - */ - private static class CopyQuotedStrategy extends Strategy { - - private final String formatField; - - /** - * Construct a Strategy that ensures the formatField has literal text - * @param formatField The literal text to match - */ - CopyQuotedStrategy(final String formatField) { - this.formatField = formatField; - } - - /** - * {@inheritDoc} - */ - @Override - boolean isNumber() { - return false; - } - - @Override - boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) { - for (int idx = 0; idx < formatField.length(); ++idx) { - final int sIdx = idx + pos.getIndex(); - if (sIdx == source.length()) { - pos.setErrorIndex(sIdx); - return false; - } - if (formatField.charAt(idx) != source.charAt(sIdx)) { - pos.setErrorIndex(sIdx); - return false; - } - } - pos.setIndex(formatField.length() + pos.getIndex()); - return true; - } - } - - /** - * A strategy that handles a text field in the parsing pattern - */ - private static class CaseInsensitiveTextStrategy extends PatternStrategy { - private final int field; - final Locale locale; - private final Map lKeyValues; - - /** - * Construct a Strategy that parses a Text field - * @param field The Calendar field - * @param definingCalendar The Calendar to use - * @param locale The Locale to use - */ - CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) { - this.field = field; - this.locale = locale; - - final StringBuilder regex = new StringBuilder(); - regex.append("((?iu)"); - lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex); - regex.setLength(regex.length()-1); - regex.append(")"); - createPattern(regex); - } - - /** - * {@inheritDoc} - */ - @Override - void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { - final String lowerCase = value.toLowerCase(locale); - Integer iVal = lKeyValues.get(lowerCase); - if (iVal == null) { - // match missing the optional trailing period - iVal = lKeyValues.get(lowerCase + '.'); - } - cal.set(field, iVal.intValue()); - } - } - - - /** - * A strategy that handles a number field in the parsing pattern - */ - private static class NumberStrategy extends Strategy { - private final int field; - - /** - * Construct a Strategy that parses a Number field - * @param field The Calendar field - */ - NumberStrategy(final int field) { - this.field= field; - } - - /** - * {@inheritDoc} - */ - @Override - boolean isNumber() { - return true; - } - - @Override - boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) { - int idx = pos.getIndex(); - int last = source.length(); - - if (maxWidth == 0) { - // if no maxWidth, strip leading white space - for (; idx < last; ++idx) { - final char c = source.charAt(idx); - if (!Character.isWhitespace(c)) { - break; - } - } - pos.setIndex(idx); - } else { - final int end = idx + maxWidth; - if (last > end) { - last = end; - } - } - - for (; idx < last; ++idx) { - final char c = source.charAt(idx); - if (!Character.isDigit(c)) { - break; - } - } - - if (pos.getIndex() == idx) { - pos.setErrorIndex(idx); - return false; - } - - final int value = Integer.parseInt(source.substring(pos.getIndex(), idx)); - pos.setIndex(idx); - - calendar.set(field, modify(parser, value)); - return true; - } - - /** - * Make any modifications to parsed integer - * @param parser The parser - * @param iValue The parsed integer - * @return The modified value - */ - int modify(final FastDateParser parser, final int iValue) { - return iValue; - } - - } - - private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) { - /** - * {@inheritDoc} - */ - @Override - int modify(final FastDateParser parser, final int iValue) { - return iValue < 100 ? parser.adjustYear(iValue) : iValue; - } - }; - - /** - * A strategy that handles a timezone field in the parsing pattern - */ - static class TimeZoneStrategy extends PatternStrategy { - private static final String RFC_822_TIME_ZONE = "[+-]\\d{4}"; - private static final String GMT_OPTION = FastTimeZone.GMT_ID + "[+-]\\d{1,2}:\\d{2}"; - - private final Locale locale; - private final Map tzNames= new HashMap<>(); - - private static class TzInfo { - TimeZone zone; - int dstOffset; - - TzInfo(final TimeZone tz, final boolean useDst) { - zone = tz; - dstOffset = useDst ?tz.getDSTSavings() :0; - } - } - - /** - * Index of zone id - */ - private static final int ID = 0; - - /** - * Construct a Strategy that parses a TimeZone - * @param locale The Locale - */ - TimeZoneStrategy(final Locale locale) { - this.locale = locale; - - final StringBuilder sb = new StringBuilder(); - sb.append("((?iu)" + RFC_822_TIME_ZONE + "|" + GMT_OPTION ); - - final Set sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); - - final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings(); - for (final String[] zoneNames : zones) { - // offset 0 is the time zone ID and is not localized - final String tzId = zoneNames[ID]; - if (tzId.equalsIgnoreCase(FastTimeZone.GMT_ID)) { - continue; - } - final TimeZone tz = TimeZone.getTimeZone(tzId); - // offset 1 is long standard name - // offset 2 is short standard name - final TzInfo standard = new TzInfo(tz, false); - TzInfo tzInfo = standard; - for (int i = 1; i < zoneNames.length; ++i) { - switch (i) { - case 3: // offset 3 is long daylight savings (or summertime) name - // offset 4 is the short summertime name - tzInfo = new TzInfo(tz, true); - break; - case 5: // offset 5 starts additional names, probably standard time - tzInfo = standard; - break; - default: - break; - } - if (zoneNames[i] != null) { - final String key = zoneNames[i].toLowerCase(locale); - // ignore the data associated with duplicates supplied in - // the additional names - if (sorted.add(key)) { - tzNames.put(key, tzInfo); - } - } - } - } - // order the regex alternatives with longer strings first, greedy - // match will ensure longest string will be consumed - for (final String zoneName : sorted) { - simpleQuote(sb.append('|'), zoneName); - } - sb.append(")"); - createPattern(sb); - } - - /** - * {@inheritDoc} - */ - @Override - void setCalendar(final FastDateParser parser, final Calendar cal, final String timeZone) { - final TimeZone tz = FastTimeZone.getGmtTimeZone(timeZone); - if (tz != null) { - cal.setTimeZone(tz); - } else { - final String lowerCase = timeZone.toLowerCase(locale); - TzInfo tzInfo = tzNames.get(lowerCase); - if (tzInfo == null) { - // match missing the optional trailing period - tzInfo = tzNames.get(lowerCase + '.'); - } - cal.set(Calendar.DST_OFFSET, tzInfo.dstOffset); - cal.set(Calendar.ZONE_OFFSET, tzInfo.zone.getRawOffset()); - } - } - } - - private static class ISO8601TimeZoneStrategy extends PatternStrategy { - // Z, +hh, -hh, +hhmm, -hhmm, +hh:mm or -hh:mm - - /** - * Construct a Strategy that parses a TimeZone - * @param pattern The Pattern - */ - ISO8601TimeZoneStrategy(final String pattern) { - createPattern(pattern); - } - - /** - * {@inheritDoc} - */ - @Override - void setCalendar(final FastDateParser parser, final Calendar cal, final String value) { - cal.setTimeZone(FastTimeZone.getGmtTimeZone(value)); - } - - private static final Strategy ISO_8601_1_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}))"); - private static final Strategy ISO_8601_2_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}\\d{2}))"); - private static final Strategy ISO_8601_3_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}(?::)\\d{2}))"); - - /** - * Factory method for ISO8601TimeZoneStrategies. - * - * @param tokenLen a token indicating the length of the TimeZone String to be formatted. - * @return a ISO8601TimeZoneStrategy that can format TimeZone String of length {@code tokenLen}. If no such - * strategy exists, an IllegalArgumentException will be thrown. - */ - static Strategy getStrategy(final int tokenLen) { - switch(tokenLen) { - case 1: - return ISO_8601_1_STRATEGY; - case 2: - return ISO_8601_2_STRATEGY; - case 3: - return ISO_8601_3_STRATEGY; - default: - throw new IllegalArgumentException("invalid number of X"); - } - } - } - - private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) { - @Override - int modify(final FastDateParser parser, final int iValue) { - return iValue-1; - } - }; - - private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR); - private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR); - private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH); - private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR); - private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH); - private static final Strategy DAY_OF_WEEK_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK) { - @Override - int modify(final FastDateParser parser, final int iValue) { - return iValue == 7 ? Calendar.SUNDAY : iValue + 1; - } - }; - - private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH); - private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY); - private static final Strategy HOUR24_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) { - @Override - int modify(final FastDateParser parser, final int iValue) { - return iValue == 24 ? 0 : iValue; - } - }; - - private static final Strategy HOUR12_STRATEGY = new NumberStrategy(Calendar.HOUR) { - @Override - int modify(final FastDateParser parser, final int iValue) { - return iValue == 12 ? 0 : iValue; - } - }; - - private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR); - private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE); - private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND); - private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND); -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java deleted file mode 100644 index ee9644f082e..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastDatePrinter.java +++ /dev/null @@ -1,1514 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.common.time; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.text.DateFormatSymbols; -import java.text.FieldPosition; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *

FastDatePrinter is a fast and thread-safe version

- */ -public class FastDatePrinter implements DatePrinter, Serializable { - // A lot of the speed in this class comes from caching, but some comes - // from the special int to StringBuffer conversion. - // - // The following produces a padded 2 digit number: - // buffer.append((char)(value / 10 + '0')); - // buffer.append((char)(value % 10 + '0')); - // - // Note that the fastest append to StringBuffer is a single char (used here). - // Note that Integer.toString() is not called, the conversion is simply - // taking the value and adding (mathematically) the ASCII value for '0'. - // So, don't change this code! It works and is very fast. - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1L; - - - /** - * The pattern. - */ - private final String mPattern; - /** - * The time zone. - */ - private final TimeZone mTimeZone; - /** - * The locale. - */ - private final Locale mLocale; - /** - * The parsed rules. - */ - private transient Rule[] mRules; - /** - * The estimated maximum length. - */ - private transient int mMaxLengthEstimate; - - // Constructor - //----------------------------------------------------------------------- - /** - *

Constructs a new FastDatePrinter.

- * factory methods of {@link FastDateFormat} to get a cached FastDatePrinter instance. - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale to use - * @throws NullPointerException if pattern, timeZone, or locale is null. - */ - protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) { - mPattern = pattern; - mTimeZone = timeZone; - mLocale = locale; - - init(); - } - - /** - *

Initializes the instance for first use.

- */ - private void init() { - final List rulesList = parsePattern(); - mRules = rulesList.toArray(new Rule[rulesList.size()]); - - int len = 0; - for (int i=mRules.length; --i >= 0; ) { - len += mRules[i].estimateLength(); - } - - mMaxLengthEstimate = len; - } - - // Parse the pattern - //----------------------------------------------------------------------- - /** - *

Returns a list of Rules given a pattern.

- * - * @return a {@code List} of Rule objects - * @throws IllegalArgumentException if pattern is invalid - */ - protected List parsePattern() { - final DateFormatSymbols symbols = new DateFormatSymbols(mLocale); - final List rules = new ArrayList<>(); - - final String[] ERAs = symbols.getEras(); - final String[] months = symbols.getMonths(); - final String[] shortMonths = symbols.getShortMonths(); - final String[] weekdays = symbols.getWeekdays(); - final String[] shortWeekdays = symbols.getShortWeekdays(); - final String[] AmPmStrings = symbols.getAmPmStrings(); - - final int length = mPattern.length(); - final int[] indexRef = new int[1]; - - for (int i = 0; i < length; i++) { - indexRef[0] = i; - final String token = parseToken(mPattern, indexRef); - i = indexRef[0]; - - final int tokenLen = token.length(); - if (tokenLen == 0) { - break; - } - - Rule rule; - final char c = token.charAt(0); - - switch (c) { - case 'G': // era designator (text) - rule = new TextField(Calendar.ERA, ERAs); - break; - case 'y': // year (number) - case 'Y': // week year - if (tokenLen == 2) { - rule = TwoDigitYearField.INSTANCE; - } else { - rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); - } - if (c == 'Y') { - rule = new WeekYear((NumberRule) rule); - } - break; - case 'M': // month in year (text and number) - if (tokenLen >= 4) { - rule = new TextField(Calendar.MONTH, months); - } else if (tokenLen == 3) { - rule = new TextField(Calendar.MONTH, shortMonths); - } else if (tokenLen == 2) { - rule = TwoDigitMonthField.INSTANCE; - } else { - rule = UnpaddedMonthField.INSTANCE; - } - break; - case 'd': // day in month (number) - rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); - break; - case 'h': // hour in am/pm (number, 1..12) - rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); - break; - case 'H': // hour in day (number, 0..23) - rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); - break; - case 'm': // minute in hour (number) - rule = selectNumberRule(Calendar.MINUTE, tokenLen); - break; - case 's': // second in minute (number) - rule = selectNumberRule(Calendar.SECOND, tokenLen); - break; - case 'S': // millisecond (number) - rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); - break; - case 'E': // day in week (text) - rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); - break; - case 'u': // day in week (number) - rule = new DayInWeekField(selectNumberRule(Calendar.DAY_OF_WEEK, tokenLen)); - break; - case 'D': // day in year (number) - rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); - break; - case 'F': // day of week in month (number) - rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); - break; - case 'w': // week in year (number) - rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); - break; - case 'W': // week in month (number) - rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); - break; - case 'a': // am/pm marker (text) - rule = new TextField(Calendar.AM_PM, AmPmStrings); - break; - case 'k': // hour in day (1..24) - rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); - break; - case 'K': // hour in am/pm (0..11) - rule = selectNumberRule(Calendar.HOUR, tokenLen); - break; - case 'X': // ISO 8601 - rule = Iso8601_Rule.getRule(tokenLen); - break; - case 'z': // time zone (text) - if (tokenLen >= 4) { - rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); - } else { - rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); - } - break; - case 'Z': // time zone (value) - if (tokenLen == 1) { - rule = TimeZoneNumberRule.INSTANCE_NO_COLON; - } else if (tokenLen == 2) { - rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES; - } else { - rule = TimeZoneNumberRule.INSTANCE_COLON; - } - break; - case '\'': // literal text - final String sub = token.substring(1); - if (sub.length() == 1) { - rule = new CharacterLiteral(sub.charAt(0)); - } else { - rule = new StringLiteral(sub); - } - break; - default: - throw new IllegalArgumentException("Illegal pattern component: " + token); - } - - rules.add(rule); - } - - return rules; - } - - /** - *

Performs the parsing of tokens.

- * - * @param pattern the pattern - * @param indexRef index references - * @return parsed token - */ - protected String parseToken(final String pattern, final int[] indexRef) { - final StringBuilder buf = new StringBuilder(); - - int i = indexRef[0]; - final int length = pattern.length(); - - char c = pattern.charAt(i); - if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { - // Scan a run of the same character, which indicates a time - // pattern. - buf.append(c); - - while (i + 1 < length) { - final char peek = pattern.charAt(i + 1); - if (peek == c) { - buf.append(c); - i++; - } else { - break; - } - } - } else { - // This will identify token as text. - buf.append('\''); - - boolean inLiteral = false; - - for (; i < length; i++) { - c = pattern.charAt(i); - - if (c == '\'') { - if (i + 1 < length && pattern.charAt(i + 1) == '\'') { - // '' is treated as escaped ' - i++; - buf.append(c); - } else { - inLiteral = !inLiteral; - } - } else if (!inLiteral && - (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { - i--; - break; - } else { - buf.append(c); - } - } - } - - indexRef[0] = i; - return buf.toString(); - } - - /** - *

Gets an appropriate rule for the padding required.

- * - * @param field the field to get a rule for - * @param padding the padding required - * @return a new rule with the correct padding - */ - protected NumberRule selectNumberRule(final int field, final int padding) { - switch (padding) { - case 1: - return new UnpaddedNumberField(field); - case 2: - return new TwoDigitNumberField(field); - default: - return new PaddedNumberField(field, padding); - } - } - - // Format methods - //----------------------------------------------------------------------- - /** - *

Formats a {@code Date}, {@code Calendar} or - * {@code Long} (milliseconds) object.

- * @deprecated Use {{@link #format(Date)}, {{@link #format(Calendar)}, {{@link #format(long)}, or {{@link #format(Object)} - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - */ - @Deprecated - @Override - public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { - if (obj instanceof Date) { - return format((Date) obj, toAppendTo); - } else if (obj instanceof Calendar) { - return format((Calendar) obj, toAppendTo); - } else if (obj instanceof Long) { - return format(((Long) obj).longValue(), toAppendTo); - } else { - throw new IllegalArgumentException("Unknown class: " + - (obj == null ? "" : obj.getClass().getName())); - } - } - - /** - *

Formats a {@code Date}, {@code Calendar} or - * {@code Long} (milliseconds) object.

- * @since 3.5 - * @param obj the object to format - * @return The formatted value. - */ - String format(final Object obj) { - if (obj instanceof Date) { - return format((Date) obj); - } else if (obj instanceof Calendar) { - return format((Calendar) obj); - } else if (obj instanceof Long) { - return format(((Long) obj).longValue()); - } else { - throw new IllegalArgumentException("Unknown class: " + - (obj == null ? "" : obj.getClass().getName())); - } - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long) - */ - @Override - public String format(final long millis) { - final Calendar c = newCalendar(); - c.setTimeInMillis(millis); - return applyRulesToString(c); - } - - /** - * Creates a String representation of the given Calendar by applying the rules of this printer to it. - * @param c the Calender to apply the rules to. - * @return a String representation of the given Calendar. - */ - private String applyRulesToString(final Calendar c) { - return applyRules(c, new StringBuilder(mMaxLengthEstimate)).toString(); - } - - /** - * Creation method for new calender instances. - * @return a new Calendar instance. - */ - private Calendar newCalendar() { - return Calendar.getInstance(mTimeZone, mLocale); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) - */ - @Override - public String format(final Date date) { - final Calendar c = newCalendar(); - c.setTime(date); - return applyRulesToString(c); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) - */ - @Override - public String format(final Calendar calendar) { - return format(calendar, new StringBuilder(mMaxLengthEstimate)).toString(); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final long millis, final StringBuffer buf) { - final Calendar c = newCalendar(); - c.setTimeInMillis(millis); - return (StringBuffer) applyRules(c, (Appendable) buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Date date, final StringBuffer buf) { - final Calendar c = newCalendar(); - c.setTime(date); - return (StringBuffer) applyRules(c, (Appendable) buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Calendar calendar, final StringBuffer buf) { - // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored - return format(calendar.getTime(), buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.Appendable) - */ - @Override - public B format(final long millis, final B buf) { - final Calendar c = newCalendar(); - c.setTimeInMillis(millis); - return applyRules(c, buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.Appendable) - */ - @Override - public B format(final Date date, final B buf) { - final Calendar c = newCalendar(); - c.setTime(date); - return applyRules(c, buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.Appendable) - */ - @Override - public B format(Calendar calendar, final B buf) { - // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored - if (!calendar.getTimeZone().equals(mTimeZone)) { - calendar = (Calendar) calendar.clone(); - calendar.setTimeZone(mTimeZone); - } - return applyRules(calendar, buf); - } - - /** - * Performs the formatting by applying the rules to the - * specified calendar. - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * - * @deprecated use {@link #format(Calendar)} or {@link #format(Calendar, Appendable)} - */ - @Deprecated - protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { - return (StringBuffer) applyRules(calendar, (Appendable) buf); - } - - /** - *

Performs the formatting by applying the rules to the - * specified calendar.

- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or StringBuffer. - * @return the specified string buffer - */ - private B applyRules(final Calendar calendar, final B buf) { - try { - for (final Rule rule : mRules) { - rule.appendTo(buf, calendar); - } - } catch (final IOException ioe) { - throw new RuntimeException(ioe); - } - return buf; - } - - // Accessors - //----------------------------------------------------------------------- - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getPattern() - */ - @Override - public String getPattern() { - return mPattern; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() - */ - @Override - public TimeZone getTimeZone() { - return mTimeZone; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getLocale() - */ - @Override - public Locale getLocale() { - return mLocale; - } - - /** - *

Gets an estimate for the maximum string length that the - * formatter will produce.

- * - *

The actual formatted length will almost always be less than or - * equal to this amount.

- * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return mMaxLengthEstimate; - } - - // Basics - //----------------------------------------------------------------------- - /** - *

Compares two objects for equality.

- * - * @param obj the object to compare to - * @return {@code true} if equal - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof FastDatePrinter)) { - return false; - } - final FastDatePrinter other = (FastDatePrinter) obj; - return mPattern.equals(other.mPattern) - && mTimeZone.equals(other.mTimeZone) - && mLocale.equals(other.mLocale); - } - - /** - *

Returns a hash code compatible with equals.

- * - * @return a hash code compatible with equals - */ - @Override - public int hashCode() { - return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); - } - - /** - *

Gets a debugging string version of this formatter.

- * - * @return a debugging string - */ - @Override - public String toString() { - return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; - } - - // Serializing - //----------------------------------------------------------------------- - /** - * Create the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - init(); - } - - /** - * Appends two digits to the given buffer. - * - * @param buffer the buffer to append to. - * @param value the value to append digits from. - */ - private static void appendDigits(final Appendable buffer, final int value) throws IOException { - buffer.append((char) (value / 10 + '0')); - buffer.append((char) (value % 10 + '0')); - } - - private static final int MAX_DIGITS = 10; // log10(Integer.MAX_VALUE) ~= 9.3 - - /** - * Appends all digits to the given buffer. - * - * @param buffer the buffer to append to. - * @param value the value to append digits from. - */ - private static void appendFullDigits(final Appendable buffer, int value, int minFieldWidth) throws IOException { - // specialized paths for 1 to 4 digits -> avoid the memory allocation from the temporary work array - // see LANG-1248 - if (value < 10000) { - // less memory allocation path works for four digits or less - - int nDigits = 4; - if (value < 1000) { - --nDigits; - if (value < 100) { - --nDigits; - if (value < 10) { - --nDigits; - } - } - } - // left zero pad - for (int i = minFieldWidth - nDigits; i > 0; --i) { - buffer.append('0'); - } - - switch (nDigits) { - case 4: - buffer.append((char) (value / 1000 + '0')); - value %= 1000; - case 3: - if (value >= 100) { - buffer.append((char) (value / 100 + '0')); - value %= 100; - } else { - buffer.append('0'); - } - case 2: - if (value >= 10) { - buffer.append((char) (value / 10 + '0')); - value %= 10; - } else { - buffer.append('0'); - } - case 1: - buffer.append((char) (value + '0')); - } - } else { - // more memory allocation path works for any digits - - // build up decimal representation in reverse - final char[] work = new char[MAX_DIGITS]; - int digit = 0; - while (value != 0) { - work[digit++] = (char) (value % 10 + '0'); - value = value / 10; - } - - // pad with zeros - while (digit < minFieldWidth) { - buffer.append('0'); - --minFieldWidth; - } - - // reverse - while (--digit >= 0) { - buffer.append(work[digit]); - } - } - } - - // Rules - //----------------------------------------------------------------------- - /** - *

Inner class defining a rule.

- */ - private interface Rule { - /** - * Returns the estimated length of the result. - * - * @return the estimated length - */ - int estimateLength(); - - /** - * Appends the value of the specified calendar to the output buffer based on the rule implementation. - * - * @param buf the output buffer - * @param calendar calendar to be appended - * @throws IOException if an I/O error occurs - */ - void appendTo(Appendable buf, Calendar calendar) throws IOException; - } - - /** - *

Inner class defining a numeric rule.

- */ - private interface NumberRule extends Rule { - /** - * Appends the specified value to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param value the value to be appended - * @throws IOException if an I/O error occurs - */ - void appendTo(Appendable buffer, int value) throws IOException; - } - - /** - *

Inner class to output a constant single character.

- */ - private static class CharacterLiteral implements Rule { - private final char mValue; - - /** - * Constructs a new instance of {@code CharacterLiteral} - * to hold the specified value. - * - * @param value the character literal - */ - CharacterLiteral(final char value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 1; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - buffer.append(mValue); - } - } - - /** - *

Inner class to output a constant string.

- */ - private static class StringLiteral implements Rule { - private final String mValue; - - /** - * Constructs a new instance of {@code StringLiteral} - * to hold the specified value. - * - * @param value the string literal - */ - StringLiteral(final String value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mValue.length(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - buffer.append(mValue); - } - } - - /** - *

Inner class to output one of a set of values.

- */ - private static class TextField implements Rule { - private final int mField; - private final String[] mValues; - - /** - * Constructs an instance of {@code TextField} - * with the specified field and values. - * - * @param field the field - * @param values the field values - */ - TextField(final int field, final String[] values) { - mField = field; - mValues = values; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - int max = 0; - for (int i=mValues.length; --i >= 0; ) { - final int len = mValues[i].length(); - if (len > max) { - max = len; - } - } - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - buffer.append(mValues[calendar.get(mField)]); - } - } - - /** - *

Inner class to output an unpadded number.

- */ - private static class UnpaddedNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code UnpadedNumberField} with the specified field. - * - * @param field the field - */ - UnpaddedNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 4; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - if (value < 10) { - buffer.append((char) (value + '0')); - } else if (value < 100) { - appendDigits(buffer, value); - } else { - appendFullDigits(buffer, value, 1); - } - } - } - - /** - *

Inner class to output an unpadded month.

- */ - private static class UnpaddedMonthField implements NumberRule { - static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); - - /** - * Constructs an instance of {@code UnpaddedMonthField}. - * - */ - UnpaddedMonthField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - if (value < 10) { - buffer.append((char) (value + '0')); - } else { - appendDigits(buffer, value); - } - } - } - - /** - *

Inner class to output a padded number.

- */ - private static class PaddedNumberField implements NumberRule { - private final int mField; - private final int mSize; - - /** - * Constructs an instance of {@code PaddedNumberField}. - * - * @param field the field - * @param size size of the output field - */ - PaddedNumberField(final int field, final int size) { - if (size < 3) { - // Should use UnpaddedNumberField or TwoDigitNumberField. - throw new IllegalArgumentException(); - } - mField = field; - mSize = size; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mSize; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - appendFullDigits(buffer, value, mSize); - } - } - - /** - *

Inner class to output a two digit number.

- */ - private static class TwoDigitNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code TwoDigitNumberField} with the specified field. - * - * @param field the field - */ - TwoDigitNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - if (value < 100) { - appendDigits(buffer, value); - } else { - appendFullDigits(buffer, value, 2); - } - } - } - - /** - *

Inner class to output a two digit year.

- */ - private static class TwoDigitYearField implements NumberRule { - static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); - - /** - * Constructs an instance of {@code TwoDigitYearField}. - */ - TwoDigitYearField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(Calendar.YEAR) % 100); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - appendDigits(buffer, value); - } - } - - /** - *

Inner class to output a two digit month.

- */ - private static class TwoDigitMonthField implements NumberRule { - static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); - - /** - * Constructs an instance of {@code TwoDigitMonthField}. - */ - TwoDigitMonthField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - appendDigits(buffer, value); - } - } - - /** - *

Inner class to output the twelve hour field.

- */ - private static class TwelveHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwelveHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwelveHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - int value = calendar.get(Calendar.HOUR); - if (value == 0) { - value = calendar.getLeastMaximum(Calendar.HOUR) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - /** - *

Inner class to output the twenty four hour field.

- */ - private static class TwentyFourHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwentyFourHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwentyFourHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - int value = calendar.get(Calendar.HOUR_OF_DAY); - if (value == 0) { - value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - /** - *

Inner class to output the numeric day in week.

- */ - private static class DayInWeekField implements NumberRule { - private final NumberRule mRule; - - DayInWeekField(final NumberRule rule) { - mRule = rule; - } - - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - final int value = calendar.get(Calendar.DAY_OF_WEEK); - mRule.appendTo(buffer, value == Calendar.SUNDAY ? 7 : value - 1); - } - - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - /** - *

Inner class to output the numeric day in week.

- */ - private static class WeekYear implements NumberRule { - private final NumberRule mRule; - - WeekYear(final NumberRule rule) { - mRule = rule; - } - - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - mRule.appendTo(buffer, calendar.getWeekYear()); - } - - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - //----------------------------------------------------------------------- - - private static final ConcurrentMap cTimeZoneDisplayCache = - new ConcurrentHashMap<>(7); - /** - *

Gets the time zone display name, using a cache for performance.

- * - * @param tz the zone to query - * @param daylight true if daylight savings - * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT} - * @param locale the locale to use - * @return the textual name of the time zone - */ - static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { - final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); - String value = cTimeZoneDisplayCache.get(key); - if (value == null) { - // This is a very slow call, so cache the results. - value = tz.getDisplayName(daylight, style, locale); - final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); - if (prior != null) { - value= prior; - } - } - return value; - } - - /** - *

Inner class to output a time zone name.

- */ - private static class TimeZoneNameRule implements Rule { - private final Locale mLocale; - private final int mStyle; - private final String mStandard; - private final String mDaylight; - - /** - * Constructs an instance of {@code TimeZoneNameRule} with the specified properties. - * - * @param timeZone the time zone - * @param locale the locale - * @param style the style - */ - TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { - mLocale = locale; - mStyle = style; - - mStandard = getTimeZoneDisplay(timeZone, false, style, locale); - mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - // We have no access to the Calendar object that will be passed to - // appendTo so base estimate on the TimeZone passed to the - // constructor - return Math.max(mStandard.length(), mDaylight.length()); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - final TimeZone zone = calendar.getTimeZone(); - if (calendar.get(Calendar.DST_OFFSET) == 0) { - buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); - } else { - buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); - } - } - } - - /** - *

Inner class to output a time zone as a number {@code +/-HHMM} - * or {@code +/-HH:MM}.

- */ - private static class TimeZoneNumberRule implements Rule { - static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); - static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); - - final boolean mColon; - - /** - * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties. - * - * @param colon add colon between HH and MM in the output if {@code true} - */ - TimeZoneNumberRule(final boolean colon) { - mColon = colon; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 5; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (mColon) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - /** - *

Inner class to output a time zone as a number {@code +/-HHMM} - * or {@code +/-HH:MM}.

- */ - private static class Iso8601_Rule implements Rule { - - // Sign TwoDigitHours or Z - static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); - // Sign TwoDigitHours Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); - // Sign TwoDigitHours : Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); - - /** - * Factory method for Iso8601_Rules. - * - * @param tokenLen a token indicating the length of the TimeZone String to be formatted. - * @return a Iso8601_Rule that can format TimeZone String of length {@code tokenLen}. If no such - * rule exists, an IllegalArgumentException will be thrown. - */ - static Iso8601_Rule getRule(final int tokenLen) { - switch(tokenLen) { - case 1: - return ISO8601_HOURS; - case 2: - return ISO8601_HOURS_MINUTES; - case 3: - return ISO8601_HOURS_COLON_MINUTES; - default: - throw new IllegalArgumentException("invalid number of X"); - } - } - - final int length; - - /** - * Constructs an instance of {@code Iso8601_Rule} with the specified properties. - * - * @param length The number of characters in output (unless Z is output) - */ - Iso8601_Rule(final int length) { - this.length = length; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return length; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - if (offset == 0) { - buffer.append("Z"); - return; - } - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (length<5) { - return; - } - - if (length==6) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - // ---------------------------------------------------------------------- - /** - *

Inner class that acts as a compound key for time zone names.

- */ - private static class TimeZoneDisplayKey { - private final TimeZone mTimeZone; - private final int mStyle; - private final Locale mLocale; - - /** - * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. - * - * @param timeZone the time zone - * @param daylight adjust the style for daylight saving time if {@code true} - * @param style the timezone style - * @param locale the timezone locale - */ - TimeZoneDisplayKey(final TimeZone timeZone, - final boolean daylight, final int style, final Locale locale) { - mTimeZone = timeZone; - if (daylight) { - mStyle = style | 0x80000000; - } else { - mStyle = style; - } - mLocale = locale; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof TimeZoneDisplayKey) { - final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; - return - mTimeZone.equals(other.mTimeZone) && - mStyle == other.mStyle && - mLocale.equals(other.mLocale); - } - return false; - } - } -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java deleted file mode 100644 index 9babe929048..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FastTimeZone.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.time; - -import java.util.TimeZone; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Faster methods to produce custom time zones. - * - * @since 3.7 - */ -public class FastTimeZone { - public static final String GMT_ID = "GMT"; - private static final Pattern GMT_PATTERN = Pattern.compile("^(?:(?i)GMT)?([+-])?(\\d\\d?)?(:?(\\d\\d?))?$"); - - private static final TimeZone GREENWICH = new GmtTimeZone(false, 0, 0); - - /** - * Gets the GMT TimeZone. - * - * @return A TimeZone with a raw offset of zero. - */ - public static TimeZone getGmtTimeZone() { - return GREENWICH; - } - - /** - * Gets a TimeZone with GMT offsets. A GMT offset must be either 'Z', or 'UTC', or match - * (GMT)? hh?(:?mm?)?, where h and m are digits representing hours and minutes. - * - * @param pattern The GMT offset - * @return A TimeZone with offset from GMT or null, if pattern does not match. - */ - public static TimeZone getGmtTimeZone(final String pattern) { - if ("Z".equals(pattern) || "UTC".equals(pattern)) { - return GREENWICH; - } - - final Matcher m = GMT_PATTERN.matcher(pattern); - if (m.matches()) { - final int hours = parseInt(m.group(2)); - final int minutes = parseInt(m.group(4)); - if (hours == 0 && minutes == 0) { - return GREENWICH; - } - return new GmtTimeZone(parseSign(m.group(1)), hours, minutes); - } - return null; - } - - /** - * Gets a TimeZone, looking first for GMT custom ids, then falling back to Olson ids. - * A GMT custom id can be 'Z', or 'UTC', or has an optional prefix of GMT, - * followed by sign, hours digit(s), optional colon(':'), and optional minutes digits. - * i.e. [GMT] (+|-) Hours [[:] Minutes] - * - * @param id A GMT custom id (or Olson id - * @return A timezone - */ - public static TimeZone getTimeZone(final String id) { - final TimeZone tz = getGmtTimeZone(id); - if (tz != null) { - return tz; - } - return TimeZone.getTimeZone(id); - } - - private static int parseInt(final String group) { - return group != null ? Integer.parseInt(group) : 0; - } - - private static boolean parseSign(final String group) { - return group != null && group.charAt(0) == '-'; - } - - // do not instantiate - private FastTimeZone() { - } - - -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java deleted file mode 100644 index 8aa1f908f59..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/FormatCache.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.time; - -import org.apache.dubbo.common.utils.Assert; - -import java.text.DateFormat; -import java.text.Format; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *

FormatCache is a cache and factory for {@link Format}s.

- */ -// TODO: Before making public move from getDateTimeInstance(Integer, ...) to int; or some other approach. -abstract class FormatCache { - - /** - * No date or no time. Used in same parameters as DateFormat.SHORT or DateFormat.LONG - */ - static final int NONE= -1; - - private final ConcurrentMap cInstanceCache - = new ConcurrentHashMap<>(7); - - private static final ConcurrentMap cDateTimeInstanceCache - = new ConcurrentHashMap<>(7); - - /** - *

Gets a formatter instance using the default pattern in the - * default timezone and locale.

- * - * @return a date/time formatter - */ - public F getInstance() { - return getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TimeZone.getDefault(), Locale.getDefault()); - } - - /** - *

Gets a formatter instance using the specified pattern, time zone - * and locale.

- * - * @param pattern {@link java.text.SimpleDateFormat} compatible - * pattern, non-null - * @param timeZone the time zone, null means use the default TimeZone - * @param locale the locale, null means use the default Locale - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - * or null - */ - public F getInstance(final String pattern, TimeZone timeZone, Locale locale) { - Assert.notNull(pattern, "Pattern must not be null"); - if (timeZone == null) { - timeZone = TimeZone.getDefault(); - } - if (locale == null) { - locale = Locale.getDefault(); - } - final MultipartKey key = new MultipartKey(pattern, timeZone, locale); - F format = cInstanceCache.get(key); - if (format == null) { - format = createInstance(pattern, timeZone, locale); - final F previousValue= cInstanceCache.putIfAbsent(key, format); - if (previousValue != null) { - // another thread snuck in and did the same work - // we should return the instance that is in ConcurrentMap - format= previousValue; - } - } - return format; - } - - /** - *

Create a format instance using the specified pattern, time zone - * and locale.

- * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this will not be null. - * @param timeZone time zone, this will not be null. - * @param locale locale, this will not be null. - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - * or null - */ - protected abstract F createInstance(String pattern, TimeZone timeZone, Locale locale); - - /** - *

Gets a date/time formatter instance using the specified style, - * time zone and locale.

- * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format - * @param timeZone optional time zone, overrides time zone of - * formatted date, null means use default Locale - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time - * pattern defined - */ - // This must remain private, see LANG-884 - private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, Locale locale) { - if (locale == null) { - locale = Locale.getDefault(); - } - final String pattern = getPatternForStyle(dateStyle, timeStyle, locale); - return getInstance(pattern, timeZone, locale); - } - - - /** - *

Gets a date/time format for the specified styles and locale.

- * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format - * @param locale The non-null locale of the desired format - * @return a localized standard date/time format - * @throws IllegalArgumentException if the Locale has no date/time pattern defined - */ - // package protected, for access from test code; do not make public or protected - static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) { - final MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale); - - String pattern = cDateTimeInstanceCache.get(key); - if (pattern == null) { - try { - DateFormat formatter; - if (dateStyle == null) { - formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale); - } else if (timeStyle == null) { - formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale); - } else { - formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale); - } - pattern = ((SimpleDateFormat) formatter).toPattern(); - final String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern); - if (previous != null) { - // even though it doesn't matter if another thread put the pattern - // it's still good practice to return the String instance that is - // actually in the ConcurrentMap - pattern= previous; - } - } catch (final ClassCastException ex) { - throw new IllegalArgumentException("No date time pattern for locale: " + locale); - } - } - return pattern; - } - - // ---------------------------------------------------------------------- - /** - *

Helper class to hold multi-part Map keys

- */ - private static class MultipartKey { - private final Object[] keys; - private int hashCode; - - /** - * Constructs an instance of MultipartKey to hold the specified objects. - * @param keys the set of objects that make up the key. Each key may be null. - */ - MultipartKey(final Object... keys) { - this.keys = keys; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(final Object obj) { - // Eliminate the usual boilerplate because - // this inner static class is only used in a generic ConcurrentHashMap - // which will not compare against other Object types - return Arrays.equals(keys, ((MultipartKey) obj).keys); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - if (hashCode==0) { - int rc= 0; - for (final Object key : keys) { - if (key!=null) { - rc= rc*7 + key.hashCode(); - } - } - hashCode= rc; - } - return hashCode; - } - } - -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java b/dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java deleted file mode 100644 index da0ba8b4afa..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/time/GmtTimeZone.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.common.time; - -import java.util.Date; -import java.util.TimeZone; - -/** - * Custom timezone that contains offset from GMT. - */ -class GmtTimeZone extends TimeZone { - - private static final int MILLISECONDS_PER_MINUTE = 60 * 1000; - private static final int MINUTES_PER_HOUR = 60; - private static final int HOURS_PER_DAY = 24; - - // Serializable! - static final long serialVersionUID = 1L; - - private final int offset; - private final String zoneId; - - GmtTimeZone(final boolean negate, final int hours, final int minutes) { - if (hours >= HOURS_PER_DAY) { - throw new IllegalArgumentException(hours + " hours out of range"); - } - if (minutes >= MINUTES_PER_HOUR) { - throw new IllegalArgumentException(minutes + " minutes out of range"); - } - final int milliseconds = (minutes + (hours * MINUTES_PER_HOUR)) * MILLISECONDS_PER_MINUTE; - offset = negate ? -milliseconds : milliseconds; - zoneId = twoDigits( - twoDigits(new StringBuilder(9).append("GMT").append(negate ? '-' : '+'), hours) - .append(':'), minutes).toString(); - - } - - private static StringBuilder twoDigits(final StringBuilder sb, final int n) { - return sb.append((char) ('0' + (n / 10))).append((char) ('0' + (n % 10))); - } - - @Override - public int getOffset(final int era, final int year, final int month, final int day, final int dayOfWeek, final int milliseconds) { - return offset; - } - - @Override - public void setRawOffset(final int offsetMillis) { - throw new UnsupportedOperationException(); - } - - @Override - public int getRawOffset() { - return offset; - } - - @Override - public String getID() { - return zoneId; - } - - @Override - public boolean useDaylightTime() { - return false; - } - - @Override - public boolean inDaylightTime(final Date date) { - return false; - } - - @Override - public String toString() { - return "[GmtTimeZone id=\"" + zoneId + "\",offset=" + offset + ']'; - } - - @Override - public int hashCode() { - return offset; - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof GmtTimeZone)) { - return false; - } - return zoneId == ((GmtTimeZone) other).zoneId; - } -} \ No newline at end of file diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java deleted file mode 100644 index 2c4e8361039..00000000000 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.common.utils; - -import org.apache.dubbo.common.time.FastDateFormat; - -import java.util.Date; - -/** - * This class is utility to provide dubbo date formatting and parsing. - */ -public final class DateUtil { - - private DateUtil() { - - }; - - /** - * This method used to return a formatted string of a given date object. - * @param date Input data object - * @param format format of data. - * @return - */ - public static String format(Date date, String format) { - Assert.notNull(date, "Given date can't be null"); - Assert.notEmptyString(format, "Given date format can't be null or empty"); - return FastDateFormat.getInstance(format).format(date); - } -} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index a3eb0bb251b..dd95d3fd10e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.rpc.filter; -import static org.apache.dubbo.common.utils.DateUtil.format; - import org.apache.dubbo.common.Constants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; @@ -36,6 +34,8 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Map; @@ -72,6 +72,9 @@ public class AccessLogFilter implements Filter { private static final String FILE_DATE_FORMAT = "yyyyMMdd"; + // It's safe to declare it as singleton since it runs on single thread only + private static final DateFormat FILE_NAME_FORMATTER = new SimpleDateFormat(FILE_DATE_FORMAT); + private static final Map> logEntries = new ConcurrentHashMap>(); private static final ScheduledExecutorService logScheduled = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Access-Log", true)); @@ -185,12 +188,12 @@ private void createIfLogDirAbsent(File file) { private void renameFile(File file) { if (file.exists()) { - String now = format(new Date(), FILE_DATE_FORMAT); - String last = format(new Date(file.lastModified()), FILE_DATE_FORMAT); + String now = FILE_NAME_FORMATTER.format(new Date()); + String last = FILE_NAME_FORMATTER.format(new Date(file.lastModified())); if (!now.equals(last)) { File archive = new File(file.getAbsolutePath() + "." + last); file.renameTo(archive); } } } -} \ No newline at end of file +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java index 852381c94ff..b7d10961470 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java @@ -21,20 +21,24 @@ import com.alibaba.fastjson.JSON; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; -import static org.apache.dubbo.common.utils.DateUtil.format; - /** - * AccessLogData is a container for log event data. In internally uses map and store each filed of log as value. It does not generate any - * dynamic value e.g. time stamp, local jmv machine host address etc. It does not allow any null or empty key. + * AccessLogData is a container for log event data. In internally uses map and store each filed of log as value. It + * does not generate any dynamic value e.g. time stamp, local jmv machine host address etc. It does not allow any null + * or empty key. + * + * Note: since its date formatter is a singleton, make sure to run it in single thread only. */ public final class AccessLogData { private static final String MESSAGE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + private static final DateFormat MESSAGE_DATE_FORMATTER = new SimpleDateFormat(MESSAGE_DATE_FORMAT); private static final String VERSION = "version"; private static final String GROUP = "group"; @@ -188,7 +192,7 @@ public String getLogMessage() { StringBuilder sn = new StringBuilder(); sn.append("[") - .append(format(getInvocationTime(), MESSAGE_DATE_FORMAT)) + .append(MESSAGE_DATE_FORMATTER.format(getInvocationTime())) .append("] ") .append(get(REMOTE_HOST)) .append(":") @@ -259,4 +263,4 @@ private void set(String key, Object value) { data.put(key, value); } -} \ No newline at end of file +} diff --git a/pom.xml b/pom.xml index 736e22c3a79..8f1a39b7201 100644 --- a/pom.xml +++ b/pom.xml @@ -493,15 +493,6 @@ **/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java **/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java - - **/org/apache/dubbo/common/time/DateParser.java - **/org/apache/dubbo/common/time/DatePrinter.java - **/org/apache/dubbo/common/time/FastDateFormat.java - **/org/apache/dubbo/common/time/FastDateParser.java - **/org/apache/dubbo/common/time/FastDatePrinter.java - **/org/apache/dubbo/common/time/FastTimeZone.java - **/org/apache/dubbo/common/time/FormatCache.java - **/org/apache/dubbo/common/time/GmtTimeZone.java