index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactory.java
/* * 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.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; /** * Abstract {@link DynamicConfigurationFactory} implementation with cache ability * * @see DynamicConfigurationFactory * @since 2.7.5 */ public abstract class AbstractDynamicConfigurationFactory implements DynamicConfigurationFactory { private volatile ConcurrentHashMap<String, DynamicConfiguration> dynamicConfigurations = new ConcurrentHashMap<>(); @Override public final DynamicConfiguration getDynamicConfiguration(URL url) { String key = url == null ? DEFAULT_KEY : url.toServiceString(); return ConcurrentHashMapUtils.computeIfAbsent(dynamicConfigurations, key, k -> createDynamicConfiguration(url)); } protected abstract DynamicConfiguration createDynamicConfiguration(URL url); }
6,800
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java
/* * 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.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * The abstract implementation of {@link DynamicConfiguration} * * @since 2.7.5 */ public abstract class AbstractDynamicConfiguration implements DynamicConfiguration { public static final String PARAM_NAME_PREFIX = "dubbo.config-center."; public static final String THREAD_POOL_PREFIX_PARAM_NAME = PARAM_NAME_PREFIX + "thread-pool.prefix"; public static final String DEFAULT_THREAD_POOL_PREFIX = PARAM_NAME_PREFIX + "workers"; public static final String THREAD_POOL_SIZE_PARAM_NAME = PARAM_NAME_PREFIX + "thread-pool.size"; /** * The keep alive time in milliseconds for threads in {@link ThreadPoolExecutor} */ public static final String THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME = PARAM_NAME_PREFIX + "thread-pool.keep-alive-time"; /** * The parameter name of group for config-center * * @since 2.7.8 */ public static final String GROUP_PARAM_NAME = PARAM_NAME_PREFIX + GROUP_KEY; /** * The parameter name of timeout for config-center * * @since 2.7.8 */ public static final String TIMEOUT_PARAM_NAME = PARAM_NAME_PREFIX + TIMEOUT_KEY; public static final int DEFAULT_THREAD_POOL_SIZE = 1; /** * Default keep alive time in milliseconds for threads in {@link ThreadPoolExecutor} is 1 minute( 60 * 1000 ms) */ public static final long DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME = TimeUnit.MINUTES.toMillis(1); /** * Logger */ protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); /** * The thread pool for workers who execute the tasks */ private final ThreadPoolExecutor workersThreadPool; private final String group; private final long timeout; protected AbstractDynamicConfiguration(URL url) { this( getThreadPoolPrefixName(url), getThreadPoolSize(url), getThreadPoolKeepAliveTime(url), getGroup(url), getTimeout(url)); } protected AbstractDynamicConfiguration( String threadPoolPrefixName, int threadPoolSize, long keepAliveTime, String group, long timeout) { this.workersThreadPool = initWorkersThreadPool(threadPoolPrefixName, threadPoolSize, keepAliveTime); this.group = group; this.timeout = timeout; } @Override public void addListener(String key, String group, ConfigurationListener listener) {} @Override public void removeListener(String key, String group, ConfigurationListener listener) {} @Override public final String getConfig(String key, String group, long timeout) throws IllegalStateException { return execute(() -> doGetConfig(key, group), timeout); } @Override public Object getInternalProperty(String key) { return null; } @Override public final void close() throws Exception { try { doClose(); } finally { doFinally(); } } @Override public boolean removeConfig(String key, String group) { return Boolean.TRUE.equals(execute(() -> doRemoveConfig(key, group), -1L)); } /** * @return the default group * @since 2.7.8 */ @Override public String getDefaultGroup() { return getGroup(); } /** * @return the default timeout * @since 2.7.8 */ @Override public long getDefaultTimeout() { return getTimeout(); } /** * Get the content of configuration in the specified key and group * * @param key the key * @param group the group * @return if found, return the content of configuration * @throws Exception If met with some problems */ protected abstract String doGetConfig(String key, String group) throws Exception; /** * Close the resources if necessary * * @throws Exception If met with some problems */ protected abstract void doClose() throws Exception; /** * Remove the config in the specified key and group * * @param key the key * @param group the group * @return If successful, return <code>true</code>, or <code>false</code> * @throws Exception * @since 2.7.8 */ protected abstract boolean doRemoveConfig(String key, String group) throws Exception; /** * Executes the {@link Runnable} with the specified timeout * * @param task the {@link Runnable task} * @param timeout timeout in milliseconds */ protected final void execute(Runnable task, long timeout) { execute( () -> { task.run(); return null; }, timeout); } /** * Executes the {@link Callable} with the specified timeout * * @param task the {@link Callable task} * @param timeout timeout in milliseconds * @param <V> the type of computing result * @return the computing result */ protected final <V> V execute(Callable<V> task, long timeout) { V value = null; try { if (timeout < 1) { // less or equal 0 value = task.call(); } else { Future<V> future = workersThreadPool.submit(task); value = future.get(timeout, TimeUnit.MILLISECONDS); } } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } return value; } protected ThreadPoolExecutor getWorkersThreadPool() { return workersThreadPool; } private void doFinally() { shutdownWorkersThreadPool(); } private void shutdownWorkersThreadPool() { if (!workersThreadPool.isShutdown()) { workersThreadPool.shutdown(); } } protected ThreadPoolExecutor initWorkersThreadPool( String threadPoolPrefixName, int threadPoolSize, long keepAliveTime) { return new ThreadPoolExecutor( threadPoolSize, threadPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory(threadPoolPrefixName, true)); } protected static String getThreadPoolPrefixName(URL url) { return getParameter(url, THREAD_POOL_PREFIX_PARAM_NAME, DEFAULT_THREAD_POOL_PREFIX); } protected static int getThreadPoolSize(URL url) { return getParameter(url, THREAD_POOL_SIZE_PARAM_NAME, DEFAULT_THREAD_POOL_SIZE); } protected static long getThreadPoolKeepAliveTime(URL url) { return getParameter(url, THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME); } protected static String getParameter(URL url, String name, String defaultValue) { if (url != null) { return url.getParameter(name, defaultValue); } return defaultValue; } protected static int getParameter(URL url, String name, int defaultValue) { if (url != null) { return url.getParameter(name, defaultValue); } return defaultValue; } protected static long getParameter(URL url, String name, long defaultValue) { if (url != null) { return url.getParameter(name, defaultValue); } return defaultValue; } protected String getGroup() { return group; } protected long getTimeout() { return timeout; } /** * Get the group from {@link URL the specified connection URL} * * @param url {@link URL the specified connection URL} * @return non-null * @since 2.7.8 */ protected static String getGroup(URL url) { String group = getParameter(url, GROUP_PARAM_NAME, null); return StringUtils.isBlank(group) ? getParameter(url, GROUP_KEY, DEFAULT_GROUP) : group; } /** * Get the timeout from {@link URL the specified connection URL} * * @param url {@link URL the specified connection URL} * @return non-null * @since 2.7.8 */ protected static long getTimeout(URL url) { return getParameter(url, TIMEOUT_PARAM_NAME, -1L); } }
6,801
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeType.java
/* * 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.config.configcenter; /** * Config change event type */ public enum ConfigChangeType { /** * A config is created. */ ADDED, /** * A config is updated. */ MODIFIED, /** * A config is deleted. */ DELETED }
6,802
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java
/* * 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.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * The factory interface to create the instance of {@link DynamicConfiguration} */ @SPI(value = "nop", scope = ExtensionScope.APPLICATION) // 2.7.5 change the default SPI implementation public interface DynamicConfigurationFactory { DynamicConfiguration getDynamicConfiguration(URL url); }
6,803
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java
/* * 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.config.configcenter; /** * Hold content and version information */ public class ConfigItem { /** * configure item content. */ private String content; /** * version information corresponding to the current configure item. */ private Object ticket; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Object getTicket() { return ticket; } public void setTicket(Object ticket) { this.ticket = ticket; } public ConfigItem(String content, Object ticket) { this.content = content; this.ticket = ticket; } public ConfigItem() {} }
6,804
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/Constants.java
/* * 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.config.configcenter; /** * @deprecated Replaced to {@link org.apache.dubbo.common.constants.CommonConstants} */ @Deprecated public interface Constants { String CONFIG_CLUSTER_KEY = "config.cluster"; String CONFIG_NAMESPACE_KEY = "config.namespace"; String CONFIG_GROUP_KEY = "config.group"; String CONFIG_CHECK_KEY = "config.check"; }
6,805
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java
/* * 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.config.configcenter.wrapper; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; /** * support multiple config center, simply iterating each concrete config center. */ public class CompositeDynamicConfiguration implements DynamicConfiguration { public static final String NAME = "COMPOSITE"; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeDynamicConfiguration.class); private final Set<DynamicConfiguration> configurations = new HashSet<>(); public void addConfiguration(DynamicConfiguration configuration) { if (configuration != null) { this.configurations.add(configuration); } } public Set<DynamicConfiguration> getInnerConfigurations() { return configurations; } @Override public void addListener(String key, String group, ConfigurationListener listener) { iterateListenerOperation(configuration -> configuration.addListener(key, group, listener)); } @Override public void removeListener(String key, String group, ConfigurationListener listener) { iterateListenerOperation(configuration -> configuration.removeListener(key, group, listener)); } @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { return (String) iterateConfigOperation(configuration -> configuration.getConfig(key, group, timeout)); } @Override public String getProperties(String key, String group, long timeout) throws IllegalStateException { return (String) iterateConfigOperation(configuration -> configuration.getProperties(key, group, timeout)); } @Override public Object getInternalProperty(String key) { return iterateConfigOperation(configuration -> configuration.getInternalProperty(key)); } @Override public boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException { boolean publishedAll = true; for (DynamicConfiguration configuration : configurations) { if (!configuration.publishConfig(key, group, content)) { publishedAll = false; } } return publishedAll; } @Override public void close() throws Exception { for (DynamicConfiguration configuration : configurations) { try { configuration.close(); } catch (Exception e) { logger.warn( INTERNAL_ERROR, "unknown error in configuration-center related code in common module", "", "close dynamic configuration " + configuration.getClass().getName() + "failed: " + e.getMessage(), e); } } configurations.clear(); } private void iterateListenerOperation(Consumer<DynamicConfiguration> consumer) { for (DynamicConfiguration configuration : configurations) { consumer.accept(configuration); } } private Object iterateConfigOperation(Function<DynamicConfiguration, Object> func) { Object value = null; for (DynamicConfiguration configuration : configurations) { value = func.apply(configuration); if (value != null) { break; } } return value; } }
6,806
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java
/* * 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.config.configcenter.file; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration; import org.apache.dubbo.common.function.ThrowableConsumer; import org.apache.dubbo.common.function.ThrowableFunction; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.io.File; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.FileUtils; import static java.lang.String.format; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableMap; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.io.FileUtils.readFileToString; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_PROCESS_LISTENER; /** * File-System based {@link DynamicConfiguration} implementation * * @since 2.7.5 */ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration { public static final String CONFIG_CENTER_DIR_PARAM_NAME = PARAM_NAME_PREFIX + "dir"; public static final String CONFIG_CENTER_ENCODING_PARAM_NAME = PARAM_NAME_PREFIX + "encoding"; public static final String DEFAULT_CONFIG_CENTER_DIR_PATH = System.getProperty("user.home") + File.separator + ".dubbo" + File.separator + "config-center"; public static final int DEFAULT_THREAD_POOL_SIZE = 1; public static final String DEFAULT_CONFIG_CENTER_ENCODING = "UTF-8"; private static final WatchEvent.Kind[] INTEREST_PATH_KINDS = of(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); /** * The class name of {@linkplain sun.nio.fs.PollingWatchService} */ private static final String POLLING_WATCH_SERVICE_CLASS_NAME = "sun.nio.fs.PollingWatchService"; private static final int THREAD_POOL_SIZE = 1; /** * Logger */ private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileSystemDynamicConfiguration.class); /** * The unmodifiable map for {@link ConfigChangeType} whose key is the {@link WatchEvent.Kind#name() name} of * {@link WatchEvent.Kind WatchEvent's Kind} */ private static final Map<String, ConfigChangeType> CONFIG_CHANGE_TYPES_MAP = unmodifiableMap(new HashMap<String, ConfigChangeType>() { // Initializes the elements that is mapping ConfigChangeType { put(ENTRY_CREATE.name(), ConfigChangeType.ADDED); put(ENTRY_DELETE.name(), ConfigChangeType.DELETED); put(ENTRY_MODIFY.name(), ConfigChangeType.MODIFIED); } }); private static final Optional<WatchService> watchService; /** * Is Pooling Based Watch Service * * @see #detectPoolingBasedWatchService(Optional) */ private static final boolean BASED_POOLING_WATCH_SERVICE; private static final WatchEvent.Modifier[] MODIFIERS; /** * the delay to action in seconds. If null, execute indirectly */ private static final Integer DELAY; /** * The thread pool for {@link WatchEvent WatchEvents} loop * It's optional if there is not any {@link ConfigurationListener} registration * * @see ThreadPoolExecutor */ private static final ThreadPoolExecutor WATCH_EVENTS_LOOP_THREAD_POOL; // static initialization static { watchService = newWatchService(); BASED_POOLING_WATCH_SERVICE = detectPoolingBasedWatchService(watchService); MODIFIERS = initWatchEventModifiers(); DELAY = initDelay(MODIFIERS); WATCH_EVENTS_LOOP_THREAD_POOL = newWatchEventsLoopThreadPool(); } /** * The Root Directory for config center */ private final File rootDirectory; private final String encoding; /** * The {@link Set} of {@link #groupDirectory(String) directories} that may be processing, * <p> * if {@link #isBasedPoolingWatchService()} is <code>false</code>, this properties will be * {@link Collections#emptySet() empty} * * @see #initProcessingDirectories() */ private final Set<File> processingDirectories; private final Map<File, List<ConfigurationListener>> listenersRepository; private ScopeModel scopeModel; private AtomicBoolean hasRegisteredShutdownHook = new AtomicBoolean(); public FileSystemDynamicConfiguration() { this(new File(DEFAULT_CONFIG_CENTER_DIR_PATH)); } public FileSystemDynamicConfiguration(File rootDirectory) { this(rootDirectory, DEFAULT_CONFIG_CENTER_ENCODING); } public FileSystemDynamicConfiguration(File rootDirectory, String encoding) { this(rootDirectory, encoding, DEFAULT_THREAD_POOL_PREFIX); } public FileSystemDynamicConfiguration(File rootDirectory, String encoding, String threadPoolPrefixName) { this(rootDirectory, encoding, threadPoolPrefixName, DEFAULT_THREAD_POOL_SIZE); } public FileSystemDynamicConfiguration( File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize) { this(rootDirectory, encoding, threadPoolPrefixName, threadPoolSize, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME); } public FileSystemDynamicConfiguration( File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize, long keepAliveTime) { super(rootDirectory.getAbsolutePath(), threadPoolPrefixName, threadPoolSize, keepAliveTime, DEFAULT_GROUP, -1L); this.rootDirectory = rootDirectory; this.encoding = encoding; this.processingDirectories = initProcessingDirectories(); this.listenersRepository = new HashMap<>(); registerDubboShutdownHook(); } public FileSystemDynamicConfiguration( File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize, long keepAliveTime, ScopeModel scopeModel) { super(rootDirectory.getAbsolutePath(), threadPoolPrefixName, threadPoolSize, keepAliveTime, DEFAULT_GROUP, -1L); this.rootDirectory = rootDirectory; this.encoding = encoding; this.processingDirectories = initProcessingDirectories(); this.listenersRepository = new HashMap<>(); this.scopeModel = scopeModel; registerDubboShutdownHook(); } public FileSystemDynamicConfiguration(URL url) { this( initDirectory(url), getEncoding(url), getThreadPoolPrefixName(url), getThreadPoolSize(url), getThreadPoolKeepAliveTime(url), url.getScopeModel()); } private Set<File> initProcessingDirectories() { return isBasedPoolingWatchService() ? new LinkedHashSet<>() : emptySet(); } public File configFile(String key, String group) { return new File(buildPathKey(group, key)); } private void doInListener(String configFilePath, BiConsumer<File, List<ConfigurationListener>> consumer) { watchService.ifPresent(watchService -> { File configFile = new File(configFilePath); executeMutually(configFile.getParentFile(), () -> { // process the WatchEvents if not start if (!isProcessingWatchEvents()) { processWatchEvents(watchService); } List<ConfigurationListener> listeners = getListeners(configFile); consumer.accept(configFile, listeners); // Nothing to return return null; }); }); } /** * Register the Dubbo ShutdownHook * * @since 2.7.8 */ private void registerDubboShutdownHook() { if (!hasRegisteredShutdownHook.compareAndSet(false, true)) { return; } ShutdownHookCallbacks shutdownHookCallbacks = ScopeModelUtil.getApplicationModel(scopeModel).getBeanFactory().getBean(ShutdownHookCallbacks.class); shutdownHookCallbacks.addCallback(() -> { watchService.ifPresent(w -> { try { w.close(); } catch (IOException e) { throw new RuntimeException(e); } }); getWatchEventsLoopThreadPool().shutdown(); }); } private static boolean isProcessingWatchEvents() { return getWatchEventsLoopThreadPool().getActiveCount() > 0; } /** * Process the {@link WatchEvent WatchEvents} loop in async execution * * @param watchService {@link WatchService} */ private void processWatchEvents(WatchService watchService) { getWatchEventsLoopThreadPool() .execute( () -> { // WatchEvents Loop while (true) { WatchKey watchKey = null; try { watchKey = watchService.take(); if (!watchKey.isValid()) { continue; } for (WatchEvent event : watchKey.pollEvents()) { WatchEvent.Kind kind = event.kind(); // configChangeType's key to match WatchEvent's Kind ConfigChangeType configChangeType = CONFIG_CHANGE_TYPES_MAP.get(kind.name()); if (configChangeType == null) { continue; } Path configDirectoryPath = (Path) watchKey.watchable(); Path currentPath = (Path) event.context(); Path configFilePath = configDirectoryPath.resolve(currentPath); File configDirectory = configDirectoryPath.toFile(); executeMutually(configDirectory, () -> { fireConfigChangeEvent( configDirectory, configFilePath.toFile(), configChangeType); signalConfigDirectory(configDirectory); return null; }); } } catch (Exception e) { return; } finally { if (watchKey != null) { // reset watchKey.reset(); } } } }); } private void signalConfigDirectory(File configDirectory) { if (isBasedPoolingWatchService()) { // remove configDirectory from processing set because it's done removeProcessingDirectory(configDirectory); // notify configDirectory notifyProcessingDirectory(configDirectory); if (logger.isDebugEnabled()) { logger.debug(format("The config rootDirectory[%s] is signalled...", configDirectory.getName())); } } } private void removeProcessingDirectory(File configDirectory) { processingDirectories.remove(configDirectory); } private void notifyProcessingDirectory(File configDirectory) { configDirectory.notifyAll(); } private List<ConfigurationListener> getListeners(File configFile) { return listenersRepository.computeIfAbsent(configFile, p -> new LinkedList<>()); } private void fireConfigChangeEvent(File configDirectory, File configFile, ConfigChangeType configChangeType) { String key = configFile.getName(); String value = getConfig(configFile); // fire ConfigChangeEvent one by one getListeners(configFile).forEach(listener -> { try { listener.process(new ConfigChangedEvent(key, configDirectory.getName(), value, configChangeType)); } catch (Throwable e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } }); } private boolean canRead(File file) { return file.exists() && file.canRead(); } @Override public Object getInternalProperty(String key) { return null; } @Override protected boolean doPublishConfig(String pathKey, String content) throws Exception { return delay(pathKey, configFile -> { FileUtils.write(configFile, content, getEncoding()); return true; }); } @Override protected String doGetConfig(String pathKey) throws Exception { File configFile = new File(pathKey); return getConfig(configFile); } @Override protected boolean doRemoveConfig(String pathKey) throws Exception { delay(pathKey, configFile -> { String content = getConfig(configFile); FileUtils.deleteQuietly(configFile); return content; }); return true; } @Override protected Collection<String> doGetConfigKeys(String groupPath) { File[] files = new File(groupPath).listFiles(File::isFile); if (files == null) { return new TreeSet<>(); } else { return Stream.of(files).map(File::getName).collect(Collectors.toList()); } } @Override protected void doAddListener(String pathKey, ConfigurationListener listener, String key, String group) { doInListener(pathKey, (configFilePath, listeners) -> { if (listeners.isEmpty()) { // If no element, it indicates watchService was registered before ThrowableConsumer.execute(configFilePath, configFile -> { FileUtils.forceMkdirParent(configFile); // A rootDirectory to be watched File configDirectory = configFile.getParentFile(); if (configDirectory != null) { // Register the configDirectory configDirectory.toPath().register(watchService.get(), INTEREST_PATH_KINDS, MODIFIERS); } }); } // Add into cache listeners.add(listener); }); } @Override protected void doRemoveListener(String pathKey, ConfigurationListener listener) { doInListener(pathKey, (file, listeners) -> { // Remove into cache listeners.remove(listener); }); } /** * Delay action for {@link #configFile(String, String) config file} * * @param configFilePath the key to represent a configuration * @param function the customized {@link Function function} with {@link File} * @param <V> the computed value * @return */ protected <V> V delay(String configFilePath, ThrowableFunction<File, V> function) { File configFile = new File(configFilePath); // Must be based on PoolingWatchService and has listeners under config file if (isBasedPoolingWatchService()) { File configDirectory = configFile.getParentFile(); executeMutually(configDirectory, () -> { if (hasListeners(configFile) && isProcessing(configDirectory)) { Integer delay = getDelay(); if (delay != null) { // wait for delay in seconds long timeout = SECONDS.toMillis(delay); if (logger.isDebugEnabled()) { logger.debug(format( "The config[path : %s] is about to delay in %d ms.", configFilePath, timeout)); } configDirectory.wait(timeout); } } addProcessing(configDirectory); return null; }); } V value = null; try { value = function.apply(configFile); } catch (Throwable e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } return value; } private boolean hasListeners(File configFile) { return getListeners(configFile).size() > 0; } /** * Is processing on {@link #buildGroupPath(String) config rootDirectory} * * @param configDirectory {@link #buildGroupPath(String) config rootDirectory} * @return if processing , return <code>true</code>, or <code>false</code> */ private boolean isProcessing(File configDirectory) { return processingDirectories.contains(configDirectory); } private void addProcessing(File configDirectory) { processingDirectories.add(configDirectory); } public Set<String> getConfigGroups() { return Stream.of(getRootDirectory().listFiles()) .filter(File::isDirectory) .map(File::getName) .collect(Collectors.toSet()); } protected String getConfig(File configFile) { return ThrowableFunction.execute( configFile, file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); } @Override protected void doClose() throws Exception {} public File getRootDirectory() { return rootDirectory; } public String getEncoding() { return encoding; } protected Integer getDelay() { return DELAY; } /** * It's whether the implementation of {@link WatchService} is based on {@linkplain sun.nio.fs.PollingWatchService} * or not. * <p> * * @return if based, return <code>true</code>, or <code>false</code> * @see #detectPoolingBasedWatchService(Optional) */ protected static boolean isBasedPoolingWatchService() { return BASED_POOLING_WATCH_SERVICE; } protected static ThreadPoolExecutor getWatchEventsLoopThreadPool() { return WATCH_EVENTS_LOOP_THREAD_POOL; } protected ThreadPoolExecutor getWorkersThreadPool() { return super.getWorkersThreadPool(); } private <V> V executeMutually(final Object mutex, Callable<V> callable) { V value = null; synchronized (mutex) { try { value = callable.call(); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } } return value; } private static <T> T[] of(T... values) { return values; } private static Integer initDelay(WatchEvent.Modifier[] modifiers) { if (isBasedPoolingWatchService()) { return 2; } else { return null; } } private static WatchEvent.Modifier[] initWatchEventModifiers() { return of(); } /** * Detect the argument of {@link WatchService} is based on {@linkplain sun.nio.fs.PollingWatchService} * or not. * <p> * Some platforms do not provide the native implementation of {@link WatchService}, just use * {@linkplain sun.nio.fs.PollingWatchService} in periodic poll file modifications. * * @param watchService the instance of {@link WatchService} * @return if based, return <code>true</code>, or <code>false</code> */ private static boolean detectPoolingBasedWatchService(Optional<WatchService> watchService) { String className = watchService.map(Object::getClass).map(Class::getName).orElse(null); return POLLING_WATCH_SERVICE_CLASS_NAME.equals(className); } private static Optional<WatchService> newWatchService() { Optional<WatchService> watchService = null; FileSystem fileSystem = FileSystems.getDefault(); try { watchService = Optional.of(fileSystem.newWatchService()); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } watchService = Optional.empty(); } return watchService; } protected static File initDirectory(URL url) { String directoryPath = getParameter(url, CONFIG_CENTER_DIR_PARAM_NAME, url == null ? null : url.getPath()); File rootDirectory = null; if (!StringUtils.isBlank(directoryPath)) { rootDirectory = new File("/" + directoryPath); } if (directoryPath == null || !rootDirectory.exists()) { // If the directory does not exist rootDirectory = new File(DEFAULT_CONFIG_CENTER_DIR_PATH); } if (!rootDirectory.exists() && !rootDirectory.mkdirs()) { throw new IllegalStateException( format("Dubbo config center rootDirectory[%s] can't be created!", rootDirectory.getAbsolutePath())); } return rootDirectory; } protected static String getEncoding(URL url) { return getParameter(url, CONFIG_CENTER_ENCODING_PARAM_NAME, DEFAULT_CONFIG_CENTER_ENCODING); } private static ThreadPoolExecutor newWatchEventsLoopThreadPool() { return new ThreadPoolExecutor( THREAD_POOL_SIZE, THREAD_POOL_SIZE, 0L, MILLISECONDS, new SynchronousQueue(), new NamedThreadFactory("dubbo-config-center-watch-events-loop", true)); } }
6,807
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactory.java
/* * 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.config.configcenter.file; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; /** * File-System based {@link DynamicConfigurationFactory} implementation * * @since 2.7.5 */ public class FileSystemDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new FileSystemDynamicConfiguration(url); } }
6,808
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfigurationFactory.java
/* * 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.config.configcenter.nop; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * */ @Deprecated public class NopDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new NopDynamicConfiguration(url); } }
6,809
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfiguration.java
/* * 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.config.configcenter.nop; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * The default extension of {@link DynamicConfiguration}. If user does not specify a config center, or specifies one * that is not a valid extension, it will default to this one. */ @Deprecated public class NopDynamicConfiguration implements DynamicConfiguration { public NopDynamicConfiguration(URL url) { // no-op } @Override public Object getInternalProperty(String key) { return null; } @Override public void addListener(String key, String group, ConfigurationListener listener) { // no-op } @Override public void removeListener(String key, String group, ConfigurationListener listener) { // no-op } @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { // no-op return null; } /** * @since 2.7.5 */ @Override public boolean publishConfig(String key, String group, String content) { return true; } @Override public void close() throws Exception { // no-op } }
6,810
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtil.java
/* * 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.beanutil; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.DefaultSerializeClassChecker; import org.apache.dubbo.common.utils.LogHelper; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; public final class JavaBeanSerializeUtil { private static final Logger logger = LoggerFactory.getLogger(JavaBeanSerializeUtil.class); private static final Map<String, Class<?>> TYPES = new HashMap<String, Class<?>>(); private static final String ARRAY_PREFIX = "["; private static final String REFERENCE_TYPE_PREFIX = "L"; private static final String REFERENCE_TYPE_SUFFIX = ";"; static { TYPES.put(boolean.class.getName(), boolean.class); TYPES.put(byte.class.getName(), byte.class); TYPES.put(short.class.getName(), short.class); TYPES.put(int.class.getName(), int.class); TYPES.put(long.class.getName(), long.class); TYPES.put(float.class.getName(), float.class); TYPES.put(double.class.getName(), double.class); TYPES.put(void.class.getName(), void.class); TYPES.put("Z", boolean.class); TYPES.put("B", byte.class); TYPES.put("C", char.class); TYPES.put("D", double.class); TYPES.put("F", float.class); TYPES.put("I", int.class); TYPES.put("J", long.class); TYPES.put("S", short.class); } private JavaBeanSerializeUtil() {} public static JavaBeanDescriptor serialize(Object obj) { return serialize(obj, JavaBeanAccessor.FIELD); } public static JavaBeanDescriptor serialize(Object obj, JavaBeanAccessor accessor) { if (obj == null) { return null; } if (obj instanceof JavaBeanDescriptor) { return (JavaBeanDescriptor) obj; } IdentityHashMap<Object, JavaBeanDescriptor> cache = new IdentityHashMap<Object, JavaBeanDescriptor>(); return createDescriptorIfAbsent(obj, accessor, cache); } private static JavaBeanDescriptor createDescriptorForSerialize(Class<?> cl) { if (cl.isEnum()) { return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_ENUM); } if (cl.isArray()) { return new JavaBeanDescriptor(cl.getComponentType().getName(), JavaBeanDescriptor.TYPE_ARRAY); } if (ReflectUtils.isPrimitive(cl)) { return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); } if (Class.class.equals(cl)) { return new JavaBeanDescriptor(Class.class.getName(), JavaBeanDescriptor.TYPE_CLASS); } if (Collection.class.isAssignableFrom(cl)) { return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_COLLECTION); } if (Map.class.isAssignableFrom(cl)) { return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_MAP); } return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_BEAN); } private static JavaBeanDescriptor createDescriptorIfAbsent( Object obj, JavaBeanAccessor accessor, IdentityHashMap<Object, JavaBeanDescriptor> cache) { if (cache.containsKey(obj)) { return cache.get(obj); } if (obj instanceof JavaBeanDescriptor) { return (JavaBeanDescriptor) obj; } JavaBeanDescriptor result = createDescriptorForSerialize(obj.getClass()); cache.put(obj, result); serializeInternal(result, obj, accessor, cache); return result; } private static void serializeInternal( JavaBeanDescriptor descriptor, Object obj, JavaBeanAccessor accessor, IdentityHashMap<Object, JavaBeanDescriptor> cache) { if (obj == null || descriptor == null) { return; } if (obj.getClass().isEnum()) { descriptor.setEnumNameProperty(((Enum<?>) obj).name()); } else if (ReflectUtils.isPrimitive(obj.getClass())) { descriptor.setPrimitiveProperty(obj); } else if (Class.class.equals(obj.getClass())) { descriptor.setClassNameProperty(((Class<?>) obj).getName()); } else if (obj.getClass().isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) { Object item = Array.get(obj, i); if (item == null) { descriptor.setProperty(i, null); } else { JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache); descriptor.setProperty(i, itemDescriptor); } } } else if (obj instanceof Collection) { Collection collection = (Collection) obj; int index = 0; for (Object item : collection) { if (item == null) { descriptor.setProperty(index++, null); } else { JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache); descriptor.setProperty(index++, itemDescriptor); } } } else if (obj instanceof Map) { Map map = (Map) obj; map.forEach((key, value) -> { Object keyDescriptor = key == null ? null : createDescriptorIfAbsent(key, accessor, cache); Object valueDescriptor = value == null ? null : createDescriptorIfAbsent(value, accessor, cache); descriptor.setProperty(keyDescriptor, valueDescriptor); }); // ~ end of loop map } else { if (JavaBeanAccessor.isAccessByMethod(accessor)) { Map<String, Method> methods = ReflectUtils.getBeanPropertyReadMethods(obj.getClass()); for (Map.Entry<String, Method> entry : methods.entrySet()) { try { Object value = entry.getValue().invoke(obj); if (value == null) { continue; } JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache); descriptor.setProperty(entry.getKey(), valueDescriptor); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } // ~ end of loop method map } // ~ end of if (JavaBeanAccessor.isAccessByMethod(accessor)) if (JavaBeanAccessor.isAccessByField(accessor)) { Map<String, Field> fields = ReflectUtils.getBeanPropertyFields(obj.getClass()); for (Map.Entry<String, Field> entry : fields.entrySet()) { if (!descriptor.containsProperty(entry.getKey())) { try { Object value = entry.getValue().get(obj); if (value == null) { continue; } JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache); descriptor.setProperty(entry.getKey(), valueDescriptor); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // ~ end of loop field map } // ~ end of if (JavaBeanAccessor.isAccessByField(accessor)) } // ~ end of else } // ~ end of method serializeInternal public static Object deserialize(JavaBeanDescriptor beanDescriptor) { return deserialize(beanDescriptor, Thread.currentThread().getContextClassLoader()); } public static Object deserialize(JavaBeanDescriptor beanDescriptor, ClassLoader loader) { if (beanDescriptor == null) { return null; } IdentityHashMap<JavaBeanDescriptor, Object> cache = new IdentityHashMap<JavaBeanDescriptor, Object>(); Object result = instantiateForDeserialize(beanDescriptor, loader, cache); deserializeInternal(result, beanDescriptor, loader, cache); return result; } private static void deserializeInternal( Object result, JavaBeanDescriptor beanDescriptor, ClassLoader loader, IdentityHashMap<JavaBeanDescriptor, Object> cache) { if (beanDescriptor.isEnumType() || beanDescriptor.isClassType() || beanDescriptor.isPrimitiveType()) { return; } if (beanDescriptor.isArrayType()) { int index = 0; for (Map.Entry<Object, Object> entry : beanDescriptor) { Object item = entry.getValue(); if (item instanceof JavaBeanDescriptor) { JavaBeanDescriptor itemDescriptor = (JavaBeanDescriptor) entry.getValue(); item = instantiateForDeserialize(itemDescriptor, loader, cache); deserializeInternal(item, itemDescriptor, loader, cache); } Array.set(result, index++, item); } } else if (beanDescriptor.isCollectionType()) { Collection collection = (Collection) result; for (Map.Entry<Object, Object> entry : beanDescriptor) { Object item = entry.getValue(); if (item instanceof JavaBeanDescriptor) { JavaBeanDescriptor itemDescriptor = (JavaBeanDescriptor) entry.getValue(); item = instantiateForDeserialize(itemDescriptor, loader, cache); deserializeInternal(item, itemDescriptor, loader, cache); } collection.add(item); } } else if (beanDescriptor.isMapType()) { Map map = (Map) result; for (Map.Entry<Object, Object> entry : beanDescriptor) { Object key = entry.getKey(); Object value = entry.getValue(); if (key instanceof JavaBeanDescriptor) { JavaBeanDescriptor keyDescriptor = (JavaBeanDescriptor) entry.getKey(); key = instantiateForDeserialize(keyDescriptor, loader, cache); deserializeInternal(key, keyDescriptor, loader, cache); } if (value instanceof JavaBeanDescriptor) { JavaBeanDescriptor valueDescriptor = (JavaBeanDescriptor) entry.getValue(); value = instantiateForDeserialize(valueDescriptor, loader, cache); deserializeInternal(value, valueDescriptor, loader, cache); } map.put(key, value); } } else if (beanDescriptor.isBeanType()) { for (Map.Entry<Object, Object> entry : beanDescriptor) { String property = entry.getKey().toString(); Object value = entry.getValue(); if (value == null) { continue; } if (value instanceof JavaBeanDescriptor) { JavaBeanDescriptor valueDescriptor = (JavaBeanDescriptor) entry.getValue(); value = instantiateForDeserialize(valueDescriptor, loader, cache); deserializeInternal(value, valueDescriptor, loader, cache); } Method method = getSetterMethod(result.getClass(), property, value.getClass()); boolean setByMethod = false; try { if (method != null) { method.invoke(result, value); setByMethod = true; } } catch (Exception e) { LogHelper.warn(logger, "Failed to set property through method " + method, e); } if (!setByMethod) { try { Field field = result.getClass().getField(property); if (field != null) { field.set(result, value); } } catch (NoSuchFieldException | IllegalAccessException e1) { LogHelper.warn(logger, "Failed to set field value", e1); } } } } else { throw new IllegalArgumentException( "Unsupported type " + beanDescriptor.getClassName() + ":" + beanDescriptor.getType()); } } private static Method getSetterMethod(Class<?> cls, String property, Class<?> valueCls) { String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); Method method = null; try { method = cls.getMethod(name, valueCls); } catch (NoSuchMethodException e) { for (Method m : cls.getMethods()) { if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) { method = m; } } } if (method != null) { method.setAccessible(true); } return method; } private static Object instantiate(Class<?> cl) throws Exception { Constructor<?>[] constructors = cl.getDeclaredConstructors(); Constructor<?> constructor = null; int argc = Integer.MAX_VALUE; for (Constructor<?> c : constructors) { if (c.getParameterTypes().length < argc) { argc = c.getParameterTypes().length; constructor = c; } } if (constructor != null) { Class<?>[] paramTypes = constructor.getParameterTypes(); Object[] constructorArgs = new Object[paramTypes.length]; for (int i = 0; i < constructorArgs.length; i++) { constructorArgs[i] = getConstructorArg(paramTypes[i]); } try { constructor.setAccessible(true); return constructor.newInstance(constructorArgs); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { LogHelper.warn(logger, e.getMessage(), e); } } return cl.getDeclaredConstructor().newInstance(); } public static Object getConstructorArg(Class<?> cl) { if (boolean.class.equals(cl) || Boolean.class.equals(cl)) { return Boolean.FALSE; } if (byte.class.equals(cl) || Byte.class.equals(cl)) { return (byte) 0; } if (short.class.equals(cl) || Short.class.equals(cl)) { return (short) 0; } if (int.class.equals(cl) || Integer.class.equals(cl)) { return 0; } if (long.class.equals(cl) || Long.class.equals(cl)) { return 0L; } if (float.class.equals(cl) || Float.class.equals(cl)) { return (float) 0; } if (double.class.equals(cl) || Double.class.equals(cl)) { return (double) 0; } if (char.class.equals(cl) || Character.class.equals(cl)) { return (char) 0; } return null; } private static Object instantiateForDeserialize( JavaBeanDescriptor beanDescriptor, ClassLoader loader, IdentityHashMap<JavaBeanDescriptor, Object> cache) { if (cache.containsKey(beanDescriptor)) { return cache.get(beanDescriptor); } if (beanDescriptor.isClassType()) { try { return name2Class(loader, beanDescriptor.getClassNameProperty()); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } if (beanDescriptor.isEnumType()) { try { Class<?> enumType = name2Class(loader, beanDescriptor.getClassName()); Method method = getEnumValueOfMethod(enumType); return method.invoke(null, enumType, beanDescriptor.getEnumPropertyName()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } if (beanDescriptor.isPrimitiveType()) { return beanDescriptor.getPrimitiveProperty(); } Object result; if (beanDescriptor.isArrayType()) { Class<?> componentType; try { componentType = name2Class(loader, beanDescriptor.getClassName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } result = Array.newInstance(componentType, beanDescriptor.propertySize()); cache.put(beanDescriptor, result); } else { try { Class<?> cl = name2Class(loader, beanDescriptor.getClassName()); result = instantiate(cl); cache.put(beanDescriptor, result); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } return result; } /** * Transform the Class.forName String to Class Object. * * @param name Class.getName() * @return Class * @throws ClassNotFoundException Class.forName */ public static Class<?> name2Class(ClassLoader loader, String name) throws ClassNotFoundException { if (TYPES.containsKey(name)) { return TYPES.get(name); } if (isArray(name)) { int dimension = 0; while (isArray(name)) { ++dimension; name = name.substring(1); } Class type = name2Class(loader, name); int[] dimensions = new int[dimension]; for (int i = 0; i < dimension; i++) { dimensions[i] = 0; } return Array.newInstance(type, dimensions).getClass(); } if (isReferenceType(name)) { name = name.substring(1, name.length() - 1); } return DefaultSerializeClassChecker.getInstance().loadClass(loader, name); } private static boolean isArray(String type) { return type != null && type.startsWith(ARRAY_PREFIX); } private static boolean isReferenceType(String type) { return type != null && type.startsWith(REFERENCE_TYPE_PREFIX) && type.endsWith(REFERENCE_TYPE_SUFFIX); } private static Method getEnumValueOfMethod(Class cl) throws NoSuchMethodException { return cl.getMethod("valueOf", Class.class, String.class); } }
6,811
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java
/* * 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.beanutil; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; public final class JavaBeanDescriptor implements Serializable, Iterable<Map.Entry<Object, Object>> { private static final long serialVersionUID = -8505586483570518029L; public static final int TYPE_CLASS = 1; public static final int TYPE_ENUM = 2; public static final int TYPE_COLLECTION = 3; public static final int TYPE_MAP = 4; public static final int TYPE_ARRAY = 5; /** * @see org.apache.dubbo.common.utils.ReflectUtils#isPrimitive(Class) */ public static final int TYPE_PRIMITIVE = 6; public static final int TYPE_BEAN = 7; private static final String ENUM_PROPERTY_NAME = "name"; private static final String CLASS_PROPERTY_NAME = "name"; private static final String PRIMITIVE_PROPERTY_VALUE = "value"; /** * Used to define a type is valid. * * @see #isValidType(int) */ private static final int TYPE_MAX = TYPE_BEAN; /** * Used to define a type is valid. * * @see #isValidType(int) */ private static final int TYPE_MIN = TYPE_CLASS; private String className; private int type; private final Map<Object, Object> properties = new LinkedHashMap<>(); public JavaBeanDescriptor() {} public JavaBeanDescriptor(String className, int type) { notEmpty(className, "class name is empty"); if (!isValidType(type)) { throw new IllegalArgumentException("type [ " + type + " ] is unsupported"); } this.className = className; this.type = type; } public boolean isClassType() { return TYPE_CLASS == type; } public boolean isEnumType() { return TYPE_ENUM == type; } public boolean isCollectionType() { return TYPE_COLLECTION == type; } public boolean isMapType() { return TYPE_MAP == type; } public boolean isArrayType() { return TYPE_ARRAY == type; } public boolean isPrimitiveType() { return TYPE_PRIMITIVE == type; } public boolean isBeanType() { return TYPE_BEAN == type; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public Object setProperty(Object propertyName, Object propertyValue) { notNull(propertyName, "Property name is null"); return properties.put(propertyName, propertyValue); } public String setEnumNameProperty(String name) { if (isEnumType()) { Object result = setProperty(ENUM_PROPERTY_NAME, name); return result == null ? null : result.toString(); } throw new IllegalStateException("The instance is not a enum wrapper"); } public String getEnumPropertyName() { if (isEnumType()) { Object result = getProperty(ENUM_PROPERTY_NAME); return result == null ? null : result.toString(); } throw new IllegalStateException("The instance is not a enum wrapper"); } public String setClassNameProperty(String name) { if (isClassType()) { Object result = setProperty(CLASS_PROPERTY_NAME, name); return result == null ? null : result.toString(); } throw new IllegalStateException("The instance is not a class wrapper"); } public String getClassNameProperty() { if (isClassType()) { Object result = getProperty(CLASS_PROPERTY_NAME); return result == null ? null : result.toString(); } throw new IllegalStateException("The instance is not a class wrapper"); } public Object setPrimitiveProperty(Object primitiveValue) { if (isPrimitiveType()) { return setProperty(PRIMITIVE_PROPERTY_VALUE, primitiveValue); } throw new IllegalStateException("The instance is not a primitive type wrapper"); } public Object getPrimitiveProperty() { if (isPrimitiveType()) { return getProperty(PRIMITIVE_PROPERTY_VALUE); } throw new IllegalStateException("The instance is not a primitive type wrapper"); } public Object getProperty(Object propertyName) { notNull(propertyName, "Property name is null"); return properties.get(propertyName); } public boolean containsProperty(Object propertyName) { notNull(propertyName, "Property name is null"); return properties.containsKey(propertyName); } @Override public Iterator<Map.Entry<Object, Object>> iterator() { return properties.entrySet().iterator(); } public int propertySize() { return properties.size(); } private boolean isValidType(int type) { return TYPE_MIN <= type && type <= TYPE_MAX; } private void notNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } } private void notEmpty(String string, String message) { if (isEmpty(string)) { throw new IllegalArgumentException(message); } } private boolean isEmpty(String string) { return string == null || "".equals(string.trim()); } }
6,812
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java
/* * 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.beanutil; public enum JavaBeanAccessor { /** * Field accessor. */ FIELD, /** * Method accessor. */ METHOD, /** * Method prefer to field. */ ALL; public static boolean isAccessByMethod(JavaBeanAccessor accessor) { return METHOD.equals(accessor) || ALL.equals(accessor); } public static boolean isAccessByField(JavaBeanAccessor accessor) { return FIELD.equals(accessor) || ALL.equals(accessor); } }
6,813
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployer.java
/* * 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.deploy; import org.apache.dubbo.common.config.ReferenceCache; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.concurrent.Future; /** * Export/refer services of module */ public interface ModuleDeployer extends Deployer<ModuleModel> { void initialize() throws IllegalStateException; Future start() throws IllegalStateException; Future getStartFuture(); void stop() throws IllegalStateException; void preDestroy() throws IllegalStateException; void postDestroy() throws IllegalStateException; boolean isInitialized(); ReferenceCache getReferenceCache(); void prepare(); void setPending(); /** * Whether start in background, do not await finish */ boolean isBackground(); }
6,814
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.java
/* * 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.deploy; import org.apache.dubbo.rpc.model.ScopeModel; public class DeployListenerAdapter<E extends ScopeModel> implements DeployListener<E> { @Override public void onInitialize(E scopeModel) {} @Override public void onStarting(E scopeModel) {} @Override public void onStarted(E scopeModel) {} @Override public void onStopping(E scopeModel) {} @Override public void onStopped(E scopeModel) {} @Override public void onFailure(E scopeModel, Throwable cause) {} }
6,815
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployer.java
/* * 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.deploy; import org.apache.dubbo.common.config.ReferenceCache; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.concurrent.Future; /** * initialize and start application instance */ public interface ApplicationDeployer extends Deployer<ApplicationModel> { /** * Initialize the component */ void initialize() throws IllegalStateException; /** * Starts the component. * @return */ Future start() throws IllegalStateException; /** * Stops the component. */ void stop() throws IllegalStateException; Future getStartFuture(); /** * Register application instance and start internal services */ void prepareApplicationInstance(); /** * Register application instance and start internal services */ void prepareInternalModule(); /** * Pre-processing before destroy model */ void preDestroy(); /** * Post-processing after destroy model */ void postDestroy(); /** * Indicates that the Application is initialized or not. */ boolean isInitialized(); ApplicationModel getApplicationModel(); ReferenceCache getReferenceCache(); /** * Whether start in background, do not await finish */ boolean isBackground(); /** * check all module state and update application state */ void checkState(ModuleModel moduleModel, DeployState moduleState); /** * module state changed callbacks */ void notifyModuleChanged(ModuleModel moduleModel, DeployState state); /** * refresh service instance */ void refreshServiceInstance(); /** * Increase the count of service update threads. * NOTE: should call ${@link ApplicationDeployer#decreaseServiceRefreshCount()} after update finished */ void increaseServiceRefreshCount(); /** * Decrease the count of service update threads */ void decreaseServiceRefreshCount(); }
6,816
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.java
/* * 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.deploy; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ModuleModel; /** * Module deploy listener */ @SPI(scope = ExtensionScope.MODULE) public interface ModuleDeployListener extends DeployListener<ModuleModel> {}
6,817
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployState.java
/* * 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.deploy; /** * Deploy state enum */ public enum DeployState { /** * Unknown state */ UNKNOWN, /** * Pending, wait for start */ PENDING, /** * Starting */ STARTING, /** * Started */ STARTED, /** * Stopping */ STOPPING, /** * Stopped */ STOPPED, /** * Failed */ FAILED }
6,818
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.java
/* * 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.deploy; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ApplicationModel; /** * Listen for Dubbo application deployment events */ @SPI(scope = ExtensionScope.APPLICATION) public interface ApplicationDeployListener extends DeployListener<ApplicationModel> { default void onModuleStarted(ApplicationModel applicationModel) {} }
6,819
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/Deployer.java
/* * 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.deploy; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.concurrent.Future; public interface Deployer<E extends ScopeModel> { /** * Initialize the component */ void initialize() throws IllegalStateException; /** * Starts the component. * @return */ Future start() throws IllegalStateException; /** * Stops the component. */ void stop() throws IllegalStateException; /** * @return true if the component is added and waiting to start */ boolean isPending(); /** * @return true if the component is starting or has been started. */ boolean isRunning(); /** * @return true if the component has been started. * @see #start() * @see #isStarting() */ boolean isStarted(); /** * @return true if the component is starting. * @see #isStarted() */ boolean isStarting(); /** * @return true if the component is stopping. * @see #isStopped() */ boolean isStopping(); /** * @return true if the component is stopping. * @see #isStopped() */ boolean isStopped(); /** * @return true if the component has failed to start or has failed to stop. */ boolean isFailed(); /** * @return current state */ DeployState getState(); void addDeployListener(DeployListener<E> listener); void removeDeployListener(DeployListener<E> listener); Throwable getError(); }
6,820
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.java
/* * 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.deploy; import org.apache.dubbo.rpc.model.ScopeModel; public interface DeployListener<E extends ScopeModel> { /** * Useful to inject some configuration like MetricsConfig, RegistryConfig, etc. */ void onInitialize(E scopeModel); void onStarting(E scopeModel); void onStarted(E scopeModel); void onStopping(E scopeModel); void onStopped(E scopeModel); void onFailure(E scopeModel, Throwable cause); }
6,821
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java
/* * 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.deploy; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION; import static org.apache.dubbo.common.deploy.DeployState.FAILED; import static org.apache.dubbo.common.deploy.DeployState.PENDING; import static org.apache.dubbo.common.deploy.DeployState.STARTED; import static org.apache.dubbo.common.deploy.DeployState.STARTING; import static org.apache.dubbo.common.deploy.DeployState.STOPPED; import static org.apache.dubbo.common.deploy.DeployState.STOPPING; public abstract class AbstractDeployer<E extends ScopeModel> implements Deployer<E> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractDeployer.class); private volatile DeployState state = PENDING; private volatile Throwable lastError; protected volatile boolean initialized = false; protected List<DeployListener<E>> listeners = new CopyOnWriteArrayList<>(); private E scopeModel; public AbstractDeployer(E scopeModel) { this.scopeModel = scopeModel; } @Override public boolean isPending() { return state == PENDING; } @Override public boolean isRunning() { return state == STARTING || state == STARTED; } @Override public boolean isStarted() { return state == STARTED; } @Override public boolean isStarting() { return state == STARTING; } @Override public boolean isStopping() { return state == STOPPING; } @Override public boolean isStopped() { return state == STOPPED; } @Override public boolean isFailed() { return state == FAILED; } @Override public DeployState getState() { return state; } @Override public void addDeployListener(DeployListener<E> listener) { listeners.add(listener); } @Override public void removeDeployListener(DeployListener<E> listener) { listeners.remove(listener); } public void setPending() { this.state = PENDING; } protected void setStarting() { this.state = STARTING; for (DeployListener<E> listener : listeners) { try { listener.onStarting(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle starting event", e); } } } protected void setStarted() { this.state = STARTED; for (DeployListener<E> listener : listeners) { try { listener.onStarted(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle started event", e); } } } protected void setStopping() { this.state = STOPPING; for (DeployListener<E> listener : listeners) { try { listener.onStopping(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopping event", e); } } } protected void setStopped() { this.state = STOPPED; for (DeployListener<E> listener : listeners) { try { listener.onStopped(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopped event", e); } } } protected void setFailed(Throwable error) { this.state = FAILED; this.lastError = error; for (DeployListener<E> listener : listeners) { try { listener.onFailure(scopeModel, error); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle failed event", e); } } } @Override public Throwable getError() { return lastError; } public boolean isInitialized() { return initialized; } protected String getIdentifier() { return scopeModel.getDesc(); } }
6,822
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java
/* * 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.constants; /** * QosConstants */ public interface QosConstants { String QOS_ENABLE = "qos.enable"; String QOS_CHECK = "qos.check"; String QOS_HOST = "qos.host"; String QOS_PORT = "qos.port"; String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip"; String ACCEPT_FOREIGN_IP_WHITELIST = "qos.accept.foreign.ip.whitelist"; String ANONYMOUS_ACCESS_PERMISSION_LEVEL = "qos.anonymous.access.permission.level"; String ANONYMOUS_ACCESS_ALLOW_COMMANDS = "qos.anonymous.access.allow.commands"; String QOS_ENABLE_COMPATIBLE = "qos-enable"; String QOS_HOST_COMPATIBLE = "qos-host"; String QOS_PORT_COMPATIBLE = "qos-port"; String ACCEPT_FOREIGN_IP_COMPATIBLE = "qos-accept-foreign-ip"; String ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE = "qos-accept-foreign-ip-whitelist"; String ANONYMOUS_ACCESS_PERMISSION_LEVEL_COMPATIBLE = "qos-anonymous-access-permission-level"; }
6,823
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java
/* * 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.constants; public interface RegistryConstants { String REGISTRY_KEY = "registry"; String REGISTRY_CLUSTER_KEY = "REGISTRY_CLUSTER"; String REGISTRY_CLUSTER_TYPE_KEY = "registry-cluster-type"; String REGISTRY_PROTOCOL = "registry"; String DYNAMIC_KEY = "dynamic"; String CATEGORY_KEY = "category"; String PROVIDERS_CATEGORY = "providers"; String CONSUMERS_CATEGORY = "consumers"; String ROUTERS_CATEGORY = "routers"; String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters"; String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; String CONFIGURATORS_CATEGORY = "configurators"; String ALL_CATEGORIES = "providers,configurators,routers"; String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators"; String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"; String ROUTERS_SUFFIX = ".routers"; String EMPTY_PROTOCOL = "empty"; String ROUTE_PROTOCOL = "route"; String ROUTE_SCRIPT_PROTOCOL = "script"; String OVERRIDE_PROTOCOL = "override"; String COMPATIBLE_CONFIG_KEY = "compatible_config"; String REGISTER_MODE_KEY = "register-mode"; String DUBBO_REGISTER_MODE_DEFAULT_KEY = "dubbo.application.register-mode"; String DUBBO_PUBLISH_INTERFACE_DEFAULT_KEY = "dubbo.application.publish-interface"; String DUBBO_PUBLISH_INSTANCE_DEFAULT_KEY = "dubbo.application.publish-instance"; String DEFAULT_REGISTER_MODE_INTERFACE = "interface"; String DEFAULT_REGISTER_MODE_INSTANCE = "instance"; String DEFAULT_REGISTER_MODE_ALL = "all"; /** * The parameter key of Dubbo Registry type * * @since 2.7.5 */ String REGISTRY_TYPE_KEY = "registry-type"; /** * The parameter value of Service-Oriented Registry type * * @since 2.7.5 */ String SERVICE_REGISTRY_TYPE = "service"; /** * The protocol for Service Discovery * * @since 2.7.5 */ String SERVICE_REGISTRY_PROTOCOL = "service-discovery-registry"; /** * Specify registry level services consumer needs to subscribe to, multiple values should be separated using ",". */ String SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services"; String PROVIDED_BY = "provided-by"; /** * The provider tri port * * @since 3.1.0 */ String PROVIDER_PORT = "provider-port"; /** * provider namespace * * @since 3.1.1 */ String PROVIDER_NAMESPACE = "provider-namespace"; /** * The request size of service instances * * @since 2.7.5 */ String INSTANCES_REQUEST_SIZE_KEY = "instances-request-size"; /** * The default request size of service instances */ int DEFAULT_INSTANCES_REQUEST_SIZE = 100; String ACCEPTS_KEY = "accepts"; String REGISTRY_ZONE = "registry_zone"; String REGISTRY_ZONE_FORCE = "registry_zone_force"; String ZONE_KEY = "zone"; String REGISTRY_SERVICE_REFERENCE_PATH = "org.apache.dubbo.registry.RegistryService"; String INIT = "INIT"; float DEFAULT_HASHMAP_LOAD_FACTOR = 0.75f; String ENABLE_EMPTY_PROTECTION_KEY = "enable-empty-protection"; boolean DEFAULT_ENABLE_EMPTY_PROTECTION = false; String REGISTER_CONSUMER_URL_KEY = "register-consumer-url"; }
6,824
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ProviderConstants.java
/* * 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.constants; /** * Provider Constants */ public interface ProviderConstants { /** * Default prefer serialization,multiple separated by commas */ String DEFAULT_PREFER_SERIALIZATION = "fastjson2,hessian2"; }
6,825
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java
/* * 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.constants; /** * RemotingConstants */ public interface RemotingConstants { String BACKUP_KEY = "backup"; }
6,826
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java
/* * 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.constants; import org.apache.dubbo.common.URL; import java.net.NetworkInterface; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; public interface CommonConstants { String DUBBO = "dubbo"; String TRIPLE = "tri"; String PROVIDER = "provider"; String CONSUMER = "consumer"; String CALLBACK = "callback"; String APPLICATION_KEY = "application"; String APPLICATION_VERSION_KEY = "application.version"; String APPLICATION_PROTOCOL_KEY = "application-protocol"; String METADATA_SERVICE_PORT_KEY = "metadata-service-port"; String METADATA_SERVICE_PROTOCOL_KEY = "metadata-service-protocol"; String METRICS_SERVICE_PORT_KEY = "metrics-service-port"; String METRICS_SERVICE_PROTOCOL_KEY = "metrics-service-protocol"; String LIVENESS_PROBE_KEY = "liveness-probe"; String READINESS_PROBE_KEY = "readiness-probe"; String STARTUP_PROBE = "startup-probe"; String REMOTE_APPLICATION_KEY = "remote.application"; String ENABLED_KEY = "enabled"; String DISABLED_KEY = "disabled"; String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; String DUBBO_MIGRATION_KEY = "dubbo.migration.file"; String DUBBO_MIGRATION_FILE_ENABLE = "dubbo.migration-file.enable"; String DEFAULT_DUBBO_MIGRATION_FILE = "dubbo-migration.yaml"; String ANY_VALUE = "*"; /** * @since 2.7.8 */ char COMMA_SEPARATOR_CHAR = ','; String COMMA_SEPARATOR = ","; String DOT_SEPARATOR = "."; Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*"); String PATH_SEPARATOR = "/"; String PROTOCOL_SEPARATOR = "://"; String PROTOCOL_SEPARATOR_ENCODED = URL.encode(PROTOCOL_SEPARATOR); String REGISTRY_SEPARATOR = "|"; Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*"); Pattern D_REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|]+\\s*"); String SEMICOLON_SEPARATOR = ";"; Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*"); Pattern EQUAL_SPLIT_PATTERN = Pattern.compile("\\s*[=]+\\s*"); String DEFAULT_PROXY = "javassist"; String DEFAULT_DIRECTORY = "dubbo"; String PROTOCOL_KEY = "protocol"; String DEFAULT_PROTOCOL = "dubbo"; String DEFAULT_THREAD_NAME = "Dubbo"; int DEFAULT_CORE_THREADS = 0; int DEFAULT_THREADS = 200; String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); String CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY = "CONSUMER_SHARED_SERVICE_EXECUTOR"; String THREADPOOL_KEY = "threadpool"; String THREAD_NAME_KEY = "threadname"; String CORE_THREADS_KEY = "corethreads"; String THREAD_POOL_EXHAUSTED_LISTENERS_KEY = "thread-pool-exhausted-listeners"; String THREADS_KEY = "threads"; String QUEUES_KEY = "queues"; String ALIVE_KEY = "alive"; String DEFAULT_THREADPOOL = "limited"; String DEFAULT_CLIENT_THREADPOOL = "cached"; String IO_THREADS_KEY = "iothreads"; String KEEP_ALIVE_KEY = "keep.alive"; int DEFAULT_QUEUES = 0; int DEFAULT_ALIVE = 60 * 1000; String TIMEOUT_KEY = "timeout"; int DEFAULT_TIMEOUT = 1000; String SESSION_KEY = "session"; // used by invocation attachments to transfer timeout from Consumer to Provider. // works as a replacement of TIMEOUT_KEY on wire, which seems to be totally useless in previous releases). String TIMEOUT_ATTACHMENT_KEY = "_TO"; String TIMEOUT_ATTACHMENT_KEY_LOWER = "_to"; String TIME_COUNTDOWN_KEY = "timeout-countdown"; String ENABLE_TIMEOUT_COUNTDOWN_KEY = "enable-timeout-countdown"; String REMOVE_VALUE_PREFIX = "-"; String PROPERTIES_CHAR_SEPARATOR = "-"; String UNDERLINE_SEPARATOR = "_"; String SEPARATOR_REGEX = "_|-"; String GROUP_CHAR_SEPARATOR = ":"; String HIDE_KEY_PREFIX = "."; String DOT_REGEX = "\\."; String DEFAULT_KEY_PREFIX = "default."; String DEFAULT_KEY = "default"; String PREFERRED_KEY = "preferred"; /** * Default timeout value in milliseconds for server shutdown */ int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; String SIDE_KEY = "side"; String PROVIDER_SIDE = "provider"; String CONSUMER_SIDE = "consumer"; String ANYHOST_KEY = "anyhost"; String ANYHOST_VALUE = "0.0.0.0"; String LOCALHOST_KEY = "localhost"; String LOCALHOST_VALUE = "127.0.0.1"; String METHODS_KEY = "methods"; String METHOD_KEY = "method"; String PID_KEY = "pid"; String TIMESTAMP_KEY = "timestamp"; String GROUP_KEY = "group"; String PATH_KEY = "path"; String ADDRESS_KEY = "address"; String INTERFACE_KEY = "interface"; String FILE_KEY = "file"; String FILTER_KEY = "filter"; String DUMP_DIRECTORY = "dump.directory"; String DUMP_ENABLE = "dump.enable"; String CLASSIFIER_KEY = "classifier"; String VERSION_KEY = "version"; String REVISION_KEY = "revision"; String METADATA_KEY = "metadata-type"; String REPORT_METADATA_KEY = "report-metadata"; String REPORT_DEFINITION_KEY = "report-definition"; String DEFAULT_METADATA_STORAGE_TYPE = "local"; String REMOTE_METADATA_STORAGE_TYPE = "remote"; String INTERFACE_REGISTER_MODE = "interface"; String INSTANCE_REGISTER_MODE = "instance"; String DEFAULT_REGISTER_MODE = "all"; String GENERIC_KEY = "generic"; /** * The composite metadata storage type includes {@link #DEFAULT_METADATA_STORAGE_TYPE "local"} and * {@link #REMOTE_METADATA_STORAGE_TYPE "remote"}. * * @since 2.7.8 */ String COMPOSITE_METADATA_STORAGE_TYPE = "composite"; /** * Consumer side 's proxy class */ String PROXY_CLASS_REF = "refClass"; /** * generic call */ String $INVOKE = "$invoke"; String $INVOKE_ASYNC = "$invokeAsync"; String GENERIC_PARAMETER_DESC = "Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;"; /** * echo call */ String $ECHO = "$echo"; /** * package version in the manifest */ String RELEASE_KEY = "release"; String PROTOBUF_MESSAGE_CLASS_NAME = "com.google.protobuf.Message"; int MAX_PROXY_COUNT = 65535; String MONITOR_KEY = "monitor"; String BACKGROUND_KEY = "background"; String CLUSTER_KEY = "cluster"; String USERNAME_KEY = "username"; String PASSWORD_KEY = "password"; String HOST_KEY = "host"; String PORT_KEY = "port"; String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND"; /** * broadcast cluster. */ String BROADCAST_CLUSTER = "broadcast"; /** * The property name for {@link NetworkInterface#getDisplayName() the name of network interface} that * the Dubbo application prefers * * @since 2.7.6 */ String DUBBO_PREFERRED_NETWORK_INTERFACE = "dubbo.network.interface.preferred"; @Deprecated String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; String DUBBO_PROTOCOL = "dubbo"; String DUBBO_LABELS = "dubbo.labels"; String DUBBO_ENV_KEYS = "dubbo.env.keys"; String CONFIG_CONFIGFILE_KEY = "config-file"; String CONFIG_ENABLE_KEY = "highest-priority"; String CONFIG_NAMESPACE_KEY = "namespace"; String CHECK_KEY = "check"; String BACKLOG_KEY = "backlog"; String HEARTBEAT_EVENT = null; String MOCK_HEARTBEAT_EVENT = "H"; String READONLY_EVENT = "R"; String WRITEABLE_EVENT = "W"; String REFERENCE_FILTER_KEY = "reference.filter"; String HEADER_FILTER_KEY = "header.filter"; String INVOCATION_INTERCEPTOR_KEY = "invocation.interceptor"; String INVOKER_LISTENER_KEY = "invoker.listener"; String REGISTRY_PROTOCOL_LISTENER_KEY = "registry.protocol.listener"; String DUBBO_VERSION_KEY = "dubbo"; String TAG_KEY = "dubbo.tag"; /** * To decide whether to make connection when the client is created */ String LAZY_CONNECT_KEY = "lazy"; String STUB_EVENT_KEY = "dubbo.stub.event"; String REFERENCE_INTERCEPTOR_KEY = "reference.interceptor"; String SERVICE_FILTER_KEY = "service.filter"; String EXPORTER_LISTENER_KEY = "exporter.listener"; /** * After simplify the registry, should add some parameter individually for provider. * * @since 2.7.0 */ String EXTRA_KEYS_KEY = "extra-keys"; String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; String GENERIC_SERIALIZATION_GSON = "gson"; String GENERIC_SERIALIZATION_DEFAULT = "true"; String GENERIC_SERIALIZATION_BEAN = "bean"; String GENERIC_RAW_RETURN = "raw.return"; String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json"; String GENERIC_WITH_CLZ_KEY = "generic.include.class"; /** * Whether to cache locally, default is true */ String REGISTRY_LOCAL_FILE_CACHE_ENABLED = "file-cache"; String METADATA_INFO_CACHE_EXPIRE_KEY = "metadata-info-cache.expire"; int DEFAULT_METADATA_INFO_CACHE_EXPIRE = 10 * 60 * 1000; String METADATA_INFO_CACHE_SIZE_KEY = "metadata-info-cache.size"; int DEFAULT_METADATA_INFO_CACHE_SIZE = 16; /** * The limit of callback service instances for one interface on every client */ String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; /** * The default limit number for callback service instances * * @see #CALLBACK_INSTANCES_LIMIT_KEY */ int DEFAULT_CALLBACK_INSTANCES = 1; String LOADBALANCE_KEY = "loadbalance"; String DEFAULT_LOADBALANCE = "random"; String RETRIES_KEY = "retries"; String FORKS_KEY = "forks"; int DEFAULT_RETRIES = 2; int DEFAULT_FAILBACK_TIMES = 3; String INTERFACES = "interfaces"; String SSL_ENABLED_KEY = "ssl-enabled"; String SERVICE_PATH_PREFIX = "service.path.prefix"; String PROTOCOL_SERVER_SERVLET = "servlet"; String PROTOCOL_SERVER = "server"; String IPV6_KEY = "ipv6"; /** * The parameter key for the class path of the ServiceNameMapping {@link Properties} file * * @since 2.7.8 */ String SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY = "service-name-mapping.properties-path"; /** * The default class path of the ServiceNameMapping {@link Properties} file * * @since 2.7.8 */ String DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH = "META-INF/dubbo/service-name-mapping.properties"; String CLASS_DESERIALIZE_BLOCK_ALL = "dubbo.security.serialize.blockAllClassExceptAllow"; String CLASS_DESERIALIZE_ALLOWED_LIST = "dubbo.security.serialize.allowedClassList"; String CLASS_DESERIALIZE_BLOCKED_LIST = "dubbo.security.serialize.blockedClassList"; String ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE = "dubbo.security.serialize.generic.native-java-enable"; String SERIALIZE_BLOCKED_LIST_FILE_PATH = "security/serialize.blockedlist"; String SERIALIZE_ALLOW_LIST_FILE_PATH = "security/serialize.allowlist"; String SERIALIZE_CHECK_STATUS_KEY = "dubbo.application.serialize-check-status"; String QOS_LIVE_PROBE_EXTENSION = "dubbo.application.liveness-probe"; String QOS_READY_PROBE_EXTENSION = "dubbo.application.readiness-probe"; String QOS_STARTUP_PROBE_EXTENSION = "dubbo.application.startup-probe"; String REGISTRY_DELAY_NOTIFICATION_KEY = "delay-notification"; String CACHE_CLEAR_TASK_INTERVAL = "dubbo.application.url.cache.task.interval"; String CACHE_CLEAR_WAITING_THRESHOLD = "dubbo.application.url.cache.clear.waiting"; String CLUSTER_INTERCEPTOR_COMPATIBLE_KEY = "dubbo.application.cluster.interceptor.compatible"; String UTF8ENCODE = "UTF-8"; /** * Pseudo URL prefix for loading from the class path: "classpath:". */ String CLASSPATH_URL_PREFIX = "classpath:"; String DEFAULT_VERSION = "0.0.0"; String CLASS_DESERIALIZE_OPEN_CHECK = "dubbo.security.serialize.openCheckClass"; String ROUTER_KEY = "router"; String EXPORT_ASYNC_KEY = "export-async"; String REFER_ASYNC_KEY = "refer-async"; String EXPORT_BACKGROUND_KEY = "export-background"; String REFER_BACKGROUND_KEY = "refer-background"; String EXPORT_THREAD_NUM_KEY = "export-thread-num"; String REFER_THREAD_NUM_KEY = "refer-thread-num"; int DEFAULT_EXPORT_THREAD_NUM = 10; int DEFAULT_REFER_THREAD_NUM = 10; int DEFAULT_DELAY_NOTIFICATION_TIME = 5000; int DEFAULT_DELAY_EXECUTE_TIMES = 10; /** * Url merge processor key */ String URL_MERGE_PROCESSOR_KEY = "url-merge-processor"; /** * use native image to compile dubbo's identifier */ String NATIVE = "native"; String DUBBO_MONITOR_ADDRESS = "dubbo.monitor.address"; String SERVICE_NAME_MAPPING_KEY = "service-name-mapping"; String SCOPE_MODEL = "scopeModel"; String SERVICE_MODEL = "serviceModel"; /** * The property name for {@link NetworkInterface#getDisplayName() the name of network interface} that * the Dubbo application will be ignored * * @since 2.7.6 */ String DUBBO_NETWORK_IGNORED_INTERFACE = "dubbo.network.interface.ignored"; String OS_NAME_KEY = "os.name"; String OS_LINUX_PREFIX = "linux"; String OS_WIN_PREFIX = "win"; String RECONNECT_TASK_TRY_COUNT = "dubbo.reconnect.reconnectTaskTryCount"; int DEFAULT_RECONNECT_TASK_TRY_COUNT = 10; String RECONNECT_TASK_PERIOD = "dubbo.reconnect.reconnectTaskPeriod"; int DEFAULT_RECONNECT_TASK_PERIOD = 1000; String RESELECT_COUNT = "dubbo.reselect.count"; int DEFAULT_RESELECT_COUNT = 10; String ENABLE_CONNECTIVITY_VALIDATION = "dubbo.connectivity.validation"; String DUBBO_INTERNAL_APPLICATION = "DUBBO_INTERNAL_APPLICATION"; String RETRY_TIMES_KEY = "retry-times"; String RETRY_PERIOD_KEY = "retry-period"; String SYNC_REPORT_KEY = "sync-report"; String CYCLE_REPORT_KEY = "cycle-report"; String WORKING_CLASSLOADER_KEY = "WORKING_CLASSLOADER"; String STAGED_CLASSLOADER_KEY = "STAGED_CLASSLOADER"; String PROVIDER_ASYNC_KEY = "PROVIDER_ASYNC"; String REGISTER_IP_KEY = "register.ip"; String CURRENT_CLUSTER_INVOKER_KEY = "currentClusterInvoker"; String ENABLE_ROUTER_SNAPSHOT_PRINT_KEY = "ENABLE_ROUTER_SNAPSHOT_PRINT"; String INJVM_COPY_UTIL_KEY = "injvm-copy-util"; String INJVM_IGNORE_SAME_MODULE_KEY = "injvm.ignore.same-module"; String SET_FUTURE_IN_SYNC_MODE = "future.sync.set"; String CLEAR_FUTURE_AFTER_GET = "future.clear.once"; String NATIVE_STUB = "nativestub"; String METADATA = "metadata"; String IGNORE_LISTEN_SHUTDOWN_HOOK = "dubbo.shutdownHook.listenIgnore"; String OPTIMIZER_KEY = "optimizer"; String PREFER_JSON_FRAMEWORK_NAME = "dubbo.json-framework.prefer"; /** * @since 3.1.0 */ String MESH_ENABLE = "mesh-enable"; /** * @since 3.1.0 */ Integer DEFAULT_MESH_PORT = 80; /** * @since 3.1.0 */ String SVC = ".svc."; /** * Domain name suffix used inside k8s. * * @since 3.1.0 */ String DEFAULT_CLUSTER_DOMAIN = "cluster.local"; /** * @since 3.1.0 */ String UNLOAD_CLUSTER_RELATED = "unloadClusterRelated"; /** * used for thread isolation between services */ String SERVICE_EXECUTOR = "service-executor"; String EXECUTOR_MANAGEMENT_MODE = "executor-management-mode"; String EXECUTOR_MANAGEMENT_MODE_DEFAULT = "default"; String EXECUTOR_MANAGEMENT_MODE_ISOLATION = "isolation"; /** * * used in JVMUtil.java ,Control stack print lines, default is 32 lines * */ String DUBBO_JSTACK_MAXLINE = "dubbo.jstack-dump.max-line"; String ENCODE_IN_IO_THREAD_KEY = "encode.in.io"; boolean DEFAULT_ENCODE_IN_IO_THREAD = false; /** * @since 3.2.0 */ String BYTE_ACCESSOR_KEY = "byte.accessor"; String PAYLOAD = "payload"; String DUBBO_METRICS_CONFIGCENTER_ENABLE = "dubbo.metrics.configcenter.enable"; Integer TRI_EXCEPTION_CODE_NOT_EXISTS = 0; String PACKABLE_METHOD_FACTORY_KEY = "serialize.packable.factory"; String DUBBO_PACKABLE_METHOD_FACTORY = "dubbo.application.parameters." + PACKABLE_METHOD_FACTORY_KEY; String DUBBO_MANUAL_REGISTER_KEY = "dubbo.application.manual-register"; String DUBBO2_COMPACT_ENABLE = "dubbo.compact.enable"; }
6,827
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java
/* * 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.constants; /** * <p>Constants of Error Codes used in logger. * * <p>Format: <i>[Category]-[Code]</i>, where: * <li>[Category] is the category code which identifies the module. * <li>[Code] is the detailed code. * <li>Every blanks should be filled with positive number. * * <br /><br /> * <p>Hint: * <li>Synchronize this file across different branches. (Use merge and cherry-pick.) * <li>Double-check the usage in different branches before deleting any of the error code. * <li>If applicable, use error code that already appears in this file. * <li>If it's required to add an error code, find an error code that's marked by 'Absent', and rename it. (so that no code is wasted) * <li>Update the corresponding file in dubbo-website repository. */ public interface LoggerCodeConstants { // Common module String COMMON_THREAD_POOL_EXHAUSTED = "0-1"; String COMMON_PROPERTY_TYPE_MISMATCH = "0-2"; String COMMON_CACHE_PATH_INACCESSIBLE = "0-3"; String COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED = "0-4"; String COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED = "0-5"; String COMMON_THREAD_INTERRUPTED_EXCEPTION = "0-6"; String COMMON_CLASS_NOT_FOUND = "0-7"; String COMMON_REFLECTIVE_OPERATION_FAILED = "0-8"; String COMMON_FAILED_NOTIFY_EVENT = "0-9"; String COMMON_UNSUPPORTED_INVOKER = "0-10"; String COMMON_FAILED_STOP_HTTP_SERVER = "0-11"; String COMMON_UNEXPECTED_EXCEPTION = "0-12"; String COMMON_METRICS_COLLECTOR_EXCEPTION = "0-13"; String COMMON_MONITOR_EXCEPTION = "0-14"; String COMMON_ERROR_LOAD_EXTENSION = "0-15"; String COMMON_EXECUTORS_NO_FOUND = "0-16"; String COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN = "0-17"; String COMMON_ERROR_USE_THREAD_POOL = "0-18"; String COMMON_ERROR_RUN_THREAD_TASK = "0-19"; String COMMON_UNEXPECTED_CREATE_DUMP = "0-20"; String COMMON_ERROR_TOO_MANY_INSTANCES = "0-21"; String COMMON_IO_EXCEPTION = "0-22"; String COMMON_JSON_CONVERT_EXCEPTION = "0-23"; String COMMON_FAILED_OVERRIDE_FIELD = "0-24"; String COMMON_FAILED_LOAD_MAPPING_CACHE = "0-25"; String COMMON_METADATA_PROCESSOR = "0-26"; String COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR = "0-27"; String VULNERABILITY_WARNING = "0-28"; // Registry module String REGISTRY_ADDRESS_INVALID = "1-1"; /** * Absent. Merged with 0-2. */ String REGISTRY_ABSENCE = "1-2"; String REGISTRY_FAILED_URL_EVICTING = "1-3"; String REGISTRY_EMPTY_ADDRESS = "1-4"; String REGISTRY_NO_PARAMETERS_URL = "1-5"; String REGISTRY_FAILED_CLEAR_CACHED_URLS = "1-6"; String REGISTRY_FAILED_NOTIFY_EVENT = "1-7"; String REGISTRY_FAILED_DESTROY_UNREGISTER_URL = "1-8"; String REGISTRY_FAILED_READ_WRITE_CACHE_FILE = "1-9"; String REGISTRY_FAILED_DELETE_LOCKFILE = "1-10"; String REGISTRY_FAILED_CREATE_INSTANCE = "1-11"; String REGISTRY_FAILED_FETCH_INSTANCE = "1-12"; String REGISTRY_EXECUTE_RETRYING_TASK = "1-13"; String REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG = "1-14"; String REGISTRY_FAILED_DESTROY_SERVICE = "1-15"; String REGISTRY_UNSUPPORTED_CATEGORY = "1-16"; String REGISTRY_FAILED_REFRESH_ADDRESS = "1-17"; String REGISTRY_MISSING_METADATA_CONFIG_PORT = "1-18"; String REGISTRY_ERROR_LISTEN_KUBERNETES = "1-19"; String REGISTRY_UNABLE_MATCH_KUBERNETES = "1-20"; String REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES = "1-21"; String REGISTRY_UNABLE_ACCESS_KUBERNETES = "1-22"; /** * Absent. Original '1-23' is changed to '81-3'. */ String REGISTRY_FAILED_DOWNLOAD_FILE = "1-23"; /** * Absent. Original '1-24' is changed to '81-1'. */ String REGISTRY_FAILED_START_ZOOKEEPER = "1-24"; /** * Absent. Original '1-25' is changed to '81-2'. */ String REGISTRY_FAILED_STOP_ZOOKEEPER = "1-25"; String REGISTRY_FAILED_GENERATE_CERT_ISTIO = "1-26"; String REGISTRY_FAILED_GENERATE_KEY_ISTIO = "1-27"; String REGISTRY_RECEIVE_ERROR_MSG_ISTIO = "1-28"; String REGISTRY_ERROR_READ_FILE_ISTIO = "1-29"; String REGISTRY_ERROR_REQUEST_XDS = "1-30"; String REGISTRY_ERROR_RESPONSE_XDS = "1-31"; String REGISTRY_ERROR_CREATE_CHANNEL_XDS = "1-32"; String REGISTRY_ERROR_INITIALIZE_XDS = "1-33"; String REGISTRY_ERROR_PARSING_XDS = "1-34"; String REGISTRY_ZOOKEEPER_EXCEPTION = "1-35"; /** * Absent. Merged with 99-0. */ String REGISTRY_UNEXPECTED_EXCEPTION = "1-36"; String REGISTRY_NACOS_EXCEPTION = "1-37"; String REGISTRY_SOCKET_EXCEPTION = "1-38"; String REGISTRY_FAILED_LOAD_METADATA = "1-39"; String REGISTRY_ROUTER_WAIT_LONG = "1-40"; String REGISTRY_ISTIO_EXCEPTION = "1-41"; String REGISTRY_NACOS_SUB_LEGACY = "1-42"; // Cluster module 2-x String CLUSTER_FAILED_SITE_SELECTION = "2-1"; String CLUSTER_NO_VALID_PROVIDER = "2-2"; String CLUSTER_FAILED_STOP = "2-3"; String CLUSTER_FAILED_LOAD_MERGER = "2-4"; String CLUSTER_FAILED_RESELECT_INVOKERS = "2-5"; String CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY = "2-6"; String CLUSTER_FAILED_EXEC_CONDITION_ROUTER = "2-7"; String CLUSTER_ERROR_RESPONSE = "2-8"; String CLUSTER_TIMER_RETRY_FAILED = "2-9"; String CLUSTER_FAILED_INVOKE_SERVICE = "2-10"; String CLUSTER_TAG_ROUTE_INVALID = "2-11"; String CLUSTER_TAG_ROUTE_EMPTY = "2-12"; String CLUSTER_FAILED_RECEIVE_RULE = "2-13"; String CLUSTER_SCRIPT_EXCEPTION = "2-14"; String CLUSTER_FAILED_RULE_PARSING = "2-15"; String CLUSTER_FAILED_MULTIPLE_RETRIES = "2-16"; String CLUSTER_FAILED_MOCK_REQUEST = "2-17"; String CLUSTER_NO_RULE_LISTENER = "2-18"; String CLUSTER_EXECUTE_FILTER_EXCEPTION = "2-19"; String CLUSTER_FAILED_GROUP_MERGE = "2-20"; // Proxy module. 3-1 String PROXY_FAILED_CONVERT_URL = "3-1"; String PROXY_FAILED_EXPORT_SERVICE = "3-2"; /** * Absent. Merged with 3-8. */ String PROXY_33 = "3-3"; String PROXY_TIMEOUT_REQUEST = "3-4"; String PROXY_ERROR_ASYNC_RESPONSE = "3-5"; String PROXY_UNSUPPORTED_INVOKER = "3-6"; String PROXY_TIMEOUT_RESPONSE = "3-7"; String PROXY_FAILED = "3-8"; // Protocol module. String PROTOCOL_UNSUPPORTED = "4-1"; String PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER = "4-2"; String PROTOCOL_FAILED_REFER_INVOKER = "4-3"; String PROTOCOL_UNSAFE_SERIALIZATION = "4-4"; String PROTOCOL_FAILED_CLOSE_STREAM = "4-5"; String PROTOCOL_ERROR_DESERIALIZE = "4-6"; String PROTOCOL_ERROR_CLOSE_CLIENT = "4-7"; String PROTOCOL_ERROR_CLOSE_SERVER = "4-8"; String PROTOCOL_FAILED_PARSE = "4-9"; String PROTOCOL_FAILED_SERIALIZE_TRIPLE = "4-10"; String PROTOCOL_FAILED_REQUEST = "4-11"; String PROTOCOL_FAILED_CREATE_STREAM_TRIPLE = "4-12"; String PROTOCOL_TIMEOUT_SERVER = "4-13"; String PROTOCOL_FAILED_RESPONSE = "4-14"; String PROTOCOL_STREAM_LISTENER = "4-15"; String PROTOCOL_CLOSED_SERVER = "4-16"; String PROTOCOL_FAILED_DESTROY_INVOKER = "4-17"; String PROTOCOL_FAILED_LOAD_MODEL = "4-18"; String PROTOCOL_INCORRECT_PARAMETER_VALUES = "4-19"; String PROTOCOL_FAILED_DECODE = "4-20"; String PROTOCOL_UNTRUSTED_SERIALIZE_CLASS = "4-21"; // Config module String CONFIG_FAILED_CONNECT_REGISTRY = "5-1"; String CONFIG_FAILED_SHUTDOWN_HOOK = "5-2"; String CONFIG_FAILED_DESTROY_INVOKER = "5-3"; String CONFIG_NO_METHOD_FOUND = "5-4"; String CONFIG_FAILED_LOAD_ENV_VARIABLE = "5-5"; String CONFIG_PROPERTY_CONFLICT = "5-6"; String CONFIG_UNEXPORT_ERROR = "5-7"; String CONFIG_USE_RANDOM_PORT = "5-8"; String CONFIG_FAILED_EXPORT_SERVICE = "5-9"; String CONFIG_SERVER_DISCONNECTED = "5-10"; String CONFIG_REGISTER_INSTANCE_ERROR = "5-11"; String CONFIG_REFRESH_INSTANCE_ERROR = "5-12"; String CONFIG_UNABLE_DESTROY_MODEL = "5-13"; String CONFIG_FAILED_START_MODEL = "5-14"; String CONFIG_FAILED_REFERENCE_MODEL = "5-15"; String CONFIG_FAILED_FIND_PROTOCOL = "5-16"; String CONFIG_PARAMETER_FORMAT_ERROR = "5-17"; String CONFIG_FAILED_NOTIFY_EVENT = "5-18"; /** * Absent. Changed to 81-4. */ String CONFIG_ZOOKEEPER_SERVER_ERROR = "5-19"; String CONFIG_STOP_DUBBO_ERROR = "5-20"; String CONFIG_FAILED_EXECUTE_DESTROY = "5-21"; String CONFIG_FAILED_INIT_CONFIG_CENTER = "5-22"; String CONFIG_FAILED_WAIT_EXPORT_REFER = "5-23"; String CONFIG_FAILED_REFER_SERVICE = "5-24"; String CONFIG_UNDEFINED_PROTOCOL = "5-25"; String CONFIG_METADATA_SERVICE_EXPORTED = "5-26"; String CONFIG_API_WRONG_USE = "5-27"; String CONFIG_NO_ANNOTATIONS_FOUND = "5-28"; String CONFIG_NO_BEANS_SCANNED = "5-29"; String CONFIG_DUPLICATED_BEAN_DEFINITION = "5-30"; String CONFIG_WARN_STATUS_CHECKER = "5-31"; String CONFIG_FAILED_CLOSE_CONNECT_APOLLO = "5-32"; String CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO = "5-33"; String CONFIG_ERROR_NACOS = "5-34"; String CONFIG_START_DUBBO_ERROR = "5-35"; String CONFIG_FILTER_VALIDATION_EXCEPTION = "5-36"; String CONFIG_ERROR_PROCESS_LISTENER = "5-37"; String CONFIG_UNDEFINED_ARGUMENT = "5-38"; String CONFIG_DUBBO_BEAN_INITIALIZER = "5-39"; String CONFIG_DUBBO_BEAN_NOT_FOUND = "5-40"; String CONFIG_SSL_PATH_LOAD_FAILED = "5-41"; String CONFIG_SSL_CERT_GENERATE_FAILED = "5-42"; String CONFIG_SSL_CONNECT_INSECURE = "5-43"; // Transport module String TRANSPORT_FAILED_CONNECT_PROVIDER = "6-1"; String TRANSPORT_CLIENT_CONNECT_TIMEOUT = "6-2"; String TRANSPORT_FAILED_CLOSE = "6-3"; /** * Absent. Merged to 99-0. */ String TRANSPORT_UNEXPECTED_EXCEPTION = "6-4"; String TRANSPORT_FAILED_DISCONNECT_PROVIDER = "6-5"; String TRANSPORT_UNSUPPORTED_MESSAGE = "6-6"; String TRANSPORT_CONNECTION_LIMIT_EXCEED = "6-7"; String TRANSPORT_FAILED_DECODE = "6-8"; String TRANSPORT_FAILED_SERIALIZATION = "6-9"; String TRANSPORT_EXCEED_PAYLOAD_LIMIT = "6-10"; String TRANSPORT_UNSUPPORTED_CHARSET = "6-11"; String TRANSPORT_FAILED_DESTROY_ZOOKEEPER = "6-12"; String TRANSPORT_FAILED_CLOSE_STREAM = "6-13"; String TRANSPORT_FAILED_RESPONSE = "6-14"; String TRANSPORT_SKIP_UNUSED_STREAM = "6-15"; String TRANSPORT_FAILED_RECONNECT = "6-16"; // qos plugin String QOS_PROFILER_DISABLED = "7-1"; String QOS_PROFILER_ENABLED = "7-2"; String QOS_PROFILER_WARN_PERCENT = "7-3"; String QOS_FAILED_START_SERVER = "7-4"; String QOS_COMMAND_NOT_FOUND = "7-5"; String QOS_UNEXPECTED_EXCEPTION = "7-6"; String QOS_PERMISSION_DENY_EXCEPTION = "7-7"; // Testing module (8[X], where [X] is number of the module to be tested.) String TESTING_REGISTRY_FAILED_TO_START_ZOOKEEPER = "81-1"; String TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER = "81-2"; String TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE = "81-3"; String TESTING_INIT_ZOOKEEPER_SERVER_ERROR = "81-4"; // Internal unknown error. /** * Unknown internal error. (99-0) */ String INTERNAL_ERROR = "99-0"; String INTERNAL_INTERRUPTED = "99-1"; }
6,828
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java
/* * 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.constants; /** * constant for Cluster fault-tolerant mode */ public interface ClusterRules { /** * When invoke fails, log the initial error and retry other invokers * (retry n times, which means at most n different invokers will be invoked) **/ String FAIL_OVER = "failover"; /** * Execute exactly once, which means this policy will throw an exception immediately in case of an invocation error. **/ String FAIL_FAST = "failfast"; /** * When invoke fails, log the error message and ignore this error by returning an empty Result. **/ String FAIL_SAFE = "failsafe"; /** * When fails, record failure requests and schedule for retry on a regular interval. **/ String FAIL_BACK = "failback"; /** * Invoke a specific number of invokers concurrently, usually used for demanding real-time operations, but need to waste more service resources. **/ String FORKING = "forking"; /** * Call all providers by broadcast, call them one by one, and report an error if any one reports an error **/ String BROADCAST = "broadcast"; String AVAILABLE = "available"; String MERGEABLE = "mergeable"; String EMPTY = ""; }
6,829
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegisterTypeEnum.java
/* * 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.constants; /** * Indicate that a service need to be registered to registry or not */ public enum RegisterTypeEnum { /** * Never register. Cannot be registered by any command(like QoS-online). */ NEVER_REGISTER, /** * Manual register. Can be registered by command(like QoS-online), but not register by default. */ MANUAL_REGISTER, /** * (INTERNAL) Auto register by deployer. Will be registered after deployer started. * (Delay publish when starting. Prevent service from being invoked before all services are started) */ AUTO_REGISTER_BY_DEPLOYER, /** * Auto register. Will be registered when one service is exported. */ AUTO_REGISTER; }
6,830
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java
/* * 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.constants; public interface FilterConstants { String CACHE_KEY = "cache"; String VALIDATION_KEY = "validation"; }
6,831
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java
/* * 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.constants; /** * constant for Load-balance strategy */ public interface LoadbalanceRules { /** * This class select one provider from multiple providers randomly. **/ String RANDOM = "random"; /** * Round-robin load balance. **/ String ROUND_ROBIN = "roundrobin"; /** * Filter the number of invokers with the least number of active calls and count the weights and quantities of these invokers. **/ String LEAST_ACTIVE = "leastactive"; /** * Consistent Hash, requests with the same parameters are always sent to the same provider. **/ String CONSISTENT_HASH = "consistenthash"; /** * Filter the number of invokers with the shortest response time of success calls and count the weights and quantities of these invokers. **/ String SHORTEST_RESPONSE = "shortestresponse"; /** * adaptive load balance. **/ String ADAPTIVE = "adaptive"; String EMPTY = ""; }
6,832
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java
/* * 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.constants; public interface MetricsConstants { String PROTOCOL_PROMETHEUS = "prometheus"; String PROTOCOL_DEFAULT = "default"; String TAG_IP = "ip"; String TAG_PID = "pid"; String TAG_HOSTNAME = "hostname"; String TAG_APPLICATION_NAME = "application.name"; String TAG_APPLICATION_MODULE = "application.module.id"; String TAG_INTERFACE_KEY = "interface"; String TAG_METHOD_KEY = "method"; String TAG_GROUP_KEY = "group"; String TAG_VERSION_KEY = "version"; String TAG_APPLICATION_VERSION_KEY = "application.version"; String TAG_KEY_KEY = "key"; String TAG_CONFIG_CENTER = "config.center"; String TAG_CHANGE_TYPE = "change.type"; String ENABLE_JVM_METRICS_KEY = "enable.jvm"; String ENABLE_COLLECTOR_SYNC_KEY = "enable.collector.sync"; String COLLECTOR_SYNC_PERIOD_KEY = "collector.sync.period"; String AGGREGATION_COLLECTOR_KEY = "aggregation"; String AGGREGATION_ENABLED_KEY = "aggregation.enabled"; String AGGREGATION_BUCKET_NUM_KEY = "aggregation.bucket.num"; String AGGREGATION_TIME_WINDOW_SECONDS_KEY = "aggregation.time.window.seconds"; String HISTOGRAM_ENABLED_KEY = "histogram.enabled"; String PROMETHEUS_EXPORTER_ENABLED_KEY = "prometheus.exporter.enabled"; String PROMETHEUS_EXPORTER_ENABLE_HTTP_SERVICE_DISCOVERY_KEY = "prometheus.exporter.enable.http.service.discovery"; String PROMETHEUS_EXPORTER_HTTP_SERVICE_DISCOVERY_URL_KEY = "prometheus.exporter.http.service.discovery.url"; String PROMETHEUS_EXPORTER_METRICS_PORT_KEY = "prometheus.exporter.metrics.port"; String PROMETHEUS_EXPORTER_METRICS_PATH_KEY = "prometheus.exporter.metrics.path"; String PROMETHEUS_PUSHGATEWAY_ENABLED_KEY = "prometheus.pushgateway.enabled"; String PROMETHEUS_PUSHGATEWAY_BASE_URL_KEY = "prometheus.pushgateway.base.url"; String PROMETHEUS_PUSHGATEWAY_USERNAME_KEY = "prometheus.pushgateway.username"; String PROMETHEUS_PUSHGATEWAY_PASSWORD_KEY = "prometheus.pushgateway.password"; String PROMETHEUS_PUSHGATEWAY_PUSH_INTERVAL_KEY = "prometheus.pushgateway.push.interval"; String PROMETHEUS_PUSHGATEWAY_JOB_KEY = "prometheus.pushgateway.job"; int PROMETHEUS_DEFAULT_METRICS_PORT = 20888; String PROMETHEUS_DEFAULT_METRICS_PATH = "/metrics"; int PROMETHEUS_DEFAULT_PUSH_INTERVAL = 30; String PROMETHEUS_DEFAULT_JOB_NAME = "default_dubbo_job"; String METRIC_FILTER_START_TIME = "metric_filter_start_time"; String TAG_THREAD_NAME = "thread.pool.name"; }
6,833
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java
/* * Copyright 2014 The Netty Project * * The Netty Project 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.threadlocal; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; /** * The internal data structure that stores the threadLocal variables for Netty and all {@link InternalThread}s. * Note that this class is for internal use only. Use {@link InternalThread} * unless you know what you are doing. */ public final class InternalThreadLocalMap { private Object[] indexedVariables; private static ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = new ThreadLocal<InternalThreadLocalMap>(); private static final AtomicInteger NEXT_INDEX = new AtomicInteger(); static final Object UNSET = new Object(); /** * should not be modified after initialization, * do not set as final due to unit test */ // Reference: https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/ArrayList.java#l229 static int ARRAY_LIST_CAPACITY_MAX_SIZE = Integer.MAX_VALUE - 8; private static final int ARRAY_LIST_CAPACITY_EXPAND_THRESHOLD = 1 << 30; public static InternalThreadLocalMap getIfSet() { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { return ((InternalThread) thread).threadLocalMap(); } return slowThreadLocalMap.get(); } public static InternalThreadLocalMap get() { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { return fastGet((InternalThread) thread); } return slowGet(); } public static InternalThreadLocalMap getAndRemove() { try { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { return ((InternalThread) thread).threadLocalMap(); } return slowThreadLocalMap.get(); } finally { remove(); } } public static void set(InternalThreadLocalMap internalThreadLocalMap) { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { ((InternalThread) thread).setThreadLocalMap(internalThreadLocalMap); } slowThreadLocalMap.set(internalThreadLocalMap); } public static void remove() { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { ((InternalThread) thread).setThreadLocalMap(null); } else { slowThreadLocalMap.remove(); } } public static void destroy() { slowThreadLocalMap = null; } public static int nextVariableIndex() { int index = NEXT_INDEX.getAndIncrement(); if (index >= ARRAY_LIST_CAPACITY_MAX_SIZE || index < 0) { NEXT_INDEX.set(ARRAY_LIST_CAPACITY_MAX_SIZE); throw new IllegalStateException("Too many thread-local indexed variables"); } return index; } public static int lastVariableIndex() { return NEXT_INDEX.get() - 1; } private InternalThreadLocalMap() { indexedVariables = newIndexedVariableTable(); } public Object indexedVariable(int index) { Object[] lookup = indexedVariables; return index < lookup.length ? lookup[index] : UNSET; } /** * @return {@code true} if and only if a new thread-local variable has been created */ public boolean setIndexedVariable(int index, Object value) { Object[] lookup = indexedVariables; if (index < lookup.length) { Object oldValue = lookup[index]; lookup[index] = value; return oldValue == UNSET; } else { expandIndexedVariableTableAndSet(index, value); return true; } } public Object removeIndexedVariable(int index) { Object[] lookup = indexedVariables; if (index < lookup.length) { Object v = lookup[index]; lookup[index] = UNSET; return v; } else { return UNSET; } } public int size() { int count = 0; for (Object o : indexedVariables) { if (o != UNSET) { ++count; } } //the fist element in `indexedVariables` is a set to keep all the InternalThreadLocal to remove //look at method `addToVariablesToRemove` return count - 1; } private static Object[] newIndexedVariableTable() { int variableIndex = NEXT_INDEX.get(); int newCapacity = variableIndex < 32 ? 32 : newCapacity(variableIndex); Object[] array = new Object[newCapacity]; Arrays.fill(array, UNSET); return array; } private static int newCapacity(int index) { int newCapacity; if (index < ARRAY_LIST_CAPACITY_EXPAND_THRESHOLD) { newCapacity = index; newCapacity |= newCapacity >>> 1; newCapacity |= newCapacity >>> 2; newCapacity |= newCapacity >>> 4; newCapacity |= newCapacity >>> 8; newCapacity |= newCapacity >>> 16; newCapacity ++; } else { newCapacity = ARRAY_LIST_CAPACITY_MAX_SIZE; } return newCapacity; } private static InternalThreadLocalMap fastGet(InternalThread thread) { InternalThreadLocalMap threadLocalMap = thread.threadLocalMap(); if (threadLocalMap == null) { thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap()); } return threadLocalMap; } private static InternalThreadLocalMap slowGet() { ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = InternalThreadLocalMap.slowThreadLocalMap; InternalThreadLocalMap ret = slowThreadLocalMap.get(); if (ret == null) { ret = new InternalThreadLocalMap(); slowThreadLocalMap.set(ret); } return ret; } private void expandIndexedVariableTableAndSet(int index, Object value) { Object[] oldArray = indexedVariables; final int oldCapacity = oldArray.length; int newCapacity = newCapacity(index); Object[] newArray = Arrays.copyOf(oldArray, newCapacity); Arrays.fill(newArray, oldCapacity, newArray.length, UNSET); newArray[index] = value; indexedVariables = newArray; } }
6,834
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java
/* * Copyright 2014 The Netty Project * * The Netty Project 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.threadlocal; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Set; /** * InternalThreadLocal * A special variant of {@link ThreadLocal} that yields higher access performance when accessed from a * {@link InternalThread}. * <p></p> * Internally, a {@link InternalThread} uses a constant index in an array, instead of using hash code and hash table, * to look for a variable. Although seemingly very subtle, it yields slight performance advantage over using a hash * table, and it is useful when accessed frequently. * <p></p> * This design is learning from {@see io.netty.util.concurrent.FastThreadLocal} which is in Netty. */ public class InternalThreadLocal<V> extends ThreadLocal<V> { private static final int VARIABLES_TO_REMOVE_INDEX = InternalThreadLocalMap.nextVariableIndex(); private final int index; public InternalThreadLocal() { index = InternalThreadLocalMap.nextVariableIndex(); } /** * Removes all {@link InternalThreadLocal} variables bound to the current thread. This operation is useful when you * are in a container environment, and you don't want to leave the thread local variables in the threads you do not * manage. */ @SuppressWarnings("unchecked") public static void removeAll() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return; } try { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v != null && v != InternalThreadLocalMap.UNSET) { Set<InternalThreadLocal<?>> variablesToRemove = (Set<InternalThreadLocal<?>>) v; InternalThreadLocal<?>[] variablesToRemoveArray = variablesToRemove.toArray(new InternalThreadLocal[0]); for (InternalThreadLocal<?> tlv : variablesToRemoveArray) { tlv.remove(threadLocalMap); } } } finally { InternalThreadLocalMap.remove(); } } /** * Returns the number of thread local variables bound to the current thread. */ public static int size() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return 0; } else { return threadLocalMap.size(); } } public static void destroy() { InternalThreadLocalMap.destroy(); } @SuppressWarnings("unchecked") private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal<?> variable) { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); Set<InternalThreadLocal<?>> variablesToRemove; if (v == InternalThreadLocalMap.UNSET || v == null) { variablesToRemove = Collections.newSetFromMap(new IdentityHashMap<InternalThreadLocal<?>, Boolean>()); threadLocalMap.setIndexedVariable(VARIABLES_TO_REMOVE_INDEX, variablesToRemove); } else { variablesToRemove = (Set<InternalThreadLocal<?>>) v; } variablesToRemove.add(variable); } @SuppressWarnings("unchecked") private static void removeFromVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal<?> variable) { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v == InternalThreadLocalMap.UNSET || v == null) { return; } Set<InternalThreadLocal<?>> variablesToRemove = (Set<InternalThreadLocal<?>>) v; variablesToRemove.remove(variable); } /** * Returns the current value for the current thread */ @SuppressWarnings("unchecked") @Override public final V get() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); Object v = threadLocalMap.indexedVariable(index); if (v != InternalThreadLocalMap.UNSET) { return (V) v; } return initialize(threadLocalMap); } public final V getWithoutInitialize() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); Object v = threadLocalMap.indexedVariable(index); if (v != InternalThreadLocalMap.UNSET) { return (V) v; } return null; } private V initialize(InternalThreadLocalMap threadLocalMap) { V v = null; try { v = initialValue(); } catch (Exception e) { throw new RuntimeException(e); } threadLocalMap.setIndexedVariable(index, v); addToVariablesToRemove(threadLocalMap, this); return v; } /** * Sets the value for the current thread. */ @Override public final void set(V value) { if (value == null || value == InternalThreadLocalMap.UNSET) { remove(); } else { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); if (threadLocalMap.setIndexedVariable(index, value)) { addToVariablesToRemove(threadLocalMap, this); } } } /** * Sets the value to uninitialized; a proceeding call to get() will trigger a call to initialValue(). */ @SuppressWarnings("unchecked") @Override public final void remove() { remove(InternalThreadLocalMap.getIfSet()); } /** * Sets the value to uninitialized for the specified thread local map; * a proceeding call to get() will trigger a call to initialValue(). * The specified thread local map must be for the current thread. */ @SuppressWarnings("unchecked") public final void remove(InternalThreadLocalMap threadLocalMap) { if (threadLocalMap == null) { return; } Object v = threadLocalMap.removeIndexedVariable(index); removeFromVariablesToRemove(threadLocalMap, this); if (v != InternalThreadLocalMap.UNSET) { try { onRemoval((V) v); } catch (Exception e) { throw new RuntimeException(e); } } } /** * Returns the initial value for this thread-local variable. */ @Override protected V initialValue() { return null; } /** * Invoked when this thread local variable is removed by {@link #remove()}. */ protected void onRemoval(@SuppressWarnings("unused") V value) throws Exception { } }
6,835
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalRunnable.java
/* * 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.threadlocal; /** * InternalRunnable * There is a risk of memory leak when using {@link InternalThreadLocal} without calling * {@link InternalThreadLocal#removeAll()}. * This design is learning from {@see io.netty.util.concurrent.FastThreadLocalRunnable} which is in Netty. */ public class InternalRunnable implements Runnable { private final Runnable runnable; public InternalRunnable(Runnable runnable) { this.runnable = runnable; } /** * After the task execution is completed, it will call {@link InternalThreadLocal#removeAll()} to clear * unnecessary variables in the thread. */ @Override public void run() { try { runnable.run(); } finally { InternalThreadLocal.removeAll(); } } /** * Wrap ordinary Runnable into {@link InternalThreadLocal}. */ public static Runnable Wrap(Runnable runnable) { return runnable instanceof InternalRunnable ? runnable : new InternalRunnable(runnable); } }
6,836
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThread.java
/* * 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.threadlocal; /** * InternalThread */ public class InternalThread extends Thread { private InternalThreadLocalMap threadLocalMap; public InternalThread() {} public InternalThread(Runnable target) { super(target); } public InternalThread(ThreadGroup group, Runnable target) { super(group, target); } public InternalThread(String name) { super(name); } public InternalThread(ThreadGroup group, String name) { super(group, name); } public InternalThread(Runnable target, String name) { super(target, name); } public InternalThread(ThreadGroup group, Runnable target, String name) { super(group, target, name); } public InternalThread(ThreadGroup group, Runnable target, String name, long stackSize) { super(group, target, name, stackSize); } /** * Returns the internal data structure that keeps the threadLocal variables bound to this thread. * Note that this method is for internal use only, and thus is subject to change at any time. */ public final InternalThreadLocalMap threadLocalMap() { return threadLocalMap; } /** * Sets the internal data structure that keeps the threadLocal variables bound to this thread. * Note that this method is for internal use only, and thus is subject to change at any time. */ public final void setThreadLocalMap(InternalThreadLocalMap threadLocalMap) { this.threadLocalMap = threadLocalMap; } }
6,837
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactory.java
/* * 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.threadlocal; import org.apache.dubbo.common.utils.NamedThreadFactory; /** * NamedInternalThreadFactory * This is a threadFactory which produce {@link InternalThread} */ public class NamedInternalThreadFactory extends NamedThreadFactory { public NamedInternalThreadFactory() { super(); } public NamedInternalThreadFactory(String prefix) { super(prefix, false); } public NamedInternalThreadFactory(String prefix, boolean daemon) { super(prefix, daemon); } @Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); InternalThread ret = new InternalThread(mGroup, InternalRunnable.Wrap(runnable), name, 0); ret.setDaemon(mDaemon); return ret; } }
6,838
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
/* * 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.stream; /** * StreamObserver is a common streaming API. It is an observer for receiving messages. * Implementations are NOT required to be thread-safe. * * @param <T> type of message */ public interface StreamObserver<T> { /** * onNext * * @param data to process */ void onNext(T data); /** * onError * * @param throwable error */ void onError(Throwable throwable); /** * onCompleted */ void onCompleted(); }
6,839
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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.timer; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Queue; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_RUN_THREAD_TASK; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_TOO_MANY_INSTANCES; /** * A {@link Timer} optimized for approximated I/O timeout scheduling. * * <h3>Tick Duration</h3> * <p> * As described with 'approximated', this timer does not execute the scheduled * {@link TimerTask} on time. {@link HashedWheelTimer}, on every tick, will * check if there are any {@link TimerTask}s behind the schedule and execute * them. * <p> * You can increase or decrease the accuracy of the execution timing by * specifying smaller or larger tick duration in the constructor. In most * network applications, I/O timeout does not need to be accurate. Therefore, * the default tick duration is 100 milliseconds, and you will not need to try * different configurations in most cases. * * <h3>Ticks per Wheel (Wheel Size)</h3> * <p> * {@link HashedWheelTimer} maintains a data structure called 'wheel'. * To put simply, a wheel is a hash table of {@link TimerTask}s whose hash * function is 'deadline of the task'. The default number of ticks per wheel * (i.e. the size of the wheel) is 512. You could specify a larger value * if you are going to schedule a lot of timeouts. * * <h3>Do not create many instances.</h3> * <p> * {@link HashedWheelTimer} creates a new thread whenever it is instantiated and * started. Therefore, you should make sure to create only one instance and * share it across your application. One of the common mistakes, that makes * your application unresponsive, is to create a new instance for every connection. * * <h3>Implementation Details</h3> * <p> * {@link HashedWheelTimer} is based on * <a href="http://cseweb.ucsd.edu/users/varghese/">George Varghese</a> and * Tony Lauck's paper, * <a href="http://cseweb.ucsd.edu/users/varghese/PAPERS/twheel.ps.Z">'Hashed * and Hierarchical Timing Wheels: data structures to efficiently implement a * timer facility'</a>. More comprehensive slides are located * <a href="http://www.cse.wustl.edu/~cdgill/courses/cs6874/TimingWheels.ppt">here</a>. */ public class HashedWheelTimer implements Timer { /** * may be in spi? */ public static final String NAME = "hased"; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HashedWheelTimer.class); private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger(); private static final AtomicBoolean WARNED_TOO_MANY_INSTANCES = new AtomicBoolean(); private static final int INSTANCE_COUNT_LIMIT = 64; private static final AtomicIntegerFieldUpdater<HashedWheelTimer> WORKER_STATE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState"); private final Worker worker = new Worker(); private final Thread workerThread; private static final int WORKER_STATE_INIT = 0; private static final int WORKER_STATE_STARTED = 1; private static final int WORKER_STATE_SHUTDOWN = 2; /** * 0 - init, 1 - started, 2 - shut down */ @SuppressWarnings({"unused", "FieldMayBeFinal"}) private volatile int workerState; private final long tickDuration; private final HashedWheelBucket[] wheel; private final int mask; private final CountDownLatch startTimeInitialized = new CountDownLatch(1); private final Queue<HashedWheelTimeout> timeouts = new LinkedBlockingQueue<>(); private final Queue<HashedWheelTimeout> cancelledTimeouts = new LinkedBlockingQueue<>(); private final AtomicLong pendingTimeouts = new AtomicLong(0); private final long maxPendingTimeouts; private volatile long startTime; /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}), default tick duration, and * default number of ticks per wheel. */ public HashedWheelTimer() { this(Executors.defaultThreadFactory()); } /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}) and default number of ticks * per wheel. * * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @throws NullPointerException if {@code unit} is {@code null} * @throws IllegalArgumentException if {@code tickDuration} is &lt;= 0 */ public HashedWheelTimer(long tickDuration, TimeUnit unit) { this(Executors.defaultThreadFactory(), tickDuration, unit); } /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}). * * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @throws NullPointerException if {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) { this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel); } /** * Creates a new timer with the default tick duration and default number of * ticks per wheel. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @throws NullPointerException if {@code threadFactory} is {@code null} */ public HashedWheelTimer(ThreadFactory threadFactory) { this(threadFactory, 100, TimeUnit.MILLISECONDS); } /** * Creates a new timer with the default number of ticks per wheel. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if {@code tickDuration} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit) { this(threadFactory, tickDuration, unit, 512); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) { this(threadFactory, tickDuration, unit, ticksPerWheel, -1); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel * @param maxPendingTimeouts The maximum number of pending timeouts after which call to * {@code newTimeout} will result in * {@link java.util.concurrent.RejectedExecutionException} * being thrown. No maximum pending timeouts limit is assumed if * this value is 0 or negative. * @throws NullPointerException if either of {@code threadFactory} and {@code unit} is {@code null} * @throws IllegalArgumentException if either of {@code tickDuration} and {@code ticksPerWheel} is &lt;= 0 */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel, long maxPendingTimeouts) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (unit == null) { throw new NullPointerException("unit"); } if (tickDuration <= 0) { throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel); } // Normalize ticksPerWheel to power of two and initialize the wheel. wheel = createWheel(ticksPerWheel); mask = wheel.length - 1; // Convert tickDuration to nanos. this.tickDuration = unit.toNanos(tickDuration); // Prevent overflow. if (this.tickDuration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException(String.format( "tickDuration: %d (expected: 0 < tickDuration in nanos < %d", tickDuration, Long.MAX_VALUE / wheel.length)); } workerThread = threadFactory.newThread(worker); this.maxPendingTimeouts = maxPendingTimeouts; if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT && WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { reportTooManyInstances(); } } @Override protected void finalize() throws Throwable { try { super.finalize(); } finally { // This object is going to be GCed and it is assumed the ship has sailed to do a proper shutdown. If // we have not yet shutdown then we want to make sure we decrement the active instance count. if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) { INSTANCE_COUNTER.decrementAndGet(); } } } private static HashedWheelBucket[] createWheel(int ticksPerWheel) { if (ticksPerWheel <= 0) { throw new IllegalArgumentException( "ticksPerWheel must be greater than 0: " + ticksPerWheel); } if (ticksPerWheel > 1073741824) { throw new IllegalArgumentException( "ticksPerWheel may not be greater than 2^30: " + ticksPerWheel); } ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel); HashedWheelBucket[] wheel = new HashedWheelBucket[ticksPerWheel]; for (int i = 0; i < wheel.length; i++) { wheel[i] = new HashedWheelBucket(); } return wheel; } private static int normalizeTicksPerWheel(int ticksPerWheel) { int normalizedTicksPerWheel = ticksPerWheel - 1; normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 1; normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 2; normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 4; normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 8; normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 16; return normalizedTicksPerWheel + 1; } /** * Starts the background thread explicitly. The background thread will * start automatically on demand even if you did not call this method. * * @throws IllegalStateException if this timer has been * {@linkplain #stop() stopped} already */ public void start() { switch (WORKER_STATE_UPDATER.get(this)) { case WORKER_STATE_INIT: if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) { workerThread.start(); } break; case WORKER_STATE_STARTED: break; case WORKER_STATE_SHUTDOWN: throw new IllegalStateException("cannot be started once stopped"); default: throw new Error("Invalid WorkerState"); } // Wait until the startTime is initialized by the worker. while (startTime == 0) { try { startTimeInitialized.await(); } catch (InterruptedException ignore) { // Ignore - it will be ready very soon. } } } @Override public Set<Timeout> stop() { if (Thread.currentThread() == workerThread) { throw new IllegalStateException( HashedWheelTimer.class.getSimpleName() + ".stop() cannot be called from " + TimerTask.class.getSimpleName()); } if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) { // workerState can be 0 or 2 at this moment - let it always be 2. if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) { INSTANCE_COUNTER.decrementAndGet(); } return Collections.emptySet(); } try { boolean interrupted = false; while (workerThread.isAlive()) { workerThread.interrupt(); try { workerThread.join(100); } catch (InterruptedException ignored) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } finally { INSTANCE_COUNTER.decrementAndGet(); } return worker.unprocessedTimeouts(); } @Override public boolean isStop() { return WORKER_STATE_SHUTDOWN == WORKER_STATE_UPDATER.get(this); } @Override public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { if (task == null) { throw new NullPointerException("task"); } if (unit == null) { throw new NullPointerException("unit"); } long pendingTimeoutsCount = pendingTimeouts.incrementAndGet(); if (maxPendingTimeouts > 0 && pendingTimeoutsCount > maxPendingTimeouts) { pendingTimeouts.decrementAndGet(); throw new RejectedExecutionException("Number of pending timeouts (" + pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending " + "timeouts (" + maxPendingTimeouts + ")"); } start(); // Add the timeout to the timeout queue which will be processed on the next tick. // During processing all the queued HashedWheelTimeouts will be added to the correct HashedWheelBucket. long deadline = System.nanoTime() + unit.toNanos(delay) - startTime; // Guard against overflow. if (delay > 0 && deadline < 0) { deadline = Long.MAX_VALUE; } HashedWheelTimeout timeout = new HashedWheelTimeout(this, task, deadline); timeouts.add(timeout); return timeout; } /** * Returns the number of pending timeouts of this {@link Timer}. */ public long pendingTimeouts() { return pendingTimeouts.get(); } private static void reportTooManyInstances() { String resourceType = ClassUtils.simpleClassName(HashedWheelTimer.class); logger.error(COMMON_ERROR_TOO_MANY_INSTANCES, "", "", "You are creating too many " + resourceType + " instances. " + resourceType + " is a shared resource that must be reused across the JVM, " + "so that only a few instances are created."); } private final class Worker implements Runnable { private final Set<Timeout> unprocessedTimeouts = new HashSet<Timeout>(); private long tick; @Override public void run() { // Initialize the startTime. startTime = System.nanoTime(); if (startTime == 0) { // We use 0 as an indicator for the uninitialized value here, so make sure it's not 0 when initialized. startTime = 1; } // Notify the other threads waiting for the initialization at start(). startTimeInitialized.countDown(); do { final long deadline = waitForNextTick(); if (deadline > 0) { int idx = (int) (tick & mask); processCancelledTasks(); HashedWheelBucket bucket = wheel[idx]; transferTimeoutsToBuckets(); bucket.expireTimeouts(deadline); tick++; } } while (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_STARTED); // Fill the unprocessedTimeouts so we can return them from stop() method. for (HashedWheelBucket bucket : wheel) { bucket.clearTimeouts(unprocessedTimeouts); } for (; ; ) { HashedWheelTimeout timeout = timeouts.poll(); if (timeout == null) { break; } if (!timeout.isCancelled()) { unprocessedTimeouts.add(timeout); } } processCancelledTasks(); } private void transferTimeoutsToBuckets() { // transfer only max. 100000 timeouts per tick to prevent a thread to stale the workerThread when it just // adds new timeouts in a loop. for (int i = 0; i < 100000; i++) { HashedWheelTimeout timeout = timeouts.poll(); if (timeout == null) { // all processed break; } if (timeout.state() == HashedWheelTimeout.ST_CANCELLED) { // Was cancelled in the meantime. continue; } long calculated = timeout.deadline / tickDuration; timeout.remainingRounds = (calculated - tick) / wheel.length; // Ensure we don't schedule for past. final long ticks = Math.max(calculated, tick); int stopIndex = (int) (ticks & mask); HashedWheelBucket bucket = wheel[stopIndex]; bucket.addTimeout(timeout); } } private void processCancelledTasks() { for (; ; ) { HashedWheelTimeout timeout = cancelledTimeouts.poll(); if (timeout == null) { // all processed break; } try { timeout.remove(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn(COMMON_ERROR_RUN_THREAD_TASK, "", "", "An exception was thrown while process a cancellation task", t); } } } } /** * calculate goal nanoTime from startTime and current tick number, * then wait until that goal has been reached. * * @return Long.MIN_VALUE if received a shutdown request, * current time otherwise (with Long.MIN_VALUE changed by +1) */ private long waitForNextTick() { long deadline = tickDuration * (tick + 1); for (; ; ) { final long currentTime = System.nanoTime() - startTime; long sleepTimeMs = (deadline - currentTime + 999999) / 1000000; if (sleepTimeMs <= 0) { if (currentTime == Long.MIN_VALUE) { return -Long.MAX_VALUE; } else { return currentTime; } } if (isWindows()) { sleepTimeMs = sleepTimeMs / 10 * 10; } try { Thread.sleep(sleepTimeMs); } catch (InterruptedException ignored) { if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) { return Long.MIN_VALUE; } } } } Set<Timeout> unprocessedTimeouts() { return Collections.unmodifiableSet(unprocessedTimeouts); } } private static final class HashedWheelTimeout implements Timeout { private static final int ST_INIT = 0; private static final int ST_CANCELLED = 1; private static final int ST_EXPIRED = 2; private static final AtomicIntegerFieldUpdater<HashedWheelTimeout> STATE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state"); private final HashedWheelTimer timer; private final TimerTask task; private final long deadline; @SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization"}) private volatile int state = ST_INIT; /** * RemainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the * HashedWheelTimeout will be added to the correct HashedWheelBucket. */ long remainingRounds; /** * This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list. * As only the workerThread will act on it there is no need for synchronization / volatile. */ HashedWheelTimeout next; HashedWheelTimeout prev; /** * The bucket to which the timeout was added */ HashedWheelBucket bucket; HashedWheelTimeout(HashedWheelTimer timer, TimerTask task, long deadline) { this.timer = timer; this.task = task; this.deadline = deadline; } @Override public Timer timer() { return timer; } @Override public TimerTask task() { return task; } @Override public boolean cancel() { // only update the state it will be removed from HashedWheelBucket on next tick. if (!compareAndSetState(ST_INIT, ST_CANCELLED)) { return false; } // If a task should be canceled we put this to another queue which will be processed on each tick. // So this means that we will have a GC latency of max. 1 tick duration which is good enough. This way we // can make again use of our LinkedBlockingQueue and so minimize the locking / overhead as much as possible. timer.cancelledTimeouts.add(this); return true; } void remove() { HashedWheelBucket bucket = this.bucket; if (bucket != null) { bucket.remove(this); } else { timer.pendingTimeouts.decrementAndGet(); } } public boolean compareAndSetState(int expected, int state) { return STATE_UPDATER.compareAndSet(this, expected, state); } public int state() { return state; } @Override public boolean isCancelled() { return state() == ST_CANCELLED; } @Override public boolean isExpired() { return state() == ST_EXPIRED; } public void expire() { if (!compareAndSetState(ST_INIT, ST_EXPIRED)) { return; } try { task.run(this); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn(COMMON_ERROR_RUN_THREAD_TASK, "", "", "An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t); } } } @Override public String toString() { final long currentTime = System.nanoTime(); long remaining = deadline - currentTime + timer.startTime; String simpleClassName = ClassUtils.simpleClassName(this.getClass()); StringBuilder buf = new StringBuilder(192) .append(simpleClassName) .append('(') .append("deadline: "); if (remaining > 0) { buf.append(remaining) .append(" ns later"); } else if (remaining < 0) { buf.append(-remaining) .append(" ns ago"); } else { buf.append("now"); } if (isCancelled()) { buf.append(", cancelled"); } return buf.append(", task: ") .append(task()) .append(')') .toString(); } } /** * Bucket that stores HashedWheelTimeouts. These are stored in a linked-list like datastructure to allow easy * removal of HashedWheelTimeouts in the middle. Also the HashedWheelTimeout act as nodes themself and so no * extra object creation is needed. */ private static final class HashedWheelBucket { /** * Used for the linked-list datastructure */ private HashedWheelTimeout head; private HashedWheelTimeout tail; /** * Add {@link HashedWheelTimeout} to this bucket. */ void addTimeout(HashedWheelTimeout timeout) { assert timeout.bucket == null; timeout.bucket = this; if (head == null) { head = tail = timeout; } else { tail.next = timeout; timeout.prev = tail; tail = timeout; } } /** * Expire all {@link HashedWheelTimeout}s for the given {@code deadline}. */ void expireTimeouts(long deadline) { HashedWheelTimeout timeout = head; // process all timeouts while (timeout != null) { HashedWheelTimeout next = timeout.next; if (timeout.remainingRounds <= 0) { next = remove(timeout); if (timeout.deadline <= deadline) { timeout.expire(); } else { // The timeout was placed into a wrong slot. This should never happen. throw new IllegalStateException(String.format( "timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline)); } } else if (timeout.isCancelled()) { next = remove(timeout); } else { timeout.remainingRounds--; } timeout = next; } } public HashedWheelTimeout remove(HashedWheelTimeout timeout) { HashedWheelTimeout next = timeout.next; // remove timeout that was either processed or cancelled by updating the linked-list if (timeout.prev != null) { timeout.prev.next = next; } if (timeout.next != null) { timeout.next.prev = timeout.prev; } if (timeout == head) { // if timeout is also the tail we need to adjust the entry too if (timeout == tail) { tail = null; head = null; } else { head = next; } } else if (timeout == tail) { // if the timeout is the tail modify the tail to be the prev node. tail = timeout.prev; } // null out prev, next and bucket to allow for GC. timeout.prev = null; timeout.next = null; timeout.bucket = null; timeout.timer.pendingTimeouts.decrementAndGet(); return next; } /** * Clear this bucket and return all not expired / cancelled {@link Timeout}s. */ void clearTimeouts(Set<Timeout> set) { for (; ; ) { HashedWheelTimeout timeout = pollTimeout(); if (timeout == null) { return; } if (timeout.isExpired() || timeout.isCancelled()) { continue; } set.add(timeout); } } private HashedWheelTimeout pollTimeout() { HashedWheelTimeout head = this.head; if (head == null) { return null; } HashedWheelTimeout next = head.next; if (next == null) { tail = this.head = null; } else { this.head = next; next.prev = null; } // null out prev and next to allow for GC. head.next = null; head.prev = null; head.bucket = null; return head; } } private static final boolean IS_OS_WINDOWS = System.getProperty(OS_NAME_KEY, "").toLowerCase(Locale.US).contains(OS_WIN_PREFIX); private boolean isWindows() { return IS_OS_WINDOWS; } }
6,840
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timeout.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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.timer; /** * A handle associated with a {@link TimerTask} that is returned by a * {@link Timer}. */ public interface Timeout { /** * Returns the {@link Timer} that created this handle. */ Timer timer(); /** * Returns the {@link TimerTask} which is associated with this handle. */ TimerTask task(); /** * Returns {@code true} if and only if the {@link TimerTask} associated * with this handle has been expired. */ boolean isExpired(); /** * Returns {@code true} if and only if the {@link TimerTask} associated * with this handle has been cancelled. */ boolean isCancelled(); /** * Attempts to cancel the {@link TimerTask} associated with this handle. * If the task has been executed or cancelled already, it will return with * no side effect. * * @return True if the cancellation completed successfully, otherwise false */ boolean cancel(); }
6,841
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timer.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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.timer; import java.util.Set; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; /** * Schedules {@link TimerTask}s for one-time future execution in a background * thread. */ public interface Timer { /** * Schedules the specified {@link TimerTask} for one-time execution after * the specified delay. * * @return a handle which is associated with the specified task * @throws IllegalStateException if this timer has been {@linkplain #stop() stopped} already * @throws RejectedExecutionException if the pending timeouts are too many and creating new timeout * can cause instability in the system. */ Timeout newTimeout(TimerTask task, long delay, TimeUnit unit); /** * Releases all resources acquired by this {@link Timer} and cancels all * tasks which were scheduled but not executed yet. * * @return the handles associated with the tasks which were canceled by * this method */ Set<Timeout> stop(); /** * the timer is stop * * @return true for stop */ boolean isStop(); }
6,842
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/timer/TimerTask.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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.timer; import java.util.concurrent.TimeUnit; /** * A task which is executed after the delay specified with * {@link Timer#newTimeout(TimerTask, long, TimeUnit)} (TimerTask, long, TimeUnit)}. */ public interface TimerTask { /** * Executed after the delay specified with * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}. * * @param timeout a handle which is associated with this task */ void run(Timeout timeout) throws Exception; }
6,843
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java
/* * 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.io; import java.io.IOException; import java.io.Reader; /** * Thread-unsafe StringReader. */ public class UnsafeStringReader extends Reader { private String mString; private int mPosition, mLimit, mMark; public UnsafeStringReader(String str) { mString = str; mLimit = str.length(); mPosition = mMark = 0; } @Override public int read() throws IOException { ensureOpen(); if (mPosition >= mLimit) { return -1; } return mString.charAt(mPosition++); } @Override public int read(char[] cs, int off, int len) throws IOException { ensureOpen(); if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (len == 0) { return 0; } if (mPosition >= mLimit) { return -1; } int n = Math.min(mLimit - mPosition, len); mString.getChars(mPosition, mPosition + n, cs, off); mPosition += n; return n; } @Override public long skip(long ns) throws IOException { ensureOpen(); if (mPosition >= mLimit) { return 0; } long n = Math.min(mLimit - mPosition, ns); n = Math.max(-mPosition, n); mPosition += n; return n; } @Override public boolean ready() throws IOException { ensureOpen(); return true; } @Override public boolean markSupported() { return true; } @Override public void mark(int readAheadLimit) throws IOException { if (readAheadLimit < 0) { throw new IllegalArgumentException("Read-ahead limit < 0"); } ensureOpen(); mMark = mPosition; } @Override public void reset() throws IOException { ensureOpen(); mPosition = mMark; } @Override public void close() throws IOException { mString = null; } private void ensureOpen() throws IOException { if (mString == null) { throw new IOException("Stream closed"); } } }
6,844
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java
/* * 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.io; import java.io.IOException; import java.io.InputStream; /** * Stream utils. */ public class StreamUtils { private StreamUtils() {} public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException { return new InputStream() { private int mPosition = 0; private int mMark = 0; private final int mLimit = Math.min(limit, is.available()); @Override public int read() throws IOException { if (mPosition < mLimit) { mPosition++; return is.read(); } return -1; } @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } if (mPosition >= mLimit) { return -1; } if (mPosition + len > mLimit) { len = mLimit - mPosition; } if (len <= 0) { return 0; } is.read(b, off, len); mPosition += len; return len; } @Override public long skip(long len) throws IOException { if (mPosition + len > mLimit) { len = mLimit - mPosition; } if (len <= 0) { return 0; } is.skip(len); mPosition += len; return len; } @Override public int available() { return mLimit - mPosition; } @Override public boolean markSupported() { return is.markSupported(); } @Override public synchronized void mark(int readlimit) { is.mark(readlimit); mMark = mPosition; } @Override public synchronized void reset() throws IOException { is.reset(); mPosition = mMark; } @Override public void close() throws IOException { is.close(); } }; } public static InputStream markSupportedInputStream(final InputStream is, final int markBufferSize) { if (is.markSupported()) { return is; } return new InputStream() { byte[] mMarkBuffer; boolean mInMarked = false; boolean mInReset = false; boolean mDry = false; private int mPosition = 0; private int mCount = 0; @Override public int read() throws IOException { if (!mInMarked) { return is.read(); } else { if (mPosition < mCount) { byte b = mMarkBuffer[mPosition++]; return b & 0xFF; } if (!mInReset) { if (mDry) { return -1; } if (null == mMarkBuffer) { mMarkBuffer = new byte[markBufferSize]; } if (mPosition >= markBufferSize) { throw new IOException("Mark buffer is full!"); } int read = is.read(); if (-1 == read) { mDry = true; return -1; } mMarkBuffer[mPosition++] = (byte) read; mCount++; return read; } else { // mark buffer is used, exit mark status! mInMarked = false; mInReset = false; mPosition = 0; mCount = 0; return is.read(); } } } /** * NOTE: the <code>readlimit</code> argument for this class * has no meaning. */ @Override public synchronized void mark(int readlimit) { mInMarked = true; mInReset = false; // mark buffer is not empty int count = mCount - mPosition; if (count > 0) { System.arraycopy(mMarkBuffer, mPosition, mMarkBuffer, 0, count); mCount = count; mPosition = 0; } } @Override public synchronized void reset() throws IOException { if (!mInMarked) { throw new IOException("should mark before reset!"); } mInReset = true; mPosition = 0; } @Override public boolean markSupported() { return true; } @Override public int available() throws IOException { int available = is.available(); if (mInMarked && mInReset) { available += mCount - mPosition; } return available; } @Override public void close() throws IOException { is.close(); } }; } public static InputStream markSupportedInputStream(final InputStream is) { return markSupportedInputStream(is, 1024); } public static void skipUnusedStream(InputStream is) throws IOException { if (is.available() > 0) { is.skip(is.available()); } } }
6,845
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java
/* * 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.io; import java.io.IOException; import java.io.Writer; /** * Thread-unsafe StringWriter. */ public class UnsafeStringWriter extends Writer { private final StringBuilder mBuffer; public UnsafeStringWriter() { lock = mBuffer = new StringBuilder(); } public UnsafeStringWriter(int size) { if (size < 0) { throw new IllegalArgumentException("Negative buffer size"); } lock = mBuffer = new StringBuilder(size); } @Override public void write(int c) { mBuffer.append((char) c); } @Override public void write(char[] cs) throws IOException { mBuffer.append(cs, 0, cs.length); } @Override public void write(char[] cs, int off, int len) throws IOException { if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (len > 0) { mBuffer.append(cs, off, len); } } @Override public void write(String str) { mBuffer.append(str); } @Override public void write(String str, int off, int len) { mBuffer.append(str, off, off + len); } @Override public Writer append(CharSequence csq) { if (csq == null) { write("null"); } else { write(csq.toString()); } return this; } @Override public Writer append(CharSequence csq, int start, int end) { CharSequence cs = (csq == null ? "null" : csq); write(cs.subSequence(start, end).toString()); return this; } @Override public Writer append(char c) { mBuffer.append(c); return this; } @Override public void close() {} @Override public void flush() {} @Override public String toString() { return mBuffer.toString(); } }
6,846
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java
/* * 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.io; import org.apache.dubbo.common.utils.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; /** * CodecUtils. */ public class Bytes { private static final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. private static final char[] BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, BASE64 = C64.toCharArray(); private static final int MASK4 = 0x0f, MASK6 = 0x3f, MASK8 = 0xff; private static final Map<Integer, byte[]> DECODE_TABLE_MAP = new ConcurrentHashMap<>(); private static final ThreadLocal<MessageDigest> MD = new ThreadLocal<>(); private Bytes() {} /** * byte array copy. * * @param src src. * @param length new length. * @return new byte array. */ public static byte[] copyOf(byte[] src, int length) { byte[] dest = new byte[length]; System.arraycopy(src, 0, dest, 0, Math.min(src.length, length)); return dest; } /** * to byte array. * * @param v value. * @return byte[]. */ public static byte[] short2bytes(short v) { byte[] ret = {0, 0}; short2bytes(v, ret); return ret; } /** * to byte array. * * @param v value. * @param b byte array. */ public static void short2bytes(short v, byte[] b) { short2bytes(v, b, 0); } /** * to byte array. * * @param v value. * @param b byte array. */ public static void short2bytes(short v, byte[] b, int off) { b[off + 1] = (byte) v; b[off + 0] = (byte) (v >>> 8); } /** * to byte array. * * @param v value. * @return byte[]. */ public static byte[] int2bytes(int v) { byte[] ret = {0, 0, 0, 0}; int2bytes(v, ret); return ret; } /** * to byte array. * * @param v value. * @param b byte array. */ public static void int2bytes(int v, byte[] b) { int2bytes(v, b, 0); } /** * to byte array. * * @param v value. * @param b byte array. * @param off array offset. */ public static void int2bytes(int v, byte[] b, int off) { b[off + 3] = (byte) v; b[off + 2] = (byte) (v >>> 8); b[off + 1] = (byte) (v >>> 16); b[off + 0] = (byte) (v >>> 24); } /** * to byte array. * * @param v value. * @return byte[]. */ public static byte[] float2bytes(float v) { byte[] ret = {0, 0, 0, 0}; float2bytes(v, ret); return ret; } /** * to byte array. * * @param v value. * @param b byte array. */ public static void float2bytes(float v, byte[] b) { float2bytes(v, b, 0); } /** * to byte array. * * @param v value. * @param b byte array. * @param off array offset. */ public static void float2bytes(float v, byte[] b, int off) { int i = Float.floatToIntBits(v); b[off + 3] = (byte) i; b[off + 2] = (byte) (i >>> 8); b[off + 1] = (byte) (i >>> 16); b[off + 0] = (byte) (i >>> 24); } /** * to byte array. * * @param v value. * @return byte[]. */ public static byte[] long2bytes(long v) { byte[] ret = {0, 0, 0, 0, 0, 0, 0, 0}; long2bytes(v, ret); return ret; } /** * to byte array. * * @param v value. * @param b byte array. */ public static void long2bytes(long v, byte[] b) { long2bytes(v, b, 0); } /** * to byte array. * * @param v value. * @param b byte array. * @param off array offset. */ public static void long2bytes(long v, byte[] b, int off) { b[off + 7] = (byte) v; b[off + 6] = (byte) (v >>> 8); b[off + 5] = (byte) (v >>> 16); b[off + 4] = (byte) (v >>> 24); b[off + 3] = (byte) (v >>> 32); b[off + 2] = (byte) (v >>> 40); b[off + 1] = (byte) (v >>> 48); b[off + 0] = (byte) (v >>> 56); } /** * to byte array. * * @param v value. * @return byte[]. */ public static byte[] double2bytes(double v) { byte[] ret = {0, 0, 0, 0, 0, 0, 0, 0}; double2bytes(v, ret); return ret; } /** * to byte array. * * @param v value. * @param b byte array. */ public static void double2bytes(double v, byte[] b) { double2bytes(v, b, 0); } /** * to byte array. * * @param v value. * @param b byte array. * @param off array offset. */ public static void double2bytes(double v, byte[] b, int off) { long j = Double.doubleToLongBits(v); b[off + 7] = (byte) j; b[off + 6] = (byte) (j >>> 8); b[off + 5] = (byte) (j >>> 16); b[off + 4] = (byte) (j >>> 24); b[off + 3] = (byte) (j >>> 32); b[off + 2] = (byte) (j >>> 40); b[off + 1] = (byte) (j >>> 48); b[off + 0] = (byte) (j >>> 56); } /** * to short. * * @param b byte array. * @return short. */ public static short bytes2short(byte[] b) { return bytes2short(b, 0); } /** * to short. * * @param b byte array. * @param off offset. * @return short. */ public static short bytes2short(byte[] b, int off) { return (short) (((b[off + 1] & 0xFF) << 0) + ((b[off + 0]) << 8)); } /** * to int. * * @param b byte array. * @return int. */ public static int bytes2int(byte[] b) { return bytes2int(b, 0); } /** * to int. * * @param b byte array. * @param off offset. * @return int. */ public static int bytes2int(byte[] b, int off) { return ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off + 0]) << 24); } /** * to int. * * @param b byte array. * @return int. */ public static float bytes2float(byte[] b) { return bytes2float(b, 0); } /** * to int. * * @param b byte array. * @param off offset. * @return int. */ public static float bytes2float(byte[] b, int off) { int i = ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off + 0]) << 24); return Float.intBitsToFloat(i); } /** * to long. * * @param b byte array. * @return long. */ public static long bytes2long(byte[] b) { return bytes2long(b, 0); } /** * to long. * * @param b byte array. * @param off offset. * @return long. */ public static long bytes2long(byte[] b, int off) { return ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ((b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ((b[off + 1] & 0xFFL) << 48) + (((long) b[off + 0]) << 56); } /** * to long. * * @param b byte array. * @return double. */ public static double bytes2double(byte[] b) { return bytes2double(b, 0); } /** * to long. * * @param b byte array. * @param off offset. * @return double. */ public static double bytes2double(byte[] b, int off) { long j = ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ((b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ((b[off + 1] & 0xFFL) << 48) + (((long) b[off + 0]) << 56); return Double.longBitsToDouble(j); } /** * to hex string. * * @param bs byte array. * @return hex string. */ public static String bytes2hex(byte[] bs) { return bytes2hex(bs, 0, bs.length); } /** * to hex string. * * @param bs byte array. * @param off offset. * @param len length. * @return hex string. */ public static String bytes2hex(byte[] bs, int off, int len) { if (off < 0) { throw new IndexOutOfBoundsException("bytes2hex: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("bytes2hex: length < 0, length is " + len); } if (off + len > bs.length) { throw new IndexOutOfBoundsException("bytes2hex: offset + length > array length."); } byte b; int r = off, w = 0; char[] cs = new char[len * 2]; for (int i = 0; i < len; i++) { b = bs[r++]; cs[w++] = BASE16[b >> 4 & MASK4]; cs[w++] = BASE16[b & MASK4]; } return new String(cs); } /** * from hex string. * * @param str hex string. * @return byte array. */ public static byte[] hex2bytes(String str) { return hex2bytes(str, 0, str.length()); } /** * from hex string. * * @param str hex string. * @param off offset. * @param len length. * @return byte array. */ public static byte[] hex2bytes(final String str, final int off, int len) { if ((len & 1) == 1) { throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1."); } if (off < 0) { throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len); } if (off + len > str.length()) { throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length."); } int num = len / 2, r = off, w = 0; byte[] b = new byte[num]; for (int i = 0; i < num; i++) { b[w++] = (byte) (hex(str.charAt(r++)) << 4 | hex(str.charAt(r++))); } return b; } /** * to base64 string. * * @param b byte array. * @return base64 string. */ public static String bytes2base64(byte[] b) { return bytes2base64(b, 0, b.length, BASE64); } /** * to base64 string. * * @param b byte array. * @return base64 string. */ public static String bytes2base64(byte[] b, int offset, int length) { return bytes2base64(b, offset, length, BASE64); } /** * to base64 string. * * @param b byte array. * @param code base64 code string(0-63 is base64 char,64 is pad char). * @return base64 string. */ public static String bytes2base64(byte[] b, String code) { return bytes2base64(b, 0, b.length, code); } /** * to base64 string. * * @param b byte array. * @param code base64 code string(0-63 is base64 char,64 is pad char). * @return base64 string. */ public static String bytes2base64(byte[] b, int offset, int length, String code) { if (code.length() < 64) { throw new IllegalArgumentException("Base64 code length < 64."); } return bytes2base64(b, offset, length, code.toCharArray()); } /** * to base64 string. * * @param b byte array. * @param code base64 code(0-63 is base64 char,64 is pad char). * @return base64 string. */ public static String bytes2base64(byte[] b, char[] code) { return bytes2base64(b, 0, b.length, code); } /** * to base64 string. * * @param bs byte array. * @param off offset. * @param len length. * @param code base64 code(0-63 is base64 char,64 is pad char). * @return base64 string. */ public static String bytes2base64(final byte[] bs, final int off, final int len, final char[] code) { if (off < 0) { throw new IndexOutOfBoundsException("bytes2base64: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("bytes2base64: length < 0, length is " + len); } if (off + len > bs.length) { throw new IndexOutOfBoundsException("bytes2base64: offset + length > array length."); } if (code.length < 64) { throw new IllegalArgumentException("Base64 code length < 64."); } boolean pad = code.length > 64; // has pad char. int num = len / 3, rem = len % 3, r = off, w = 0; char[] cs = new char[num * 4 + (rem == 0 ? 0 : pad ? 4 : rem + 1)]; for (int i = 0; i < num; i++) { int b1 = bs[r++] & MASK8, b2 = bs[r++] & MASK8, b3 = bs[r++] & MASK8; cs[w++] = code[b1 >> 2]; cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)]; cs[w++] = code[(b2 << 2) & MASK6 | (b3 >> 6)]; cs[w++] = code[b3 & MASK6]; } if (rem == 1) { int b1 = bs[r++] & MASK8; cs[w++] = code[b1 >> 2]; cs[w++] = code[(b1 << 4) & MASK6]; if (pad) { cs[w++] = code[64]; cs[w++] = code[64]; } } else if (rem == 2) { int b1 = bs[r++] & MASK8, b2 = bs[r++] & MASK8; cs[w++] = code[b1 >> 2]; cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)]; cs[w++] = code[(b2 << 2) & MASK6]; if (pad) { cs[w++] = code[64]; } } return new String(cs); } /** * from base64 string. * * @param str base64 string. * @return byte array. */ public static byte[] base642bytes(String str) { return base642bytes(str, 0, str.length()); } /** * from base64 string. * * @param str base64 string. * @param offset offset. * @param length length. * @return byte array. */ public static byte[] base642bytes(String str, int offset, int length) { return base642bytes(str, offset, length, C64); } /** * from base64 string. * * @param str base64 string. * @param code base64 code(0-63 is base64 char,64 is pad char). * @return byte array. */ public static byte[] base642bytes(String str, String code) { return base642bytes(str, 0, str.length(), code); } /** * from base64 string. * * @param str base64 string. * @param off offset. * @param len length. * @param code base64 code(0-63 is base64 char,64 is pad char). * @return byte array. */ public static byte[] base642bytes(final String str, final int off, final int len, final String code) { if (off < 0) { throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len); } if (len == 0) { return new byte[0]; } if (off + len > str.length()) { throw new IndexOutOfBoundsException("base642bytes: offset + length > string length."); } if (code.length() < 64) { throw new IllegalArgumentException("Base64 code length < 64."); } int rem = len % 4; if (rem == 1) { throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1."); } int num = len / 4, size = num * 3; if (code.length() > 64) { if (rem != 0) { throw new IllegalArgumentException("base642bytes: base64 string length error."); } char pc = code.charAt(64); if (str.charAt(off + len - 2) == pc) { size -= 2; --num; rem = 2; } else if (str.charAt(off + len - 1) == pc) { size--; --num; rem = 3; } } else { if (rem == 2) { size++; } else if (rem == 3) { size += 2; } } int r = off, w = 0; byte[] b = new byte[size], t = decodeTable(code); for (int i = 0; i < num; i++) { int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)]; int c3 = t[str.charAt(r++)], c4 = t[str.charAt(r++)]; b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); b[w++] = (byte) ((c3 << 6) | c4); } if (rem == 2) { int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)]; b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); } else if (rem == 3) { int c1 = t[str.charAt(r++)], c2 = t[str.charAt(r++)], c3 = t[str.charAt(r++)]; b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); } return b; } /** * from base64 string. * * @param str base64 string. * @param code base64 code(0-63 is base64 char,64 is pad char). * @return byte array. */ public static byte[] base642bytes(String str, char[] code) { return base642bytes(str, 0, str.length(), code); } /** * from base64 string. * * @param str base64 string. * @param off offset. * @param len length. * @param code base64 code(0-63 is base64 char,64 is pad char). * @return byte array. */ public static byte[] base642bytes(final String str, final int off, final int len, final char[] code) { if (off < 0) { throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off); } if (len < 0) { throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len); } if (len == 0) { return new byte[0]; } if (off + len > str.length()) { throw new IndexOutOfBoundsException("base642bytes: offset + length > string length."); } if (code.length < 64) { throw new IllegalArgumentException("Base64 code length < 64."); } int rem = len % 4; if (rem == 1) { throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1."); } int num = len / 4, size = num * 3; if (code.length > 64) { if (rem != 0) { throw new IllegalArgumentException("base642bytes: base64 string length error."); } char pc = code[64]; if (str.charAt(off + len - 2) == pc) { size -= 2; --num; rem = 2; } else if (str.charAt(off + len - 1) == pc) { size--; --num; rem = 3; } } else { if (rem == 2) { size++; } else if (rem == 3) { size += 2; } } int r = off, w = 0; byte[] b = new byte[size]; for (int i = 0; i < num; i++) { int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)); int c3 = indexOf(code, str.charAt(r++)), c4 = indexOf(code, str.charAt(r++)); b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); b[w++] = (byte) ((c3 << 6) | c4); } if (rem == 2) { int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)); b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); } else if (rem == 3) { int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)), c3 = indexOf(code, str.charAt(r++)); b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); } return b; } /** * zip. * * @param bytes source. * @return compressed byte array. * @throws IOException */ public static byte[] zip(byte[] bytes) throws IOException { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(); OutputStream os = new DeflaterOutputStream(bos); try { os.write(bytes); } finally { os.close(); bos.close(); } return bos.toByteArray(); } /** * unzip. * * @param bytes compressed byte array. * @return byte uncompressed array. * @throws IOException */ public static byte[] unzip(byte[] bytes) throws IOException { UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes); UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(); InputStream is = new InflaterInputStream(bis); try { IOUtils.write(is, bos); return bos.toByteArray(); } finally { is.close(); bis.close(); bos.close(); } } /** * get md5. * * @param str input string. * @return MD5 byte array. */ public static byte[] getMD5(String str) { return getMD5(str.getBytes()); } /** * get md5. * * @param source byte array source. * @return MD5 byte array. */ public static byte[] getMD5(byte[] source) { MessageDigest md = getMessageDigest(); return md.digest(source); } /** * get md5. * * @param file file source. * @return MD5 byte array. */ public static byte[] getMD5(File file) throws IOException { InputStream is = new FileInputStream(file); try { return getMD5(is); } finally { is.close(); } } /** * get md5. * * @param is input stream. * @return MD5 byte array. */ public static byte[] getMD5(InputStream is) throws IOException { return getMD5(is, 1024 * 8); } private static byte hex(char c) { if (c <= '9') { return (byte) (c - '0'); } if (c >= 'a' && c <= 'f') { return (byte) (c - 'a' + 10); } if (c >= 'A' && c <= 'F') { return (byte) (c - 'A' + 10); } throw new IllegalArgumentException("hex string format error [" + c + "]."); } private static int indexOf(char[] cs, char c) { for (int i = 0, len = cs.length; i < len; i++) { if (cs[i] == c) { return i; } } return -1; } private static byte[] decodeTable(String code) { int hash = code.hashCode(); byte[] ret = DECODE_TABLE_MAP.get(hash); if (ret == null) { if (code.length() < 64) { throw new IllegalArgumentException("Base64 code length < 64."); } // create new decode table. ret = new byte[128]; for (int i = 0; i < 128; i++) // init table. { ret[i] = -1; } for (int i = 0; i < 64; i++) { ret[code.charAt(i)] = (byte) i; } DECODE_TABLE_MAP.put(hash, ret); } return ret; } private static byte[] getMD5(InputStream is, int bs) throws IOException { MessageDigest md = getMessageDigest(); byte[] buf = new byte[bs]; while (is.available() > 0) { int read, total = 0; do { if ((read = is.read(buf, total, bs - total)) <= 0) { break; } total += read; } while (total < bs); md.update(buf); } return md.digest(); } private static MessageDigest getMessageDigest() { MessageDigest ret = MD.get(); if (ret == null) { try { ret = MessageDigest.getInstance("MD5"); MD.set(ret); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } return ret; } }
6,847
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java
/* * 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.io; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; /** * UnsafeByteArrayOutputStream. */ public class UnsafeByteArrayOutputStream extends OutputStream { protected byte[] mBuffer; protected int mCount; public UnsafeByteArrayOutputStream() { this(32); } public UnsafeByteArrayOutputStream(int size) { if (size < 0) { throw new IllegalArgumentException("Negative initial size: " + size); } mBuffer = new byte[size]; } @Override public void write(int b) { int newCount = mCount + 1; if (newCount > mBuffer.length) { mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newCount)); } mBuffer[mCount] = (byte) b; mCount = newCount; } @Override public void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (len == 0) { return; } int newCount = mCount + len; if (newCount > mBuffer.length) { mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newCount)); } System.arraycopy(b, off, mBuffer, mCount, len); mCount = newCount; } public int size() { return mCount; } public void reset() { mCount = 0; } public byte[] toByteArray() { return Bytes.copyOf(mBuffer, mCount); } public ByteBuffer toByteBuffer() { return ByteBuffer.wrap(mBuffer, 0, mCount); } public void writeTo(OutputStream out) throws IOException { out.write(mBuffer, 0, mCount); } @Override public String toString() { return new String(mBuffer, 0, mCount); } public String toString(String charset) throws UnsupportedEncodingException { return new String(mBuffer, 0, mCount, charset); } @Override public void close() throws IOException {} }
6,848
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java
/* * 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.io; import java.io.IOException; import java.io.InputStream; /** * UnsafeByteArrayInputStream. */ public class UnsafeByteArrayInputStream extends InputStream { protected byte[] mData; protected int mPosition, mLimit, mMark = 0; public UnsafeByteArrayInputStream(byte[] buf) { this(buf, 0, buf.length); } public UnsafeByteArrayInputStream(byte[] buf, int offset) { this(buf, offset, buf.length - offset); } public UnsafeByteArrayInputStream(byte[] buf, int offset, int length) { mData = buf; mPosition = mMark = offset; mLimit = Math.min(offset + length, buf.length); } @Override public int read() { return (mPosition < mLimit) ? (mData[mPosition++] & 0xff) : -1; } @Override public int read(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } if (mPosition >= mLimit) { return -1; } if (mPosition + len > mLimit) { len = mLimit - mPosition; } if (len <= 0) { return 0; } System.arraycopy(mData, mPosition, b, off, len); mPosition += len; return len; } @Override public long skip(long len) { if (mPosition + len > mLimit) { len = mLimit - mPosition; } if (len <= 0) { return 0; } mPosition += len; return len; } @Override public int available() { return mLimit - mPosition; } @Override public boolean markSupported() { return true; } @Override public void mark(int readAheadLimit) { mMark = mPosition; } @Override public void reset() { mPosition = mMark; } @Override public void close() throws IOException {} public int position() { return mPosition; } public void position(int newPosition) { mPosition = newPosition; } public int size() { return mData == null ? 0 : mData.length; } }
6,849
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java
/* * 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.constants.CommonConstants; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Miscellaneous io utility methods. * Mainly for internal use within the framework. * * @since 2.0.7 */ public class IOUtils { private static final int BUFFER_SIZE = 1024 * 8; public static final int EOF = -1; private IOUtils() {} /** * write. * * @param is InputStream instance. * @param os OutputStream instance. * @return count. * @throws IOException If an I/O error occurs */ public static long write(InputStream is, OutputStream os) throws IOException { return write(is, os, BUFFER_SIZE); } /** * write. * * @param is InputStream instance. * @param os OutputStream instance. * @param bufferSize buffer size. * @return count. * @throws IOException If an I/O error occurs */ public static long write(InputStream is, OutputStream os, int bufferSize) throws IOException { byte[] buff = new byte[bufferSize]; return write(is, os, buff); } /** * write. * * @param input InputStream instance. * @param output OutputStream instance. * @param buffer buffer byte array * @return count. * @throws IOException If an I/O error occurs */ public static long write(final InputStream input, final OutputStream output, final byte[] buffer) throws IOException { long count = 0; int n; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * read string. * * @param reader Reader instance. * @return String. * @throws IOException If an I/O error occurs */ public static String read(Reader reader) throws IOException { try (StringWriter writer = new StringWriter()) { write(reader, writer); return writer.getBuffer().toString(); } } /** * write string. * * @param writer Writer instance. * @param string String. * @throws IOException If an I/O error occurs */ public static long write(Writer writer, String string) throws IOException { try (Reader reader = new StringReader(string)) { return write(reader, writer); } } /** * write. * * @param reader Reader. * @param writer Writer. * @return count. * @throws IOException If an I/O error occurs */ public static long write(Reader reader, Writer writer) throws IOException { return write(reader, writer, BUFFER_SIZE); } /** * write. * * @param reader Reader. * @param writer Writer. * @param bufferSize buffer size. * @return count. * @throws IOException If an I/O error occurs */ public static long write(Reader reader, Writer writer, int bufferSize) throws IOException { int read; long total = 0; char[] buf = new char[bufferSize]; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); total += read; } return total; } /** * read lines. * * @param file file. * @return lines. * @throws IOException If an I/O error occurs */ public static String[] readLines(File file) throws IOException { if (file == null || !file.exists() || !file.canRead()) { return new String[0]; } return readLines(new FileInputStream(file)); } /** * read lines. * * @param is input stream. * @return lines. * @throws IOException If an I/O error occurs */ public static String[] readLines(InputStream is) throws IOException { List<String> lines = new ArrayList<String>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines.toArray(new String[0]); } } public static String read(InputStream is, String encoding) throws IOException { StringBuilder stringBuilder = new StringBuilder(); InputStreamReader inputStreamReader = new InputStreamReader(is, encoding); char[] buf = new char[1024]; int len; while ((len = inputStreamReader.read(buf)) != -1) { stringBuilder.append(buf, 0, len); } inputStreamReader.close(); return stringBuilder.toString(); } /** * write lines. * * @param os output stream. * @param lines lines. * @throws IOException If an I/O error occurs */ public static void writeLines(OutputStream os, String[] lines) throws IOException { try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(os))) { for (String line : lines) { writer.println(line); } writer.flush(); } } /** * write lines. * * @param file file. * @param lines lines. * @throws IOException If an I/O error occurs */ public static void writeLines(File file, String[] lines) throws IOException { if (file == null) { throw new IOException("File is null."); } writeLines(new FileOutputStream(file), lines); } /** * append lines. * * @param file file. * @param lines lines. * @throws IOException If an I/O error occurs */ public static void appendLines(File file, String[] lines) throws IOException { if (file == null) { throw new IOException("File is null."); } writeLines(new FileOutputStream(file, true), lines); } /** * use like spring code * * @param resourceLocation * @return */ public static URL getURL(String resourceLocation) throws FileNotFoundException { Assert.notNull(resourceLocation, "Resource location must not be null"); if (resourceLocation.startsWith(CommonConstants.CLASSPATH_URL_PREFIX)) { String path = resourceLocation.substring(CommonConstants.CLASSPATH_URL_PREFIX.length()); ClassLoader cl = ClassUtils.getClassLoader(); URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path)); if (url == null) { String description = "class path resource [" + path + "]"; throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist"); } return url; } try { // try URL return new URL(resourceLocation); } catch (MalformedURLException ex) { // no URL -> treat as file path try { return new File(resourceLocation).toURI().toURL(); } catch (MalformedURLException ex2) { throw new FileNotFoundException( "Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path"); } } } public static byte[] toByteArray(final InputStream inputStream) throws IOException { try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int n; while (-1 != (n = inputStream.read(buffer))) { byteArrayOutputStream.write(buffer, 0, n); } return byteArrayOutputStream.toByteArray(); } } }
6,850
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.java
/* * 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.constants.CommonConstants; import java.io.OutputStream; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import static java.lang.Thread.State.BLOCKED; import static java.lang.Thread.State.TIMED_WAITING; import static java.lang.Thread.State.WAITING; public class JVMUtil { public static void jstack(OutputStream stream) throws Exception { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); for (ThreadInfo threadInfo : threadMxBean.dumpAllThreads(true, true)) { stream.write(getThreadDumpString(threadInfo).getBytes()); } } private static String getThreadDumpString(ThreadInfo threadInfo) { StringBuilder sb = new StringBuilder("\"" + threadInfo.getThreadName() + "\"" + " Id=" + threadInfo.getThreadId() + " " + threadInfo.getThreadState()); if (threadInfo.getLockName() != null) { sb.append(" on " + threadInfo.getLockName()); } if (threadInfo.getLockOwnerName() != null) { sb.append(" owned by \"" + threadInfo.getLockOwnerName() + "\" Id=" + threadInfo.getLockOwnerId()); } if (threadInfo.isSuspended()) { sb.append(" (suspended)"); } if (threadInfo.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); int i = 0; // default is 32, means only print up to 32 lines int jstackMaxLine = 32; String jstackMaxLineStr = System.getProperty(CommonConstants.DUBBO_JSTACK_MAXLINE); if (StringUtils.isNotEmpty(jstackMaxLineStr)) { try { jstackMaxLine = Integer.parseInt(jstackMaxLineStr); } catch (Exception ignore) { } } StackTraceElement[] stackTrace = threadInfo.getStackTrace(); MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors(); for (; i < stackTrace.length && i < jstackMaxLine; i++) { StackTraceElement ste = stackTrace[i]; sb.append("\tat ").append(ste.toString()); sb.append('\n'); if (i == 0 && threadInfo.getLockInfo() != null) { Thread.State ts = threadInfo.getThreadState(); if (BLOCKED.equals(ts)) { sb.append("\t- blocked on ").append(threadInfo.getLockInfo()); sb.append('\n'); } else if (WAITING.equals(ts) || TIMED_WAITING.equals(ts)) { sb.append("\t- waiting on ").append(threadInfo.getLockInfo()); sb.append('\n'); } } for (MonitorInfo mi : lockedMonitors) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked ").append(mi); sb.append('\n'); } } } if (i < stackTrace.length) { sb.append("\t..."); sb.append('\n'); } LockInfo[] locks = threadInfo.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); return sb.toString(); } }
6,851
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java
/* * 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 java.util.List; /** * The model class of pagination * * @since 2.7.5 */ public interface Page<T> { /** * Gets the offset of request * * @return positive integer */ int getOffset(); /** * Gets the size of request for pagination query * * @return positive integer */ int getPageSize(); /** * Gets the total amount of elements. * * @return the total amount of elements */ int getTotalSize(); /** * Get the number of total pages. * * @return the number of total pages. */ int getTotalPages(); /** * The data of current page * * @return non-null {@link List} */ List<T> getData(); /** * The size of {@link #getData() data} * * @return positive integer */ default int getDataSize() { return getData().size(); } /** * It indicates has next page or not * * @return if has , return <code>true</code>, or <code>false</code> */ boolean hasNext(); /** * Returns whether the page has data at all. * * @return */ default boolean hasData() { return getDataSize() > 0; } }
6,852
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java
/* * 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.io.UnsafeStringWriter; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.valueOf; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DOT_REGEX; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEPARATOR_REGEX; import static org.apache.dubbo.common.constants.CommonConstants.UNDERLINE_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION; /** * StringUtils */ public final class StringUtils { public static final String EMPTY_STRING = ""; public static final int INDEX_NOT_FOUND = -1; public static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(StringUtils.class); private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); // key value pair pattern. private static final Pattern NUM_PATTERN = Pattern.compile("^\\d+$"); private static final Pattern PARAMETERS_PATTERN = Pattern.compile("^\\[((\\s*\\{\\s*[\\w_\\-\\.]+\\s*:\\s*.+?\\s*\\}\\s*,?\\s*)+)\\s*\\]$"); private static final Pattern PAIR_PARAMETERS_PATTERN = Pattern.compile("^\\{\\s*([\\w-_\\.]+)\\s*:\\s*(.+)\\s*\\}$"); private static final int PAD_LIMIT = 8192; private static final byte[] HEX2B; /** * @since 2.7.5 */ public static final char EQUAL_CHAR = '='; public static final String EQUAL = valueOf(EQUAL_CHAR); public static final char AND_CHAR = '&'; public static final String AND = valueOf(AND_CHAR); public static final char SEMICOLON_CHAR = ';'; public static final String SEMICOLON = valueOf(SEMICOLON_CHAR); public static final char QUESTION_MASK_CHAR = '?'; public static final String QUESTION_MASK = valueOf(QUESTION_MASK_CHAR); public static final char SLASH_CHAR = '/'; public static final String SLASH = valueOf(SLASH_CHAR); public static final char HYPHEN_CHAR = '-'; public static final String HYPHEN = valueOf(HYPHEN_CHAR); static { HEX2B = new byte[128]; Arrays.fill(HEX2B, (byte) -1); HEX2B['0'] = (byte) 0; HEX2B['1'] = (byte) 1; HEX2B['2'] = (byte) 2; HEX2B['3'] = (byte) 3; HEX2B['4'] = (byte) 4; HEX2B['5'] = (byte) 5; HEX2B['6'] = (byte) 6; HEX2B['7'] = (byte) 7; HEX2B['8'] = (byte) 8; HEX2B['9'] = (byte) 9; HEX2B['A'] = (byte) 10; HEX2B['B'] = (byte) 11; HEX2B['C'] = (byte) 12; HEX2B['D'] = (byte) 13; HEX2B['E'] = (byte) 14; HEX2B['F'] = (byte) 15; HEX2B['a'] = (byte) 10; HEX2B['b'] = (byte) 11; HEX2B['c'] = (byte) 12; HEX2B['d'] = (byte) 13; HEX2B['e'] = (byte) 14; HEX2B['f'] = (byte) 15; } private StringUtils() {} /** * Gets a CharSequence length or {@code 0} if the CharSequence is * {@code null}. * * @param cs a CharSequence or {@code null} * @return CharSequence length or {@code 0} if the CharSequence is * {@code null}. */ public static int length(final CharSequence cs) { return cs == null ? 0 : cs.length(); } /** * <p>Repeat a String {@code repeat} times to form a * new String.</p> * * <pre> * StringUtils.repeat(null, 2) = null * StringUtils.repeat("", 0) = "" * StringUtils.repeat("", 2) = "" * StringUtils.repeat("a", 3) = "aaa" * StringUtils.repeat("ab", 2) = "abab" * StringUtils.repeat("a", -2) = "" * </pre> * * @param str the String to repeat, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * {@code null} if null String input */ public static String repeat(final String str, final int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } if (repeat <= 0) { return EMPTY_STRING; } final int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return repeat(str.charAt(0), repeat); } final int outputLength = inputLength * repeat; switch (inputLength) { case 1: return repeat(str.charAt(0), repeat); case 2: final char ch0 = str.charAt(0); final char ch1 = str.charAt(1); final char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default: final StringBuilder buf = new StringBuilder(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } } /** * <p>Repeat a String {@code repeat} times to form a * new String, with a String separator injected each time. </p> * * <pre> * StringUtils.repeat(null, null, 2) = null * StringUtils.repeat(null, "x", 2) = null * StringUtils.repeat("", null, 0) = "" * StringUtils.repeat("", "", 2) = "" * StringUtils.repeat("", "x", 3) = "xxx" * StringUtils.repeat("?", ", ", 3) = "?, ?, ?" * </pre> * * @param str the String to repeat, may be null * @param separator the String to inject, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * {@code null} if null String input * @since 2.5 */ public static String repeat(final String str, final String separator, final int repeat) { if (str == null || separator == null) { return repeat(str, repeat); } // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it final String result = repeat(str + separator, repeat); return removeEnd(result, separator); } /** * <p>Removes a substring only if it is at the end of a source string, * otherwise returns the source string.</p> * * <p>A {@code null} source string will return {@code null}. * An empty ("") source string will return the empty string. * A {@code null} search string will return the source string.</p> * * <pre> * StringUtils.removeEnd(null, *) = null * StringUtils.removeEnd("", *) = "" * StringUtils.removeEnd(*, null) = * * StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com" * StringUtils.removeEnd("www.domain.com", ".com") = "www.domain" * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com" * StringUtils.removeEnd("abc", "") = "abc" * </pre> * * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * {@code null} if null String input */ public static String removeEnd(final String str, final String remove) { if (isAnyEmpty(str, remove)) { return str; } if (str.endsWith(remove)) { return str.substring(0, str.length() - remove.length()); } return str; } /** * <p>Returns padding using the specified delimiter repeated * to a given length.</p> * * <pre> * StringUtils.repeat('e', 0) = "" * StringUtils.repeat('e', 3) = "eee" * StringUtils.repeat('e', -2) = "" * </pre> * * <p>Note: this method doesn't not support padding with * <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> * as they require a pair of {@code char}s to be represented. * If you are needing to support full I18N of your applications * consider using {@link #repeat(String, int)} instead. * </p> * * @param ch character to repeat * @param repeat number of times to repeat char, negative treated as zero * @return String with repeated character * @see #repeat(String, int) */ public static String repeat(final char ch, final int repeat) { final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } /** * <p>Strips any of a set of characters from the end of a String.</p> * * <p>A {@code null} input String returns {@code null}. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is {@code null}, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripEnd(null, *) = null * StringUtils.stripEnd("", *) = "" * StringUtils.stripEnd("abc", "") = "abc" * StringUtils.stripEnd("abc", null) = "abc" * StringUtils.stripEnd(" abc", null) = " abc" * StringUtils.stripEnd("abc ", null) = "abc" * StringUtils.stripEnd(" abc ", null) = " abc" * StringUtils.stripEnd(" abcyx", "xyz") = " abc" * StringUtils.stripEnd("120.00", ".0") = "12" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the set of characters to remove, null treated as whitespace * @return the stripped String, {@code null} if null String input */ public static String stripEnd(final String str, final String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.isEmpty()) { return str; } else { while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) { end--; } } return str.substring(0, end); } /** * <p>Replaces all occurrences of a String within another String.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *) = null * StringUtils.replace("", *, *) = "" * StringUtils.replace("any", null, *) = "any" * StringUtils.replace("any", *, null) = "any" * StringUtils.replace("any", "", *) = "any" * StringUtils.replace("aba", "a", null) = "aba" * StringUtils.replace("aba", "a", "") = "b" * StringUtils.replace("aba", "a", "z") = "zbz" * </pre> * * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace it with, may be null * @return the text with any replacements processed, * {@code null} if null String input * @see #replace(String text, String searchString, String replacement, int max) */ public static String replace(final String text, final String searchString, final String replacement) { return replace(text, searchString, replacement, -1); } /** * <p>Replaces a String with another String inside a larger String, * for the first {@code max} values of the search String.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *, *) = null * StringUtils.replace("", *, *, *) = "" * StringUtils.replace("any", null, *, *) = "any" * StringUtils.replace("any", *, null, *) = "any" * StringUtils.replace("any", "", *, *) = "any" * StringUtils.replace("any", *, *, 0) = "any" * StringUtils.replace("abaa", "a", null, -1) = "abaa" * StringUtils.replace("abaa", "a", "", -1) = "b" * StringUtils.replace("abaa", "a", "z", 0) = "abaa" * StringUtils.replace("abaa", "a", "z", 1) = "zbaa" * StringUtils.replace("abaa", "a", "z", 2) = "zbza" * StringUtils.replace("abaa", "a", "z", -1) = "zbzz" * </pre> * * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace it with, may be null * @param max maximum number of values to replace, or {@code -1} if no maximum * @return the text with any replacements processed, * {@code null} if null String input */ public static String replace(final String text, final String searchString, final String replacement, int max) { if (isAnyEmpty(text, searchString) || replacement == null || max == 0) { return text; } int start = 0; int end = text.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; } final int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = increase < 0 ? 0 : increase; increase *= max < 0 ? 16 : max > 64 ? 64 : max; final StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text, start, end).append(replacement); start = end + replLength; if (--max == 0) { break; } end = text.indexOf(searchString, start); } buf.append(text.substring(start)); return buf.toString(); } public static boolean isBlank(CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * is not blank string. * * @param cs source string. * @return is not blank. */ public static boolean isNotBlank(CharSequence cs) { return !isBlank(cs); } /** * Check the cs String whether contains non whitespace characters. * * @param cs * @return */ public static boolean hasText(CharSequence cs) { return !isBlank(cs); } /** * is empty string. * * @param str source string. * @return is empty. */ public static boolean isEmpty(String str) { return str == null || str.isEmpty(); } /** * <p>Checks if the strings contain empty or null elements. <p/> * * <pre> * StringUtils.isNoneEmpty(null) = false * StringUtils.isNoneEmpty("") = false * StringUtils.isNoneEmpty(" ") = true * StringUtils.isNoneEmpty("abc") = true * StringUtils.isNoneEmpty("abc", "def") = true * StringUtils.isNoneEmpty("abc", null) = false * StringUtils.isNoneEmpty("abc", "") = false * StringUtils.isNoneEmpty("abc", " ") = true * </pre> * * @param ss the strings to check * @return {@code true} if all strings are not empty or null */ public static boolean isNoneEmpty(final String... ss) { if (ArrayUtils.isEmpty(ss)) { return false; } for (final String s : ss) { if (isEmpty(s)) { return false; } } return true; } /** * <p>Checks if the strings contain at least on empty or null element. <p/> * * <pre> * StringUtils.isAnyEmpty(null) = true * StringUtils.isAnyEmpty("") = true * StringUtils.isAnyEmpty(" ") = false * StringUtils.isAnyEmpty("abc") = false * StringUtils.isAnyEmpty("abc", "def") = false * StringUtils.isAnyEmpty("abc", null) = true * StringUtils.isAnyEmpty("abc", "") = true * StringUtils.isAnyEmpty("abc", " ") = false * </pre> * * @param ss the strings to check * @return {@code true} if at least one in the strings is empty or null */ public static boolean isAnyEmpty(final String... ss) { return !isNoneEmpty(ss); } /** * is not empty string. * * @param str source string. * @return is not empty. */ public static boolean isNotEmpty(String str) { return !isEmpty(str); } /** * if s1 is null and s2 is null, then return true * * @param s1 str1 * @param s2 str2 * @return equals */ public static boolean isEquals(String s1, String s2) { if (s1 == null && s2 == null) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } /** * is positive integer or zero string. * * @param str a string * @return is positive integer or zero */ public static boolean isNumber(String str) { return isNotEmpty(str) && NUM_PATTERN.matcher(str).matches(); } /** * parse str to Integer(if str is not number or n < 0, then return 0) * * @param str a number str * @return positive integer or zero */ public static int parseInteger(String str) { return isNumber(str) ? Integer.parseInt(str) : 0; } /** * parse str to Long(if str is not number or n < 0, then return 0) * * @param str a number str * @return positive long or zero */ public static long parseLong(String str) { return isNumber(str) ? Long.parseLong(str) : 0; } /** * Returns true if s is a legal Java identifier.<p> * <a href="http://www.exampledepot.com/egs/java.lang/IsJavaId.html">more info.</a> */ public static boolean isJavaIdentifier(String s) { if (isEmpty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { if (!Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; } public static boolean isContains(String values, String value) { return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value); } public static boolean isContains(String str, char ch) { return isNotEmpty(str) && str.indexOf(ch) >= 0; } public static boolean isNotContains(String str, char ch) { return !isContains(str, ch); } /** * @param values * @param value * @return contains */ public static boolean isContains(String[] values, String value) { if (isNotEmpty(value) && ArrayUtils.isNotEmpty(values)) { for (String v : values) { if (value.equals(v)) { return true; } } } return false; } public static boolean isNumeric(String str, boolean allowDot) { if (str == null || str.isEmpty()) { return false; } boolean hasDot = false; int sz = str.length(); for (int i = 0; i < sz; i++) { if (str.charAt(i) == '.') { if (hasDot || !allowDot) { return false; } hasDot = true; continue; } if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** * @param e * @return string */ public static String toString(Throwable e) { UnsafeStringWriter w = new UnsafeStringWriter(); PrintWriter p = new PrintWriter(w); p.print(e.getClass().getName()); if (e.getMessage() != null) { p.print(": " + e.getMessage()); } p.println(); try { e.printStackTrace(p); return w.toString(); } finally { p.close(); } } /** * @param msg * @param e * @return string */ public static String toString(String msg, Throwable e) { UnsafeStringWriter w = new UnsafeStringWriter(); w.write(msg + "\n"); PrintWriter p = new PrintWriter(w); try { e.printStackTrace(p); return w.toString(); } finally { p.close(); } } /** * translate. * * @param src source string. * @param from src char table. * @param to target char table. * @return String. */ public static String translate(String src, String from, String to) { if (isEmpty(src)) { return src; } StringBuilder sb = null; int ix; char c; for (int i = 0, len = src.length(); i < len; i++) { c = src.charAt(i); ix = from.indexOf(c); if (ix == -1) { if (sb != null) { sb.append(c); } } else { if (sb == null) { sb = new StringBuilder(len); sb.append(src, 0, i); } if (ix < to.length()) { sb.append(to.charAt(ix)); } } } return sb == null ? src : sb.toString(); } /** * split. * * @param ch char. * @return string array. */ public static String[] split(String str, char ch) { if (isEmpty(str)) { return EMPTY_STRING_ARRAY; } return splitToList0(str, ch).toArray(EMPTY_STRING_ARRAY); } private static List<String> splitToList0(String str, char ch) { List<String> result = new ArrayList<>(); int ix = 0, len = str.length(); for (int i = 0; i < len; i++) { if (str.charAt(i) == ch) { result.add(str.substring(ix, i)); ix = i + 1; } } if (ix >= 0) { result.add(str.substring(ix)); } return result; } /** * Splits String around matches of the given character. * <p> * Note: Compare with {@link StringUtils#split(String, char)}, this method reduce memory copy. */ public static List<String> splitToList(String str, char ch) { if (isEmpty(str)) { return Collections.emptyList(); } return splitToList0(str, ch); } /** * Split the specified value to be a {@link Set} * * @param value the content to be split * @param separatorChar a char to separate * @return non-null read-only {@link Set} * @since 2.7.8 */ public static Set<String> splitToSet(String value, char separatorChar) { return splitToSet(value, separatorChar, false); } /** * Split the specified value to be a {@link Set} * * @param value the content to be split * @param separatorChar a char to separate * @param trimElements require to trim the elements or not * @return non-null read-only {@link Set} * @since 2.7.8 */ public static Set<String> splitToSet(String value, char separatorChar, boolean trimElements) { List<String> values = splitToList(value, separatorChar); int size = values.size(); if (size < 1) { // empty condition return emptySet(); } if (!trimElements) { // Do not require to trim the elements return new LinkedHashSet(values); } return unmodifiableSet(values.stream().map(String::trim).collect(LinkedHashSet::new, Set::add, Set::addAll)); } /** * join string. * * @param array String array. * @return String. */ public static String join(String[] array) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (String s : array) { sb.append(s); } return sb.toString(); } /** * join string like javascript. * * @param array String array. * @param split split * @return String. */ public static String join(String[] array, char split) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (i > 0) { sb.append(split); } sb.append(array[i]); } return sb.toString(); } /** * join string like javascript. * * @param array String array. * @param split split * @return String. */ public static String join(String[] array, String split) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (i > 0) { sb.append(split); } sb.append(array[i]); } return sb.toString(); } public static String join(Collection<String> coll, String split) { if (CollectionUtils.isEmpty(coll)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (String s : coll) { if (isFirst) { isFirst = false; } else { sb.append(split); } sb.append(s); } return sb.toString(); } /** * parse key-value pair. * * @param str string. * @param itemSeparator item separator. * @return key-value map; */ private static Map<String, String> parseKeyValuePair(String str, String itemSeparator) { String[] tmp = str.split(itemSeparator); Map<String, String> map = new HashMap<String, String>(tmp.length); for (int i = 0; i < tmp.length; i++) { Matcher matcher = KVP_PATTERN.matcher(tmp[i]); if (!matcher.matches()) { continue; } map.put(matcher.group(1), matcher.group(2)); } return map; } public static String getQueryStringValue(String qs, String key) { Map<String, String> map = parseQueryString(qs); return map.get(key); } /** * parse query string to Parameters. * * @param qs query string. * @return Parameters instance. */ public static Map<String, String> parseQueryString(String qs) { if (isEmpty(qs)) { return new HashMap<String, String>(); } return parseKeyValuePair(qs, "\\&"); } public static String getServiceKey(Map<String, String> ps) { StringBuilder buf = new StringBuilder(); String group = ps.get(GROUP_KEY); if (isNotEmpty(group)) { buf.append(group).append('/'); } buf.append(ps.get(INTERFACE_KEY)); String version = ps.get(VERSION_KEY); if (isNotEmpty(group)) { buf.append(':').append(version); } return buf.toString(); } public static String toQueryString(Map<String, String> ps) { StringBuilder buf = new StringBuilder(); if (ps != null && ps.size() > 0) { for (Map.Entry<String, String> entry : new TreeMap<String, String>(ps).entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (isNoneEmpty(key, value)) { if (buf.length() > 0) { buf.append('&'); } buf.append(key); buf.append('='); buf.append(value); } } } return buf.toString(); } public static String camelToSplitName(String camelName, String split) { if (isEmpty(camelName)) { return camelName; } if (!isWord(camelName)) { // convert Ab-Cd-Ef to ab-cd-ef if (isSplitCase(camelName, split.charAt(0))) { return camelName.toLowerCase(); } // not camel case return camelName; } StringBuilder buf = null; for (int i = 0; i < camelName.length(); i++) { char ch = camelName.charAt(i); if (ch >= 'A' && ch <= 'Z') { if (buf == null) { buf = new StringBuilder(); if (i > 0) { buf.append(camelName, 0, i); } } if (i > 0) { buf.append(split); } buf.append(Character.toLowerCase(ch)); } else if (buf != null) { buf.append(ch); } } return buf == null ? camelName.toLowerCase() : buf.toString().toLowerCase(); } private static boolean isSplitCase(String str, char separator) { if (str == null) { return false; } return str.chars().allMatch(ch -> (ch == separator) || isWord((char) ch)); } private static boolean isWord(String str) { if (str == null) { return false; } return str.chars().allMatch(ch -> isWord((char) ch)); } private static boolean isWord(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) { return true; } return false; } /** * Convert snake_case or SNAKE_CASE to kebab-case. * <p> * NOTE: Return itself if it's not a snake case. * * @param snakeName * @param split * @return */ public static String snakeToSplitName(String snakeName, String split) { String lowerCase = snakeName.toLowerCase(); if (isSnakeCase(snakeName)) { return replace(lowerCase, "_", split); } return snakeName; } protected static boolean isSnakeCase(String str) { return str.contains("_") || str.equals(str.toLowerCase()) || str.equals(str.toUpperCase()); } /** * Convert camelCase or snake_case/SNAKE_CASE to kebab-case * * @param str * @param split * @return */ public static String convertToSplitName(String str, String split) { if (isSnakeCase(str)) { return snakeToSplitName(str, split); } else { return camelToSplitName(str, split); } } public static String toArgumentString(Object[] args) { StringBuilder buf = new StringBuilder(); for (Object arg : args) { if (buf.length() > 0) { buf.append(COMMA_SEPARATOR); } if (arg == null || ReflectUtils.isPrimitives(arg.getClass())) { buf.append(arg); } else { try { buf.append(JsonUtils.toJson(arg)); } catch (Exception e) { logger.warn(COMMON_JSON_CONVERT_EXCEPTION, "", "", e.getMessage(), e); buf.append(arg); } } } return buf.toString(); } public static String trim(String str) { return str == null ? null : str.trim(); } public static String toURLKey(String key) { return key.toLowerCase().replaceAll(SEPARATOR_REGEX, HIDE_KEY_PREFIX); } public static String toOSStyleKey(String key) { key = key.toUpperCase().replaceAll(DOT_REGEX, UNDERLINE_SEPARATOR); if (!key.startsWith("DUBBO_")) { key = "DUBBO_" + key; } return key; } public static boolean isAllUpperCase(String str) { if (str != null && !isEmpty(str)) { int sz = str.length(); for (int i = 0; i < sz; ++i) { if (!Character.isUpperCase(str.charAt(i))) { return false; } } return true; } else { return false; } } public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, (String) null); } public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) { if (str == null) { return new String[0]; } else if (delimiter == null) { return new String[] {str}; } else { List<String> result = new ArrayList(); int pos; if ("".equals(delimiter)) { for (pos = 0; pos < str.length(); ++pos) { result.add(deleteAny(str.substring(pos, pos + 1), charsToDelete)); } } else { int delPos; for (pos = 0; (delPos = str.indexOf(delimiter, pos)) != -1; pos = delPos + delimiter.length()) { result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); } if (str.length() > 0 && pos <= str.length()) { result.add(deleteAny(str.substring(pos), charsToDelete)); } } return toStringArray((Collection) result); } } public static String arrayToDelimitedString(Object[] arr, String delim) { if (ArrayUtils.isEmpty(arr)) { return ""; } else if (arr.length == 1) { return nullSafeToString(arr[0]); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; ++i) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } } public static String deleteAny(String inString, String charsToDelete) { if (isNotEmpty(inString) && isNotEmpty(charsToDelete)) { StringBuilder sb = new StringBuilder(inString.length()); for (int i = 0; i < inString.length(); ++i) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { sb.append(c); } } return sb.toString(); } else { return inString; } } public static String[] toStringArray(Collection<String> collection) { return (String[]) collection.toArray(new String[0]); } public static String nullSafeToString(Object obj) { if (obj == null) { return "null"; } else if (obj instanceof String) { return (String) obj; } else { String str = obj.toString(); return str != null ? str : ""; } } /** * Decode parameters string to map * * @param rawParameters format like '[{a:b},{c:d}]' * @return */ public static Map<String, String> parseParameters(String rawParameters) { if (StringUtils.isBlank(rawParameters)) { return Collections.emptyMap(); } Matcher matcher = PARAMETERS_PATTERN.matcher(rawParameters); if (!matcher.matches()) { return Collections.emptyMap(); } String pairs = matcher.group(1); String[] pairArr = pairs.split("\\s*,\\s*"); Map<String, String> parameters = new HashMap<>(); for (String pair : pairArr) { Matcher pairMatcher = PAIR_PARAMETERS_PATTERN.matcher(pair); if (pairMatcher.matches()) { parameters.put(pairMatcher.group(1), pairMatcher.group(2)); } } return parameters; } /** * Encode parameters map to string, like '[{a:b},{c:d}]' * * @param params * @return */ public static String encodeParameters(Map<String, String> params) { if (params == null || params.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); sb.append('['); params.forEach((key, value) -> { // {key:value}, if (hasText(value)) { sb.append('{').append(key).append(':').append(value).append("},"); } }); // delete last separator ',' if (sb.charAt(sb.length() - 1) == ',') { sb.deleteCharAt(sb.length() - 1); } sb.append(']'); return sb.toString(); } public static int decodeHexNibble(final char c) { // Character.digit() is not used here, as it addresses a larger // set of characters (both ASCII and full-width latin letters). byte[] hex2b = HEX2B; return c < hex2b.length ? hex2b[c] : -1; } /** * Decode a 2-digit hex byte from within a string. */ public static byte decodeHexByte(CharSequence s, int pos) { int hi = decodeHexNibble(s.charAt(pos)); int lo = decodeHexNibble(s.charAt(pos + 1)); if (hi == -1 || lo == -1) { throw new IllegalArgumentException( String.format("invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s)); } return (byte) ((hi << 4) + lo); } /** * Create the common-delimited {@link String} by one or more {@link String} members * * @param one one {@link String} * @param others others {@link String} * @return <code>null</code> if <code>one</code> or <code>others</code> is <code>null</code> * @since 2.7.8 */ public static String toCommaDelimitedString(String one, String... others) { String another = arrayToDelimitedString(others, COMMA_SEPARATOR); return isEmpty(another) ? one : one + COMMA_SEPARATOR + another; } /** * Test str whether starts with the prefix ignore case. * * @param str * @param prefix * @return */ public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null || str.length() < prefix.length()) { return false; } // return str.substring(0, prefix.length()).equalsIgnoreCase(prefix); return str.regionMatches(true, 0, prefix, 0, prefix.length()); } }
6,853
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java
/* * The MIT License * * Copyright (c) 2013 Edin Dazdarevic (edin.dazdarevic@gmail.com) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package org.apache.dubbo.common.utils; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * A class that enables to get an IP range from CIDR specification. It supports * both IPv4 and IPv6. * <p> * From https://github.com/edazdarevic/CIDRUtils/blob/master/CIDRUtils.java */ public class CIDRUtils { private final String cidr; private InetAddress inetAddress; private InetAddress startAddress; private InetAddress endAddress; private final int prefixLength; public CIDRUtils(String cidr) throws UnknownHostException { this.cidr = cidr; /* split CIDR to address and prefix part */ if (this.cidr.contains("/")) { int index = this.cidr.indexOf("/"); String addressPart = this.cidr.substring(0, index); String networkPart = this.cidr.substring(index + 1); inetAddress = InetAddress.getByName(addressPart); prefixLength = Integer.parseInt(networkPart); calculate(); } else { throw new IllegalArgumentException("not an valid CIDR format!"); } } private void calculate() throws UnknownHostException { ByteBuffer maskBuffer; int targetSize; if (inetAddress.getAddress().length == 4) { maskBuffer = ByteBuffer .allocate(4) .putInt(-1); targetSize = 4; } else { maskBuffer = ByteBuffer.allocate(16) .putLong(-1L) .putLong(-1L); targetSize = 16; } BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength); ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress()); BigInteger ipVal = new BigInteger(1, buffer.array()); BigInteger startIp = ipVal.and(mask); BigInteger endIp = startIp.add(mask.not()); byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize); byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize); this.startAddress = InetAddress.getByAddress(startIpArr); this.endAddress = InetAddress.getByAddress(endIpArr); } private byte[] toBytes(byte[] array, int targetSize) { int counter = 0; List<Byte> newArr = new ArrayList<Byte>(); while (counter < targetSize && (array.length - 1 - counter >= 0)) { newArr.add(0, array[array.length - 1 - counter]); counter++; } int size = newArr.size(); for (int i = 0; i < (targetSize - size); i++) { newArr.add(0, (byte) 0); } byte[] ret = new byte[newArr.size()]; for (int i = 0; i < newArr.size(); i++) { ret[i] = newArr.get(i); } return ret; } public String getNetworkAddress() { return this.startAddress.getHostAddress(); } public String getBroadcastAddress() { return this.endAddress.getHostAddress(); } public boolean isInRange(String ipAddress) throws UnknownHostException { InetAddress address = InetAddress.getByName(ipAddress); BigInteger start = new BigInteger(1, this.startAddress.getAddress()); BigInteger end = new BigInteger(1, this.endAddress.getAddress()); BigInteger target = new BigInteger(1, address.getAddress()); int st = start.compareTo(target); int te = target.compareTo(end); return (st == -1 || st == 0) && (te == -1 || te == 0); } }
6,854
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NamedThreadFactory.java
/* * 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 java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * InternalThreadFactory. */ public class NamedThreadFactory implements ThreadFactory { protected static final AtomicInteger POOL_SEQ = new AtomicInteger(1); protected final AtomicInteger mThreadNum = new AtomicInteger(1); protected final String mPrefix; protected final boolean mDaemon; protected final ThreadGroup mGroup; public NamedThreadFactory() { this("pool-" + POOL_SEQ.getAndIncrement(), false); } public NamedThreadFactory(String prefix) { this(prefix, false); } public NamedThreadFactory(String prefix, boolean daemon) { mPrefix = prefix + "-thread-"; mDaemon = daemon; SecurityManager s = System.getSecurityManager(); mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); } @Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); Thread ret = new Thread(mGroup, runnable, name, 0); ret.setDaemon(mDaemon); return ret; } public ThreadGroup getThreadGroup() { return mGroup; } // for test public AtomicInteger getThreadNum() { return mThreadNum; } }
6,855
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java
/* * 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.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.TreeMap; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; import java.util.function.Supplier; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom; /** * PojoUtils. Travel object deeply, and convert complex type to simple type. * <p/> * Simple type below will be remained: * <ul> * <li> Primitive Type, also include <b>String</b>, <b>Number</b>(Integer, Long), <b>Date</b> * <li> Array of Primitive Type * <li> Collection, eg: List, Map, Set etc. * </ul> * <p/> * Other type will be covert to a map which contains the attributes and value pair of object. * <p> * TODO: exact PojoUtils to scope bean */ public class PojoUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PojoUtils.class); private static final ConcurrentMap<String, Method> NAME_METHODS_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<Class<?>, ConcurrentMap<String, Field>> CLASS_FIELD_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, Object> CLASS_NOT_FOUND_CACHE = new ConcurrentHashMap<>(); private static final Object NOT_FOUND_VALUE = new Object(); private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean(ConfigurationUtils.getProperty( ApplicationModel.defaultModel(), CommonConstants.GENERIC_WITH_CLZ_KEY, "true")); private static final List<Class<?>> CLASS_CAN_BE_STRING = Arrays.asList( Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Boolean.class, Character.class); public static Object[] generalize(Object[] objs) { Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = generalize(objs[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes) { if (objs.length != types.length || objs.length != gtypes.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i], gtypes[i]); } return dests; } public static Object generalize(Object pojo) { return generalize(pojo, new IdentityHashMap<>()); } @SuppressWarnings("unchecked") private static Object generalize(Object pojo, Map<Object, Object> history) { if (pojo == null) { return null; } if (pojo instanceof Enum<?>) { return ((Enum<?>) pojo).name(); } if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { int len = Array.getLength(pojo); String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = ((Enum<?>) Array.get(pojo, i)).name(); } return values; } if (ReflectUtils.isPrimitives(pojo.getClass())) { return pojo; } if (pojo instanceof LocalDate || pojo instanceof LocalDateTime || pojo instanceof LocalTime) { return pojo.toString(); } if (pojo instanceof Class) { return ((Class) pojo).getName(); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); if (pojo.getClass().isArray()) { int len = Array.getLength(pojo); Object[] dest = new Object[len]; history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); dest[i] = generalize(obj, history); } return dest; } if (pojo instanceof Collection<?>) { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = (pojo instanceof List<?>) ? new ArrayList<>(len) : new HashSet<>(len); history.put(pojo, dest); for (Object obj : src) { dest.add(generalize(obj, history)); } return dest; } if (pojo instanceof Map<?, ?>) { Map<Object, Object> src = (Map<Object, Object>) pojo; Map<Object, Object> dest = createMap(src); history.put(pojo, dest); for (Map.Entry<Object, Object> obj : src.entrySet()) { dest.put(generalize(obj.getKey(), history), generalize(obj.getValue(), history)); } return dest; } Map<String, Object> map = new HashMap<>(); history.put(pojo, map); if (GENERIC_WITH_CLZ) { map.put("class", pojo.getClass().getName()); } for (Method method : pojo.getClass().getMethods()) { if (ReflectUtils.isBeanPropertyReadMethod(method)) { ReflectUtils.makeAccessible(method); try { map.put( ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // public field for (Field field : pojo.getClass().getFields()) { if (ReflectUtils.isPublicInstanceField(field)) { try { Object fieldValue = field.get(pojo); if (history.containsKey(pojo)) { Object pojoGeneralizedValue = history.get(pojo); if (pojoGeneralizedValue instanceof Map && ((Map) pojoGeneralizedValue).containsKey(field.getName())) { continue; } } if (fieldValue != null) { map.put(field.getName(), generalize(fieldValue, history)); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } return map; } public static Object realize(Object pojo, Class<?> type) { return realize0(pojo, type, null, new IdentityHashMap<>()); } public static Object realize(Object pojo, Class<?> type, Type genericType) { return realize0(pojo, type, genericType, new IdentityHashMap<>()); } private static class PojoInvocationHandler implements InvocationHandler { private final Map<Object, Object> map; public PojoInvocationHandler(Map<Object, Object> map) { this.map = map; } @Override @SuppressWarnings("unchecked") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(map, args); } String methodName = method.getName(); Object value = null; if (methodName.length() > 3 && methodName.startsWith("get")) { value = map.get(methodName.substring(3, 4).toLowerCase() + methodName.substring(4)); } else if (methodName.length() > 2 && methodName.startsWith("is")) { value = map.get(methodName.substring(2, 3).toLowerCase() + methodName.substring(3)); } else { value = map.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1)); } if (value instanceof Map<?, ?> && !Map.class.isAssignableFrom(method.getReturnType())) { value = realize0(value, method.getReturnType(), null, new IdentityHashMap<>()); } return value; } } @SuppressWarnings("unchecked") private static Collection<Object> createCollection(Class<?> type, int len) { if (type.isAssignableFrom(ArrayList.class)) { return new ArrayList<>(len); } if (type.isAssignableFrom(HashSet.class)) { return new HashSet<>(len); } if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { try { return (Collection<Object>) type.getDeclaredConstructor().newInstance(); } catch (Exception e) { // ignore } } return new ArrayList<>(); } private static Map createMap(Map src) { Class<? extends Map> cl = src.getClass(); Map result = null; if (HashMap.class == cl) { result = new HashMap(); } else if (Hashtable.class == cl) { result = new Hashtable(); } else if (IdentityHashMap.class == cl) { result = new IdentityHashMap(); } else if (LinkedHashMap.class == cl) { result = new LinkedHashMap(); } else if (Properties.class == cl) { result = new Properties(); } else if (TreeMap.class == cl) { result = new TreeMap(); } else if (WeakHashMap.class == cl) { return new WeakHashMap(); } else if (ConcurrentHashMap.class == cl) { result = new ConcurrentHashMap(); } else if (ConcurrentSkipListMap.class == cl) { result = new ConcurrentSkipListMap(); } else { try { result = cl.getDeclaredConstructor().newInstance(); } catch (Exception e) { /* ignore */ } if (result == null) { try { Constructor<?> constructor = cl.getConstructor(Map.class); result = (Map) constructor.newInstance(Collections.EMPTY_MAP); } catch (Exception e) { /* ignore */ } } } if (result == null) { result = new HashMap<>(); } return result; } @SuppressWarnings({"unchecked", "rawtypes"}) private static Object realize0(Object pojo, Class<?> type, Type genericType, final Map<Object, Object> history) { return realize1(pojo, type, genericType, new HashMap<>(8), history); } private static Object realize1( Object pojo, Class<?> type, Type genericType, final Map<String, Type> mapParent, final Map<Object, Object> history) { if (pojo == null) { return null; } if (type != null && type.isEnum() && pojo.getClass() == String.class) { return Enum.valueOf((Class<Enum>) type, (String) pojo); } if (ReflectUtils.isPrimitives(pojo.getClass()) && !(type != null && type.isArray() && type.getComponentType().isEnum() && pojo.getClass() == String[].class)) { return CompatibleTypeUtils.compatibleTypeConvert(pojo, type); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); Map<String, Type> mapGeneric = new HashMap<>(8); mapGeneric.putAll(mapParent); TypeVariable<? extends Class<?>>[] typeParameters = type.getTypeParameters(); if (genericType instanceof ParameterizedType && typeParameters.length > 0) { ParameterizedType parameterizedType = (ParameterizedType) genericType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeParameters.length; i++) { if (!(actualTypeArguments[i] instanceof TypeVariable)) { mapGeneric.put(typeParameters[i].getTypeName(), actualTypeArguments[i]); } } } if (pojo.getClass().isArray()) { if (Collection.class.isAssignableFrom(type)) { Class<?> ctype = pojo.getClass().getComponentType(); int len = Array.getLength(pojo); Collection dest = createCollection(type, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize1(obj, ctype, null, mapGeneric, history); dest.add(value); } return dest; } else { Class<?> ctype = (type != null && type.isArray() ? type.getComponentType() : pojo.getClass().getComponentType()); int len = Array.getLength(pojo); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize1(obj, ctype, null, mapGeneric, history); Array.set(dest, i, value); } return dest; } } if (pojo instanceof Collection<?>) { if (type.isArray()) { Class<?> ctype = type.getComponentType(); Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); int i = 0; for (Object obj : src) { Object value = realize1(obj, ctype, null, mapGeneric, history); Array.set(dest, i, value); i++; } return dest; } else { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = createCollection(type, len); history.put(pojo, dest); for (Object obj : src) { Type keyType = getGenericClassByIndex(genericType, 0); Class<?> keyClazz = obj == null ? null : obj.getClass(); if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } Object value = realize1(obj, keyClazz, keyType, mapGeneric, history); dest.add(value); } return dest; } } if (pojo instanceof Map<?, ?> && type != null) { Object className = ((Map<Object, Object>) pojo).get("class"); if (className instanceof String) { if (!CLASS_NOT_FOUND_CACHE.containsKey(className)) { try { type = DefaultSerializeClassChecker.getInstance() .loadClass(ClassUtils.getClassLoader(), (String) className); } catch (ClassNotFoundException e) { CLASS_NOT_FOUND_CACHE.put((String) className, NOT_FOUND_VALUE); } } } // special logic for enum if (type.isEnum()) { Object name = ((Map<Object, Object>) pojo).get("name"); if (name != null) { if (!(name instanceof String)) { throw new IllegalArgumentException("`name` filed should be string!"); } else { return Enum.valueOf((Class<Enum>) type, (String) name); } } } Map<Object, Object> map; // when return type is not the subclass of return type from the signature and not an interface if (!type.isInterface() && !type.isAssignableFrom(pojo.getClass())) { try { map = (Map<Object, Object>) type.getDeclaredConstructor().newInstance(); Map<Object, Object> mapPojo = (Map<Object, Object>) pojo; map.putAll(mapPojo); if (GENERIC_WITH_CLZ) { map.remove("class"); } } catch (Exception e) { // ignore error map = (Map<Object, Object>) pojo; } } else { map = (Map<Object, Object>) pojo; } if (Map.class.isAssignableFrom(type) || type == Object.class) { final Map<Object, Object> result; // fix issue#5939 Type mapKeyType = getKeyTypeForMap(map.getClass()); Type typeKeyType = getGenericClassByIndex(genericType, 0); boolean typeMismatch = mapKeyType instanceof Class && typeKeyType instanceof Class && !typeKeyType.getTypeName().equals(mapKeyType.getTypeName()); if (typeMismatch) { result = createMap(new HashMap(0)); } else { result = createMap(map); } history.put(pojo, result); for (Map.Entry<Object, Object> entry : map.entrySet()) { Type keyType = getGenericClassByIndex(genericType, 0); Type valueType = getGenericClassByIndex(genericType, 1); Class<?> keyClazz; if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } else if (keyType instanceof ParameterizedType) { keyClazz = (Class<?>) ((ParameterizedType) keyType).getRawType(); } else { keyClazz = entry.getKey() == null ? null : entry.getKey().getClass(); } Class<?> valueClazz; if (valueType instanceof Class) { valueClazz = (Class<?>) valueType; } else if (valueType instanceof ParameterizedType) { valueClazz = (Class<?>) ((ParameterizedType) valueType).getRawType(); } else { valueClazz = entry.getValue() == null ? null : entry.getValue().getClass(); } Object key = keyClazz == null ? entry.getKey() : realize1(entry.getKey(), keyClazz, keyType, mapGeneric, history); Object value = valueClazz == null ? entry.getValue() : realize1(entry.getValue(), valueClazz, valueType, mapGeneric, history); result.put(key, value); } return result; } else if (type.isInterface()) { Object dest = Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class<?>[] {type}, new PojoInvocationHandler(map)); history.put(pojo, dest); return dest; } else { Object dest; if (Throwable.class.isAssignableFrom(type)) { Object message = map.get("message"); if (message instanceof String) { dest = newThrowableInstance(type, (String) message); } else { dest = newInstance(type); } } else { dest = newInstance(type); } history.put(pojo, dest); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { String name = (String) key; Object value = entry.getValue(); if (value != null) { Method method = getSetterMethod(dest.getClass(), name, value.getClass()); Field field = getAndCacheField(dest.getClass(), name); if (method != null) { if (!method.isAccessible()) { method.setAccessible(true); } Type containType = Optional.ofNullable(field) .map(Field::getGenericType) .map(Type::getTypeName) .map(mapGeneric::get) .orElse(null); if (containType != null) { // is generic if (containType instanceof ParameterizedType) { value = realize1( value, (Class<?>) ((ParameterizedType) containType).getRawType(), containType, mapGeneric, history); } else if (containType instanceof Class) { value = realize1( value, (Class<?>) containType, containType, mapGeneric, history); } else { Type ptype = method.getGenericParameterTypes()[0]; value = realize1( value, method.getParameterTypes()[0], ptype, mapGeneric, history); } } else { Type ptype = method.getGenericParameterTypes()[0]; value = realize1(value, method.getParameterTypes()[0], ptype, mapGeneric, history); } try { method.invoke(dest, value); } catch (Exception e) { String exceptionDescription = "Failed to set pojo " + dest.getClass().getSimpleName() + " property " + name + " value " + value.getClass() + ", cause: " + e.getMessage(); logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", exceptionDescription, e); throw new RuntimeException(exceptionDescription, e); } } else if (field != null) { value = realize1(value, field.getType(), field.getGenericType(), mapGeneric, history); try { field.set(dest, value); } catch (IllegalAccessException e) { throw new RuntimeException( "Failed to set field " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); } } } } } return dest; } } return pojo; } /** * Get key type for {@link Map} directly implemented by {@code clazz}. * If {@code clazz} does not implement {@link Map} directly, return {@code null}. * * @param clazz {@link Class} * @return Return String.class for {@link com.alibaba.fastjson.JSONObject} */ private static Type getKeyTypeForMap(Class<?> clazz) { Type[] interfaces = clazz.getGenericInterfaces(); if (!ArrayUtils.isEmpty(interfaces)) { for (Type type : interfaces) { if (type instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) type; if ("java.util.Map".equals(t.getRawType().getTypeName())) { return t.getActualTypeArguments()[0]; } } } } return null; } /** * Get parameterized type * * @param genericType generic type * @param index index of the target parameterized type * @return Return Person.class for List<Person>, return Person.class for Map<String, Person> when index=0 */ private static Type getGenericClassByIndex(Type genericType, int index) { Type clazz = null; // find parameterized type if (genericType instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) genericType; Type[] types = t.getActualTypeArguments(); clazz = types[index]; } return clazz; } private static Object newThrowableInstance(Class<?> cls, String message) { try { Constructor<?> messagedConstructor = cls.getDeclaredConstructor(String.class); return messagedConstructor.newInstance(message); } catch (Exception t) { return newInstance(cls); } } private static Object newInstance(Class<?> cls) { try { return cls.getDeclaredConstructor().newInstance(); } catch (Exception t) { Constructor<?>[] constructors = cls.getDeclaredConstructors(); /* From Javadoc java.lang.Class#getDeclaredConstructors This method returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. This method returns an array of length 0, if this Class object represents an interface, a primitive type, an array class, or void. */ if (constructors.length == 0) { throw new RuntimeException("Illegal constructor: " + cls.getName()); } Throwable lastError = null; Arrays.sort(constructors, Comparator.comparingInt(a -> a.getParameterTypes().length)); for (Constructor<?> constructor : constructors) { try { constructor.setAccessible(true); Object[] parameters = Arrays.stream(constructor.getParameterTypes()) .map(PojoUtils::getDefaultValue) .toArray(); return constructor.newInstance(parameters); } catch (Exception e) { lastError = e; } } throw new RuntimeException(lastError.getMessage(), lastError); } } /** * return init value * * @param parameterType * @return */ private static Object getDefaultValue(Class<?> parameterType) { if ("char".equals(parameterType.getName())) { return Character.MIN_VALUE; } if ("boolean".equals(parameterType.getName())) { return false; } if ("byte".equals(parameterType.getName())) { return (byte) 0; } if ("short".equals(parameterType.getName())) { return (short) 0; } return parameterType.isPrimitive() ? 0 : null; } private static Method getSetterMethod(Class<?> cls, String property, Class<?> valueCls) { String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); Method method = NAME_METHODS_CACHE.get(cls.getName() + "." + name + "(" + valueCls.getName() + ")"); if (method == null) { try { method = cls.getMethod(name, valueCls); } catch (NoSuchMethodException e) { for (Method m : cls.getMethods()) { if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) { method = m; break; } } } if (method != null) { NAME_METHODS_CACHE.put(cls.getName() + "." + name + "(" + valueCls.getName() + ")", method); } } return method; } private static Field getAndCacheField(Class<?> cls, String fieldName) { Field result; if (CLASS_FIELD_CACHE.containsKey(cls) && CLASS_FIELD_CACHE.get(cls).containsKey(fieldName)) { return CLASS_FIELD_CACHE.get(cls).get(fieldName); } result = getField(cls, fieldName); if (result != null) { ConcurrentMap<String, Field> fields = CLASS_FIELD_CACHE.computeIfAbsent(cls, k -> new ConcurrentHashMap<>()); fields.putIfAbsent(fieldName, result); } return result; } private static Field getField(Class<?> cls, String fieldName) { Field result = null; for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { result = acls.getDeclaredField(fieldName); if (!Modifier.isPublic(result.getModifiers())) { result.setAccessible(true); } } catch (NoSuchFieldException e) { } } if (result == null && cls != null) { for (Field field : cls.getFields()) { if (fieldName.equals(field.getName()) && ReflectUtils.isPublicInstanceField(field)) { result = field; break; } } } return result; } public static boolean isPojo(Class<?> cls) { return !ReflectUtils.isPrimitives(cls) && !Collection.class.isAssignableFrom(cls) && !Map.class.isAssignableFrom(cls); } /** * Update the property if absent * * @param getterMethod the getter method * @param setterMethod the setter method * @param newValue the new value * @param <T> the value type * @since 2.7.8 */ public static <T> void updatePropertyIfAbsent(Supplier<T> getterMethod, Consumer<T> setterMethod, T newValue) { if (newValue != null && getterMethod.get() == null) { setterMethod.accept(newValue); } } /** * convert map to a specific class instance * * @param map map wait for convert * @param cls the specified class * @param <T> the type of {@code cls} * @return class instance declare in param {@code cls} * @throws ReflectiveOperationException if the instance creation is failed * @since 2.7.10 */ public static <T> T mapToPojo(Map<String, Object> map, Class<T> cls) throws ReflectiveOperationException { T instance = cls.getDeclaredConstructor().newInstance(); Map<String, Field> beanPropertyFields = ReflectUtils.getBeanPropertyFields(cls); for (Map.Entry<String, Field> entry : beanPropertyFields.entrySet()) { String name = entry.getKey(); Field field = entry.getValue(); Object mapObject = map.get(name); if (mapObject == null) { continue; } Type type = field.getGenericType(); Object fieldObject = getFieldObject(mapObject, type); field.set(instance, fieldObject); } return instance; } private static Object getFieldObject(Object mapObject, Type fieldType) throws ReflectiveOperationException { if (fieldType instanceof Class<?>) { return convertClassType(mapObject, (Class<?>) fieldType); } else if (fieldType instanceof ParameterizedType) { return convertParameterizedType(mapObject, (ParameterizedType) fieldType); } else if (fieldType instanceof GenericArrayType || fieldType instanceof TypeVariable<?> || fieldType instanceof WildcardType) { // ignore these type currently return null; } else { throw new IllegalArgumentException("Unrecognized Type: " + fieldType.toString()); } } @SuppressWarnings("unchecked") private static Object convertClassType(Object mapObject, Class<?> type) throws ReflectiveOperationException { if (type.isPrimitive() || isAssignableFrom(type, mapObject.getClass())) { return mapObject; } else if (Objects.equals(type, String.class) && CLASS_CAN_BE_STRING.contains(mapObject.getClass())) { // auto convert specified type to string return mapObject.toString(); } else if (mapObject instanceof Map) { return mapToPojo((Map<String, Object>) mapObject, type); } else { // type didn't match and mapObject is not another Map struct. // we just ignore this situation. return null; } } @SuppressWarnings("unchecked") private static Object convertParameterizedType(Object mapObject, ParameterizedType type) throws ReflectiveOperationException { Type rawType = type.getRawType(); if (!isAssignableFrom((Class<?>) rawType, mapObject.getClass())) { return null; } Type[] actualTypeArguments = type.getActualTypeArguments(); if (isAssignableFrom(Map.class, (Class<?>) rawType)) { Map<Object, Object> map = (Map<Object, Object>) mapObject.getClass().getDeclaredConstructor().newInstance(); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) mapObject).entrySet()) { Object key = getFieldObject(entry.getKey(), actualTypeArguments[0]); Object value = getFieldObject(entry.getValue(), actualTypeArguments[1]); map.put(key, value); } return map; } else if (isAssignableFrom(Collection.class, (Class<?>) rawType)) { Collection<Object> collection = (Collection<Object>) mapObject.getClass().getDeclaredConstructor().newInstance(); for (Object m : (Iterable<?>) mapObject) { Object ele = getFieldObject(m, actualTypeArguments[0]); collection.add(ele); } return collection; } else { // ignore other type currently return null; } } }
6,856
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.java
/* * 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 java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; public class LFUCache<K, V> { private final Map<K, CacheNode<K, V>> map; private final CacheDeque<K, V>[] freqTable; private final int capacity; private final int evictionCount; private int curSize = 0; private final ReentrantLock lock = new ReentrantLock(); private static final int DEFAULT_INITIAL_CAPACITY = 1000; private static final float DEFAULT_EVICTION_FACTOR = 0.75f; public LFUCache() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_EVICTION_FACTOR); } /** * Constructs and initializes cache with specified capacity and eviction * factor. Unacceptable parameter values followed with * {@link IllegalArgumentException}. * * @param maxCapacity cache max capacity * @param evictionFactor cache proceedEviction factor */ @SuppressWarnings("unchecked") public LFUCache(final int maxCapacity, final float evictionFactor) { if (maxCapacity <= 0) { throw new IllegalArgumentException("Illegal initial capacity: " + maxCapacity); } boolean factorInRange = evictionFactor <= 1 && evictionFactor > 0; if (!factorInRange || Float.isNaN(evictionFactor)) { throw new IllegalArgumentException("Illegal eviction factor value:" + evictionFactor); } this.capacity = maxCapacity; this.evictionCount = (int) (capacity * evictionFactor); this.map = new HashMap<>(); this.freqTable = new CacheDeque[capacity + 1]; for (int i = 0; i <= capacity; i++) { freqTable[i] = new CacheDeque<>(); } for (int i = 0; i < capacity; i++) { freqTable[i].nextDeque = freqTable[i + 1]; } freqTable[capacity].nextDeque = freqTable[capacity]; } public int getCapacity() { return capacity; } public V put(final K key, final V value) { CacheNode<K, V> node; lock.lock(); try { node = map.get(key); if (node != null) { CacheNode.withdrawNode(node); node.value = value; freqTable[0].addLastNode(node); map.put(key, node); } else { curSize++; if (curSize > capacity) { proceedEviction(); } node = freqTable[0].addLast(key, value); map.put(key, node); } } finally { lock.unlock(); } return node.value; } public V remove(final K key) { CacheNode<K, V> node = null; lock.lock(); try { if (map.containsKey(key)) { node = map.remove(key); if (node != null) { CacheNode.withdrawNode(node); } curSize--; } } finally { lock.unlock(); } return (node != null) ? node.value : null; } public V get(final K key) { CacheNode<K, V> node = null; lock.lock(); try { if (map.containsKey(key)) { node = map.get(key); CacheNode.withdrawNode(node); node.owner.nextDeque.addLastNode(node); } } finally { lock.unlock(); } return (node != null) ? node.value : null; } /** * Evicts less frequently used elements corresponding to eviction factor, * specified at instantiation step. * * @return number of evicted elements */ private int proceedEviction() { int targetSize = capacity - evictionCount; int evictedElements = 0; FREQ_TABLE_ITER_LOOP: for (int i = 0; i <= capacity; i++) { CacheNode<K, V> node; while (!freqTable[i].isEmpty()) { node = freqTable[i].pollFirst(); remove(node.key); if (targetSize >= curSize) { break FREQ_TABLE_ITER_LOOP; } evictedElements++; } } return evictedElements; } /** * Returns cache current size. * * @return cache size */ public int getSize() { return curSize; } static class CacheNode<K, V> { CacheNode<K, V> prev; CacheNode<K, V> next; K key; V value; CacheDeque<K, V> owner; CacheNode() {} CacheNode(final K key, final V value) { this.key = key; this.value = value; } /** * This method takes specified node and reattaches it neighbors nodes * links to each other, so specified node will no longer tied with them. * Returns united node, returns null if argument is null. * * @param node note to retrieve * @param <K> key * @param <V> value * @return retrieved node */ static <K, V> CacheNode<K, V> withdrawNode(final CacheNode<K, V> node) { if (node != null && node.prev != null) { node.prev.next = node.next; if (node.next != null) { node.next.prev = node.prev; } } return node; } } /** * Custom deque implementation of LIFO type. Allows to place element at top * of deque and poll very last added elements. An arbitrary node from the * deque can be removed with {@link CacheNode#withdrawNode(CacheNode)} * method. * * @param <K> key * @param <V> value */ static class CacheDeque<K, V> { CacheNode<K, V> last; CacheNode<K, V> first; CacheDeque<K, V> nextDeque; /** * Constructs list and initializes last and first pointers. */ CacheDeque() { last = new CacheNode<>(); first = new CacheNode<>(); last.next = first; first.prev = last; } /** * Puts the node with specified key and value at the end of the deque * and returns node. * * @param key key * @param value value * @return added node */ CacheNode<K, V> addLast(final K key, final V value) { CacheNode<K, V> node = new CacheNode<>(key, value); node.owner = this; node.next = last.next; node.prev = last; node.next.prev = node; last.next = node; return node; } CacheNode<K, V> addLastNode(final CacheNode<K, V> node) { node.owner = this; node.next = last.next; node.prev = last; node.next.prev = node; last.next = node; return node; } /** * Retrieves and removes the first node of this deque. * * @return removed node */ CacheNode<K, V> pollFirst() { CacheNode<K, V> node = null; if (first.prev != last) { node = first.prev; first.prev = node.prev; first.prev.next = first; node.prev = null; node.next = null; } return node; } /** * Checks if link to the last node points to link to the first node. * * @return is deque empty */ boolean isEmpty() { return last.next == first; } } }
6,857
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java
/* * 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.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; /** * JRE version */ public enum JRE { JAVA_8, JAVA_9, JAVA_10, JAVA_11, JAVA_12, JAVA_13, JAVA_14, JAVA_15, JAVA_16, JAVA_17, JAVA_18, JAVA_19, JAVA_20, JAVA_21, JAVA_22, JAVA_23, OTHER; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JRE.class); private static final JRE VERSION = getJre(); /** * get current JRE version * * @return JRE version */ public static JRE currentVersion() { return VERSION; } /** * is current version * * @return true if current version */ public boolean isCurrentVersion() { return this == VERSION; } private static JRE getJre() { // get java version from system property String version = System.getProperty("java.version"); boolean isBlank = StringUtils.isBlank(version); if (isBlank) { logger.debug("java.version is blank"); } // if start with 1.8 return java 8 if (!isBlank && version.startsWith("1.8")) { return JAVA_8; } // if JRE version is 9 or above, we can get version from java.lang.Runtime.version() try { Object javaRunTimeVersion = MethodUtils.invokeMethod(Runtime.getRuntime(), "version"); int majorVersion = MethodUtils.invokeMethod(javaRunTimeVersion, "major"); switch (majorVersion) { case 9: return JAVA_9; case 10: return JAVA_10; case 11: return JAVA_11; case 12: return JAVA_12; case 13: return JAVA_13; case 14: return JAVA_14; case 15: return JAVA_15; case 16: return JAVA_16; case 17: return JAVA_17; case 18: return JAVA_18; case 19: return JAVA_19; case 20: return JAVA_20; case 21: return JAVA_21; case 22: return JAVA_22; default: return OTHER; } } catch (Exception e) { logger.debug( "Can't determine current JRE version (maybe java.version is null), assuming that JRE version is 8.", e); } // default java 8 return JAVA_8; } }
6,858
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java
/* * 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 java.util.function.Supplier; public class CacheableSupplier<T> implements Supplier<T> { private volatile T object; private final Supplier<T> supplier; public CacheableSupplier(Supplier<T> supplier) { this.supplier = supplier; } public static <T> CacheableSupplier<T> newSupplier(Supplier<T> supplier) { return new CacheableSupplier<>(supplier); } @Override public T get() { if (this.object == null) { this.object = supplier.get(); } return object; } }
6,859
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java
/* * 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.config.Configuration; import org.apache.dubbo.common.config.InmemoryConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class ConfigUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigUtils.class); private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\s*\\{?\\s*([\\._0-9a-zA-Z]+)\\s*\\}?"); private static int PID = -1; private ConfigUtils() {} public static boolean isNotEmpty(String value) { return !isEmpty(value); } public static boolean isEmpty(String value) { return StringUtils.isEmpty(value) || "false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value) || "null".equalsIgnoreCase(value) || "N/A".equalsIgnoreCase(value); } public static boolean isDefault(String value) { return "true".equalsIgnoreCase(value) || "default".equalsIgnoreCase(value); } /** * Insert default extension into extension list. * <p> * Extension list support<ul> * <li>Special value <code><strong>default</strong></code>, means the location for default extensions. * <li>Special symbol<code><strong>-</strong></code>, means remove. <code>-foo1</code> will remove default extension 'foo'; <code>-default</code> will remove all default extensions. * </ul> * * @param type Extension type * @param cfg Extension name list * @param def Default extension list * @return result extension list */ public static List<String> mergeValues( ExtensionDirector extensionDirector, Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (extensionDirector.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); // add initial values String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } // -default is not included if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { // add default extension int i = names.indexOf(DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(DEFAULT_KEY); } else { names.remove(DEFAULT_KEY); } // merge - configuration for (String name : new ArrayList<String>(names)) { if (name.startsWith(REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } public static String replaceProperty(String expression, Map<String, String> params) { return replaceProperty(expression, new InmemoryConfiguration(params)); } public static String replaceProperty(String expression, Configuration configuration) { if (StringUtils.isEmpty(expression) || expression.indexOf('$') < 0) { return expression; } Matcher matcher = VARIABLE_PATTERN.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String key = matcher.group(1); String value = System.getProperty(key); if (value == null && configuration != null) { Object val = configuration.getProperty(key); value = (val != null) ? val.toString() : null; } if (value == null) { // maybe not placeholders, use origin express value = matcher.group(); } matcher.appendReplacement(sb, Matcher.quoteReplacement(value)); } matcher.appendTail(sb); return sb.toString(); } /** * Get dubbo properties. * It is not recommended using this method to modify dubbo properties. * * @return */ public static Properties getProperties(Set<ClassLoader> classLoaders) { String path = System.getProperty(CommonConstants.DUBBO_PROPERTIES_KEY); if (StringUtils.isEmpty(path)) { path = System.getenv(CommonConstants.DUBBO_PROPERTIES_KEY); if (StringUtils.isEmpty(path)) { path = CommonConstants.DEFAULT_DUBBO_PROPERTIES; } } return ConfigUtils.loadProperties(classLoaders, path, false, true); } /** * System environment -> System properties * * @param key key * @return value */ public static String getSystemProperty(String key) { String value = System.getenv(key); if (StringUtils.isEmpty(value)) { value = System.getProperty(key); } return value; } public static Properties loadProperties(Set<ClassLoader> classLoaders, String fileName) { return loadProperties(classLoaders, fileName, false, false); } public static Properties loadProperties(Set<ClassLoader> classLoaders, String fileName, boolean allowMultiFile) { return loadProperties(classLoaders, fileName, allowMultiFile, false); } /** * Load properties file to {@link Properties} from class path. * * @param fileName properties file name. for example: <code>dubbo.properties</code>, <code>METE-INF/conf/foo.properties</code> * @param allowMultiFile if <code>false</code>, throw {@link IllegalStateException} when found multi file on the class path. * @param optional is optional. if <code>false</code>, log warn when properties config file not found!s * @return loaded {@link Properties} content. <ul> * <li>return empty Properties if no file found. * <li>merge multi properties file if found multi file * </ul> * @throws IllegalStateException not allow multi-file, but multi-file exist on class path. */ public static Properties loadProperties( Set<ClassLoader> classLoaders, String fileName, boolean allowMultiFile, boolean optional) { Properties properties = new Properties(); // add scene judgement in windows environment Fix 2557 if (checkFileNameExist(fileName)) { try { FileInputStream input = new FileInputStream(fileName); try { properties.load(input); } finally { input.close(); } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return properties; } Set<java.net.URL> set = null; try { List<ClassLoader> classLoadersToLoad = new LinkedList<>(); classLoadersToLoad.add(ClassUtils.getClassLoader()); classLoadersToLoad.addAll(classLoaders); set = ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad).values().stream() .reduce(new LinkedHashSet<>(), (a, i) -> { a.addAll(i); return a; }); } catch (Throwable t) { logger.warn(COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file: " + t.getMessage(), t); } if (CollectionUtils.isEmpty(set)) { if (!optional) { logger.warn(COMMON_IO_EXCEPTION, "", "", "No " + fileName + " found on the class path."); } return properties; } if (!allowMultiFile) { if (set.size() > 1) { String errMsg = String.format( "only 1 %s file is expected, but %d dubbo.properties files found on class path: %s", fileName, set.size(), set); logger.warn(COMMON_IO_EXCEPTION, "", "", errMsg); } // fall back to use method getResourceAsStream try { properties.load(ClassUtils.getClassLoader().getResourceAsStream(fileName)); } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return properties; } logger.info("load " + fileName + " properties file from " + set); for (java.net.URL url : set) { try { Properties p = new Properties(); InputStream input = url.openStream(); if (input != null) { try { p.load(input); properties.putAll(p); } finally { try { input.close(); } catch (Throwable t) { } } } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), e); } } return properties; } public static String loadMigrationRule(Set<ClassLoader> classLoaders, String fileName) { String rawRule = ""; if (checkFileNameExist(fileName)) { try { try (FileInputStream input = new FileInputStream(fileName)) { return readString(input); } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } } try { List<ClassLoader> classLoadersToLoad = new LinkedList<>(); classLoadersToLoad.add(ClassUtils.getClassLoader()); classLoadersToLoad.addAll(classLoaders); for (Set<URL> urls : ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad) .values()) { for (URL url : urls) { InputStream is = url.openStream(); if (is != null) { return readString(is); } } } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return rawRule; } private static String readString(InputStream is) { StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { int n; while ((n = reader.read(buffer)) != -1) { if (n < 10) { buffer = Arrays.copyOf(buffer, n); } stringBuilder.append(String.valueOf(buffer)); buffer = new char[10]; } } catch (IOException e) { logger.error(COMMON_IO_EXCEPTION, "", "", "Read migration file error.", e); } return stringBuilder.toString(); } /** * check if the fileName can be found in filesystem * * @param fileName * @return */ private static boolean checkFileNameExist(String fileName) { File file = new File(fileName); return file.exists(); } public static int getPid() { if (PID < 0) { try { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); // format: "pid@hostname" String name = runtime.getName(); PID = Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Throwable e) { PID = 0; } } return PID; } }
6,860
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java
/* * 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 java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static java.util.stream.StreamSupport.stream; import static org.apache.dubbo.common.function.Predicates.and; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterList; import static org.apache.dubbo.common.utils.ClassUtils.getAllInterfaces; import static org.apache.dubbo.common.utils.ClassUtils.getAllSuperClasses; import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom; /** * The utilities class for {@link Type} * * @since 2.7.6 */ public interface TypeUtils { Predicate<Class<?>> NON_OBJECT_TYPE_FILTER = t -> !Objects.equals(Object.class, t); static boolean isParameterizedType(Type type) { return type instanceof ParameterizedType; } static Type getRawType(Type type) { if (isParameterizedType(type)) { return ((ParameterizedType) type).getRawType(); } else { return type; } } static Class<?> getRawClass(Type type) { Type rawType = getRawType(type); if (isClass(rawType)) { return (Class) rawType; } return null; } static boolean isClass(Type type) { return type instanceof Class; } static <T> Class<T> findActualTypeArgument(Type type, Class<?> interfaceClass, int index) { return (Class<T>) findActualTypeArguments(type, interfaceClass).get(index); } static List<Class<?>> findActualTypeArguments(Type type, Class<?> interfaceClass) { List<Class<?>> actualTypeArguments = new ArrayList<>(); getAllGenericTypes(type, t -> isAssignableFrom(interfaceClass, getRawClass(t))) .forEach(parameterizedType -> { Class<?> rawClass = getRawClass(parameterizedType); Type[] typeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeArguments.length; i++) { Type typeArgument = typeArguments[i]; if (typeArgument instanceof Class) { actualTypeArguments.add(i, (Class) typeArgument); } } Class<?> superClass = rawClass.getSuperclass(); if (superClass != null) { actualTypeArguments.addAll(findActualTypeArguments(superClass, interfaceClass)); } }); return unmodifiableList(actualTypeArguments); } /** * Get the specified types' generic types(including super classes and interfaces) that are assignable from {@link ParameterizedType} interface * * @param type the specified type * @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance * @return non-null read-only {@link List} */ static List<ParameterizedType> getGenericTypes(Type type, Predicate<ParameterizedType>... typeFilters) { Class<?> rawClass = getRawClass(type); if (rawClass == null) { return emptyList(); } List<Type> genericTypes = new LinkedList<>(); genericTypes.add(rawClass.getGenericSuperclass()); genericTypes.addAll(asList(rawClass.getGenericInterfaces())); return unmodifiableList(filterList(genericTypes, TypeUtils::isParameterizedType).stream() .map(ParameterizedType.class::cast) .filter(and(typeFilters)) .collect(toList())); } /** * Get all generic types(including super classes and interfaces) that are assignable from {@link ParameterizedType} interface * * @param type the specified type * @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance * @return non-null read-only {@link List} */ static List<ParameterizedType> getAllGenericTypes(Type type, Predicate<ParameterizedType>... typeFilters) { List<ParameterizedType> allGenericTypes = new LinkedList<>(); // Add generic super classes allGenericTypes.addAll(getAllGenericSuperClasses(type, typeFilters)); // Add generic super interfaces allGenericTypes.addAll(getAllGenericInterfaces(type, typeFilters)); // wrap unmodifiable object return unmodifiableList(allGenericTypes); } /** * Get all generic super classes that are assignable from {@link ParameterizedType} interface * * @param type the specified type * @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance * @return non-null read-only {@link List} */ static List<ParameterizedType> getAllGenericSuperClasses(Type type, Predicate<ParameterizedType>... typeFilters) { Class<?> rawClass = getRawClass(type); if (rawClass == null || rawClass.isInterface()) { return emptyList(); } List<Class<?>> allTypes = new LinkedList<>(); // Add current class allTypes.add(rawClass); // Add all super classes allTypes.addAll(getAllSuperClasses(rawClass, NON_OBJECT_TYPE_FILTER)); List<ParameterizedType> allGenericSuperClasses = allTypes.stream() .map(Class::getGenericSuperclass) .filter(TypeUtils::isParameterizedType) .map(ParameterizedType.class::cast) .collect(Collectors.toList()); return unmodifiableList(filterAll(allGenericSuperClasses, typeFilters)); } /** * Get all generic interfaces that are assignable from {@link ParameterizedType} interface * * @param type the specified type * @param typeFilters one or more {@link Predicate}s to filter the {@link ParameterizedType} instance * @return non-null read-only {@link List} */ static List<ParameterizedType> getAllGenericInterfaces(Type type, Predicate<ParameterizedType>... typeFilters) { Class<?> rawClass = getRawClass(type); if (rawClass == null) { return emptyList(); } List<Class<?>> allTypes = new LinkedList<>(); // Add current class allTypes.add(rawClass); // Add all super classes allTypes.addAll(getAllSuperClasses(rawClass, NON_OBJECT_TYPE_FILTER)); // Add all super interfaces allTypes.addAll(getAllInterfaces(rawClass)); List<ParameterizedType> allGenericInterfaces = allTypes.stream() .map(Class::getGenericInterfaces) .map(Arrays::asList) .flatMap(Collection::stream) .filter(TypeUtils::isParameterizedType) .map(ParameterizedType.class::cast) .collect(toList()); return unmodifiableList(filterAll(allGenericInterfaces, typeFilters)); } static String getClassName(Type type) { return getRawType(type).getTypeName(); } static Set<String> getClassNames(Iterable<? extends Type> types) { return stream(types.spliterator(), false).map(TypeUtils::getClassName).collect(toSet()); } }
6,861
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java
/* * 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; /** * Helper Class for hold a value. */ public class Holder<T> { private volatile T value; public void set(T value) { this.value = value; } public T get() { return value; } }
6,862
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java
/* * 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.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.Locale; import java.util.Objects; import java.util.Set; public class SerializeSecurityManager { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityManager.class); private final Set<String> allowedPrefix = new ConcurrentHashSet<>(); private final Set<String> alwaysAllowedPrefix = new ConcurrentHashSet<>(); private final Set<String> disAllowedPrefix = new ConcurrentHashSet<>(); private final Set<AllowClassNotifyListener> listeners = new ConcurrentHashSet<>(); private final Set<String> warnedClasses = new ConcurrentHashSet<>(1); private volatile SerializeCheckStatus checkStatus = null; private volatile SerializeCheckStatus defaultCheckStatus = AllowClassNotifyListener.DEFAULT_STATUS; private volatile Boolean checkSerializable = null; public void addToAlwaysAllowed(String className) { boolean modified = alwaysAllowedPrefix.add(className); if (modified) { notifyPrefix(); } } public void addToAllowed(String className) { if (disAllowedPrefix.stream().anyMatch(className::startsWith)) { return; } boolean modified = allowedPrefix.add(className); if (modified) { notifyPrefix(); } } public void addToDisAllowed(String className) { boolean modified = disAllowedPrefix.add(className); modified = allowedPrefix.removeIf(allow -> allow.startsWith(className)) || modified; if (modified) { notifyPrefix(); } String lowerCase = className.toLowerCase(Locale.ROOT); if (!Objects.equals(lowerCase, className)) { addToDisAllowed(lowerCase); } } public void setCheckStatus(SerializeCheckStatus checkStatus) { if (this.checkStatus == null) { this.checkStatus = checkStatus; logger.info("Serialize check level: " + checkStatus.name()); notifyCheckStatus(); return; } // If has been set to WARN, ignore STRICT if (this.checkStatus.level() <= checkStatus.level()) { return; } this.checkStatus = checkStatus; logger.info("Serialize check level: " + checkStatus.name()); notifyCheckStatus(); } public void setDefaultCheckStatus(SerializeCheckStatus checkStatus) { this.defaultCheckStatus = checkStatus; logger.info("Serialize check default level: " + checkStatus.name()); notifyCheckStatus(); } public void setCheckSerializable(boolean checkSerializable) { if (this.checkSerializable == null || (Boolean.TRUE.equals(this.checkSerializable) && !checkSerializable)) { this.checkSerializable = checkSerializable; logger.info("Serialize check serializable: " + checkSerializable); notifyCheckSerializable(); } } public void registerListener(AllowClassNotifyListener listener) { listeners.add(listener); listener.notifyPrefix(getAllowedPrefix(), getDisAllowedPrefix()); listener.notifyCheckSerializable(isCheckSerializable()); listener.notifyCheckStatus(getCheckStatus()); } private void notifyPrefix() { for (AllowClassNotifyListener listener : listeners) { listener.notifyPrefix(getAllowedPrefix(), getDisAllowedPrefix()); } } private void notifyCheckStatus() { for (AllowClassNotifyListener listener : listeners) { listener.notifyCheckStatus(getCheckStatus()); } } private void notifyCheckSerializable() { for (AllowClassNotifyListener listener : listeners) { listener.notifyCheckSerializable(isCheckSerializable()); } } protected SerializeCheckStatus getCheckStatus() { return checkStatus == null ? defaultCheckStatus : checkStatus; } protected Set<String> getAllowedPrefix() { Set<String> set = new ConcurrentHashSet<>(); set.addAll(allowedPrefix); set.addAll(alwaysAllowedPrefix); return set; } protected Set<String> getDisAllowedPrefix() { Set<String> set = new ConcurrentHashSet<>(); set.addAll(disAllowedPrefix); return set; } protected boolean isCheckSerializable() { return checkSerializable == null || checkSerializable; } public Set<String> getWarnedClasses() { return warnedClasses; } }
6,863
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java
/* * 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.compact.Dubbo2CompactUtils; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Service; import java.lang.annotation.Annotation; import java.util.List; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute; import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty; import static org.apache.dubbo.common.utils.ClassUtils.isGenericClass; import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; /** * The resolver class for {@link Service @Service} * * @see Service * @see com.alibaba.dubbo.config.annotation.Service * @since 2.7.6 */ public class ServiceAnnotationResolver { /** * The annotation {@link Class classes} of Dubbo Service (read-only) * * @since 2.7.9 */ public static List<Class<? extends Annotation>> SERVICE_ANNOTATION_CLASSES = loadServiceAnnotationClasses(); private static List<Class<? extends Annotation>> loadServiceAnnotationClasses() { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { return unmodifiableList(asList(DubboService.class, Service.class, Dubbo2CompactUtils.getServiceClass())); } else { return unmodifiableList(asList(DubboService.class, Service.class)); } } private final Annotation serviceAnnotation; private final Class<?> serviceType; public ServiceAnnotationResolver(Class<?> serviceType) throws IllegalArgumentException { this.serviceType = serviceType; this.serviceAnnotation = getServiceAnnotation(serviceType); } private Annotation getServiceAnnotation(Class<?> serviceType) { Annotation serviceAnnotation = null; for (Class<? extends Annotation> serviceAnnotationClass : SERVICE_ANNOTATION_CLASSES) { serviceAnnotation = serviceType.getAnnotation(serviceAnnotationClass); if (serviceAnnotation != null) { break; } } if (serviceAnnotation == null) { throw new IllegalArgumentException(format( "Any annotation of [%s] can't be annotated in the service type[%s].", SERVICE_ANNOTATION_CLASSES, serviceType.getName())); } return serviceAnnotation; } /** * Resolve the class name of interface * * @return if not found, return <code>null</code> */ public String resolveInterfaceClassName() { Class interfaceClass; // first, try to get the value from "interfaceName" attribute String interfaceName = resolveAttribute("interfaceName"); if (isEmpty(interfaceName)) { // If not found, try "interfaceClass" interfaceClass = resolveAttribute("interfaceClass"); } else { interfaceClass = resolveClass(interfaceName, getClass().getClassLoader()); } if (isGenericClass(interfaceClass)) { interfaceName = interfaceClass.getName(); } else { interfaceName = null; } if (isEmpty(interfaceName)) { // If not fund, try to get the first interface from the service type Class[] interfaces = serviceType.getInterfaces(); if (isNotEmpty(interfaces)) { interfaceName = interfaces[0].getName(); } } return interfaceName; } public String resolveVersion() { return resolveAttribute("version"); } public String resolveGroup() { return resolveAttribute("group"); } private <T> T resolveAttribute(String attributeName) { return getAttribute(serviceAnnotation, attributeName); } public Annotation getServiceAnnotation() { return serviceAnnotation; } public Class<?> getServiceType() { return serviceType; } }
6,864
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java
/* * 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.convert.ConverterUtil; import org.apache.dubbo.rpc.model.FrameworkModel; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.flip; import static org.apache.dubbo.common.utils.CollectionUtils.ofSet; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; public class ClassUtils { /** * Suffix for array class names: "[]" */ public static final String ARRAY_SUFFIX = "[]"; /** * Simple Types including: * <ul> * <li>{@link Void}</li> * <li>{@link Boolean}</li> * <li>{@link Character}</li> * <li>{@link Byte}</li> * <li>{@link Integer}</li> * <li>{@link Float}</li> * <li>{@link Double}</li> * <li>{@link String}</li> * <li>{@link BigDecimal}</li> * <li>{@link BigInteger}</li> * <li>{@link Date}</li> * <li>{@link Object}</li> * </ul> * * @see javax.management.openmbean.SimpleType * @since 2.7.6 */ public static final Set<Class<?>> SIMPLE_TYPES = ofSet( Void.class, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, BigDecimal.class, BigInteger.class, Date.class, Object.class, Duration.class); /** * Prefix for internal array class names: "[L" */ private static final String INTERNAL_ARRAY_PREFIX = "[L"; /** * Map with primitive type name as key and corresponding primitive type as * value, for example: "int" -> "int.class". */ private static final Map<String, Class<?>> PRIMITIVE_TYPE_NAME_MAP = new HashMap<>(32); /** * Map with primitive wrapper type as key and corresponding primitive type * as value, for example: Integer.class -> int.class. */ private static final Map<Class<?>, Class<?>> PRIMITIVE_WRAPPER_TYPE_MAP = new HashMap<>(16); static { PRIMITIVE_WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Byte.class, byte.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Character.class, char.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Double.class, double.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Float.class, float.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Integer.class, int.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Long.class, long.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Short.class, short.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Void.class, void.class); Set<Class<?>> primitiveTypeNames = new HashSet<>(32); primitiveTypeNames.addAll(PRIMITIVE_WRAPPER_TYPE_MAP.values()); primitiveTypeNames.addAll(Arrays.asList( boolean[].class, byte[].class, char[].class, double[].class, float[].class, int[].class, long[].class, short[].class)); for (Class<?> primitiveTypeName : primitiveTypeNames) { PRIMITIVE_TYPE_NAME_MAP.put(primitiveTypeName.getName(), primitiveTypeName); } } /** * Map with primitive type as key and corresponding primitive wrapper type * as value, for example: int.class -> Integer.class. */ private static final Map<Class<?>, Class<?>> WRAPPER_PRIMITIVE_TYPE_MAP = flip(PRIMITIVE_WRAPPER_TYPE_MAP); /** * Separator char for package */ private static final char PACKAGE_SEPARATOR_CHAR = '.'; public static Class<?> forNameWithThreadContextClassLoader(String name) throws ClassNotFoundException { return forName(name, Thread.currentThread().getContextClassLoader()); } public static Class<?> forNameWithCallerClassLoader(String name, Class<?> caller) throws ClassNotFoundException { return forName(name, caller.getClassLoader()); } public static ClassLoader getCallerClassLoader(Class<?> caller) { return caller.getClassLoader(); } /** * get class loader * * @param clazz * @return class loader */ public static ClassLoader getClassLoader(Class<?> clazz) { ClassLoader cl = null; if (!clazz.getName().startsWith("org.apache.dubbo")) { cl = clazz.getClassLoader(); } if (cl == null) { try { cl = Thread.currentThread().getContextClassLoader(); } catch (Exception ignored) { // Cannot access thread context ClassLoader - falling back to system class loader... } if (cl == null) { // No thread context class loader -> use class loader of this class. cl = clazz.getClassLoader(); if (cl == null) { // getClassLoader() returning null indicates the bootstrap ClassLoader try { cl = ClassLoader.getSystemClassLoader(); } catch (Exception ignored) { // Cannot access system ClassLoader - oh well, maybe the caller can live with null... } } } } return cl; } /** * Return the default ClassLoader to use: typically the thread context * ClassLoader, if available; the ClassLoader that loaded the ClassUtils * class will be used as fallback. * <p> * Call this method if you intend to use the thread context ClassLoader in a * scenario where you absolutely need a non-null ClassLoader reference: for * example, for class path resource loading (but not necessarily for * <code>Class.forName</code>, which accepts a <code>null</code> ClassLoader * reference as well). * * @return the default ClassLoader (never <code>null</code>) * @see java.lang.Thread#getContextClassLoader() */ public static ClassLoader getClassLoader() { return getClassLoader(ClassUtils.class); } /** * Same as <code>Class.forName()</code>, except that it works for primitive * types. */ public static Class<?> forName(String name) throws ClassNotFoundException { return forName(name, getClassLoader()); } /** * Replacement for <code>Class.forName()</code> that also returns Class * instances for primitives (like "int") and array class names (like * "String[]"). * * @param name the name of the Class * @param classLoader the class loader to use (may be <code>null</code>, * which indicates the default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException if the class was not found * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Class<?> clazz = resolvePrimitiveClassName(name); if (clazz != null) { return clazz; } // "java.lang.String[]" style arrays if (name.endsWith(ARRAY_SUFFIX)) { String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } // "[Ljava.lang.String;" style arrays int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); if (internalArrayMarker != -1 && name.endsWith(";")) { String elementClassName = null; if (internalArrayMarker == 0) { elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); } else if (name.startsWith("[")) { elementClassName = name.substring(1); } Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getClassLoader(); } return classLoaderToUse.loadClass(name); } /** * Resolve the given class name as primitive class, if appropriate, * according to the JVM's naming rules for primitive classes. * <p> * Also supports the JVM's internal class names for primitive arrays. Does * <i>not</i> support the "[]" suffix notation for primitive arrays; this is * only supported by {@link #forName}. * * @param name the name of the potentially primitive class * @return the primitive class, or <code>null</code> if the name does not * denote a primitive class or primitive array class */ public static Class<?> resolvePrimitiveClassName(String name) { Class<?> result = null; // Most class names will be quite long, considering that they // SHOULD sit in a package, so a length check is worthwhile. if (name != null && name.length() <= 8) { // Could be a primitive - likely. result = (Class<?>) PRIMITIVE_TYPE_NAME_MAP.get(name); } return result; } public static String toShortString(Object obj) { if (obj == null) { return "null"; } return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); } public static String simpleClassName(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } String className = clazz.getName(); final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (lastDotIdx > -1) { return className.substring(lastDotIdx + 1); } return className; } /** * The specified type is primitive type or simple type * * @param type the type to test * @return * @deprecated as 2.7.6, use {@link Class#isPrimitive()} plus {@link #isSimpleType(Class)} instead */ public static boolean isPrimitive(Class<?> type) { return type != null && (type.isPrimitive() || isSimpleType(type)); } /** * The specified type is simple type or not * * @param type the type to test * @return if <code>type</code> is one element of {@link #SIMPLE_TYPES}, return <code>true</code>, or <code>false</code> * @see #SIMPLE_TYPES * @since 2.7.6 */ public static boolean isSimpleType(Class<?> type) { return SIMPLE_TYPES.contains(type); } public static Object convertPrimitive(Class<?> type, String value) { return convertPrimitive(FrameworkModel.defaultModel(), type, value); } public static Object convertPrimitive(FrameworkModel frameworkModel, Class<?> type, String value) { if (isEmpty(value)) { return null; } Class<?> wrapperType = WRAPPER_PRIMITIVE_TYPE_MAP.getOrDefault(type, type); Object result = null; try { result = frameworkModel.getBeanFactory().getBean(ConverterUtil.class).convertIfPossible(value, wrapperType); } catch (Exception e) { // ignore exception } return result; } /** * We only check boolean value at this moment. * * @param type * @param value * @return */ public static boolean isTypeMatch(Class<?> type, String value) { if ((type == boolean.class || type == Boolean.class) && !("true".equals(value) || "false".equals(value))) { return false; } return true; } /** * Get all super classes from the specified type * * @param type the specified type * @param classFilters the filters for classes * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllSuperClasses(Class<?> type, Predicate<Class<?>>... classFilters) { Set<Class<?>> allSuperClasses = new LinkedHashSet<>(); Class<?> superClass = type.getSuperclass(); while (superClass != null) { // add current super class allSuperClasses.add(superClass); superClass = superClass.getSuperclass(); } return unmodifiableSet(filterAll(allSuperClasses, classFilters)); } /** * Get all interfaces from the specified type * * @param type the specified type * @param interfaceFilters the filters for interfaces * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllInterfaces(Class<?> type, Predicate<Class<?>>... interfaceFilters) { if (type == null || type.isPrimitive()) { return emptySet(); } Set<Class<?>> allInterfaces = new LinkedHashSet<>(); Set<Class<?>> resolved = new LinkedHashSet<>(); Queue<Class<?>> waitResolve = new LinkedList<>(); resolved.add(type); Class<?> clazz = type; while (clazz != null) { Class<?>[] interfaces = clazz.getInterfaces(); if (isNotEmpty(interfaces)) { // add current interfaces Arrays.stream(interfaces).filter(resolved::add).forEach(cls -> { allInterfaces.add(cls); waitResolve.add(cls); }); } // add all super classes to waitResolve getAllSuperClasses(clazz).stream().filter(resolved::add).forEach(waitResolve::add); clazz = waitResolve.poll(); } return filterAll(allInterfaces, interfaceFilters); } /** * Get all inherited types from the specified type * * @param type the specified type * @param typeFilters the filters for types * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllInheritedTypes(Class<?> type, Predicate<Class<?>>... typeFilters) { // Add all super classes Set<Class<?>> types = new LinkedHashSet<>(getAllSuperClasses(type, typeFilters)); // Add all interface classes types.addAll(getAllInterfaces(type, typeFilters)); return unmodifiableSet(types); } /** * the semantics is same as {@link Class#isAssignableFrom(Class)} * * @param superType the super type * @param targetType the target type * @return see {@link Class#isAssignableFrom(Class)} * @since 2.7.6 */ public static boolean isAssignableFrom(Class<?> superType, Class<?> targetType) { // any argument is null if (superType == null || targetType == null) { return false; } // equals if (Objects.equals(superType, targetType)) { return true; } // isAssignableFrom return superType.isAssignableFrom(targetType); } /** * Test the specified class name is present in the {@link ClassLoader} * * @param className the name of {@link Class} * @param classLoader {@link ClassLoader} * @return If found, return <code>true</code> * @since 2.7.6 */ public static boolean isPresent(String className, ClassLoader classLoader) { try { forName(className, classLoader); } catch (Exception ignored) { // Ignored return false; } return true; } /** * Resolve the {@link Class} by the specified name and {@link ClassLoader} * * @param className the name of {@link Class} * @param classLoader {@link ClassLoader} * @return If can't be resolved , return <code>null</code> * @since 2.7.6 */ public static Class<?> resolveClass(String className, ClassLoader classLoader) { Class<?> targetClass = null; try { targetClass = forName(className, classLoader); } catch (Exception ignored) { // Ignored } return targetClass; } /** * Is generic class or not? * * @param type the target type * @return if the target type is not null or <code>void</code> or Void.class, return <code>true</code>, or false * @since 2.7.6 */ public static boolean isGenericClass(Class<?> type) { return type != null && !void.class.equals(type) && !Void.class.equals(type); } public static boolean hasMethods(Method[] methods) { if (methods == null || methods.length == 0) { return false; } for (Method m : methods) { if (m.getDeclaringClass() != Object.class) { return true; } } return false; } private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; /** * get method name array. * * @return method name array. */ public static String[] getMethodNames(Class<?> tClass) { if (tClass == Object.class) { return OBJECT_METHODS; } Method[] methods = Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[] {}); List<String> mns = new ArrayList<>(); // method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } String mn = m.getName(); mns.add(mn); } } return mns.toArray(new String[0]); } public static boolean isMatch(Class<?> from, Class<?> to) { if (from == to) { return true; } boolean isMatch; if (from.isPrimitive()) { isMatch = matchPrimitive(from, to); } else if (to.isPrimitive()) { isMatch = matchPrimitive(to, from); } else { isMatch = to.isAssignableFrom(from); } return isMatch; } private static boolean matchPrimitive(Class<?> from, Class<?> to) { if (from == boolean.class) { return to == Boolean.class; } else if (from == byte.class) { return to == Byte.class; } else if (from == char.class) { return to == Character.class; } else if (from == short.class) { return to == Short.class; } else if (from == int.class) { return to == Integer.class; } else if (from == long.class) { return to == Long.class; } else if (from == float.class) { return to == Float.class; } else if (from == double.class) { return to == Double.class; } else if (from == void.class) { return to == Void.class; } return false; } /** * get method name array. * * @return method name array. */ public static String[] getDeclaredMethodNames(Class<?> tClass) { if (tClass == Object.class) { return OBJECT_METHODS; } Method[] methods = Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[] {}); List<String> dmns = new ArrayList<>(); // method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } String mn = m.getName(); if (m.getDeclaringClass() == tClass) { dmns.add(mn); } } } dmns.sort(Comparator.naturalOrder()); return dmns.toArray(new String[0]); } }
6,865
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java
/* * 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; /** * Contains some methods to check array. */ public final class ArrayUtils { private ArrayUtils() {} /** * <p>Checks if the array is null or empty. <p/> * * @param array th array to check * @return {@code true} if the array is null or empty. */ public static boolean isEmpty(final Object[] array) { return array == null || array.length == 0; } /** * <p>Checks if the array is not null or empty. <p/> * * @param array th array to check * @return {@code true} if the array is not null or empty. */ public static boolean isNotEmpty(final Object[] array) { return !isEmpty(array); } public static boolean contains(final String[] array, String valueToFind) { return indexOf(array, valueToFind, 0) != -1; } public static int indexOf(String[] array, String valueToFind, int startIndex) { if (isEmpty(array) || valueToFind == null) { return -1; } else { if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; ++i) { if (valueToFind.equals(array[i])) { return i; } } return -1; } } /** * Convert from variable arguments to array * * @param values variable arguments * @param <T> The class * @return array * @since 2.7.9 */ public static <T> T[] of(T... values) { return values; } }
6,866
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java
/* * 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 java.lang.reflect.Field; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; /** * Miscellaneous collection utility methods. * Mainly for internal use within the framework. * * @since 2.0.7 */ public class CollectionUtils { private static final Comparator<String> SIMPLE_NAME_COMPARATOR = (s1, s2) -> { if (s1 == null && s2 == null) { return 0; } if (s1 == null) { return -1; } if (s2 == null) { return 1; } int i1 = s1.lastIndexOf('.'); if (i1 >= 0) { s1 = s1.substring(i1 + 1); } int i2 = s2.lastIndexOf('.'); if (i2 >= 0) { s2 = s2.substring(i2 + 1); } return s1.compareToIgnoreCase(s2); }; private CollectionUtils() {} @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> List<T> sort(List<T> list) { if (isNotEmpty(list)) { Collections.sort((List) list); } return list; } public static List<String> sortSimpleName(List<String> list) { if (list != null && list.size() > 0) { Collections.sort(list, SIMPLE_NAME_COMPARATOR); } return list; } /** * Flip the specified {@link Map} * * @param map The specified {@link Map},Its value must be unique * @param <K> The key type of specified {@link Map} * @param <V> The value type of specified {@link Map} * @return {@link Map} */ @SuppressWarnings("unchecked") public static <K, V> Map<V, K> flip(Map<K, V> map) { if (isEmptyMap(map)) { return (Map<V, K>) map; } Set<V> set = new HashSet<>(map.values()); if (set.size() != map.size()) { throw new IllegalArgumentException("The map value must be unique."); } return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); } public static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator) { if (list == null) { return null; } Map<String, Map<String, String>> result = new HashMap<>(); for (Map.Entry<String, List<String>> entry : list.entrySet()) { result.put(entry.getKey(), split(entry.getValue(), separator)); } return result; } public static Map<String, List<String>> joinAll(Map<String, Map<String, String>> map, String separator) { if (map == null) { return null; } Map<String, List<String>> result = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) { result.put(entry.getKey(), join(entry.getValue(), separator)); } return result; } public static Map<String, String> split(List<String> list, String separator) { if (list == null) { return null; } Map<String, String> map = new HashMap<>(); if (list.isEmpty()) { return map; } for (String item : list) { int index = item.indexOf(separator); if (index == -1) { map.put(item, ""); } else { map.put(item.substring(0, index), item.substring(index + 1)); } } return map; } public static List<String> join(Map<String, String> map, String separator) { if (map == null) { return null; } List<String> list = new ArrayList<>(); if (map.size() == 0) { return list; } for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isEmpty(value)) { list.add(key); } else { list.add(key + separator + value); } } return list; } public static String join(List<String> list, String separator) { StringBuilder sb = new StringBuilder(); for (String ele : list) { if (sb.length() > 0) { sb.append(separator); } sb.append(ele); } return sb.toString(); } public static boolean mapEquals(Map<?, ?> map1, Map<?, ?> map2) { if (map1 == null && map2 == null) { return true; } if (map1 == null || map2 == null) { return false; } if (map1.size() != map2.size()) { return false; } for (Map.Entry<?, ?> entry : map1.entrySet()) { Object key = entry.getKey(); Object value1 = entry.getValue(); Object value2 = map2.get(key); if (!objectEquals(value1, value2)) { return false; } } return true; } private static boolean objectEquals(Object obj1, Object obj2) { if (obj1 == null && obj2 == null) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.equals(obj2); } public static Map<String, String> toStringMap(String... pairs) { Map<String, String> parameters = new HashMap<>(); if (ArrayUtils.isEmpty(pairs)) { return parameters; } if (pairs.length > 0) { if (pairs.length % 2 != 0) { throw new IllegalArgumentException("pairs must be even."); } for (int i = 0; i < pairs.length; i = i + 2) { parameters.put(pairs[i], pairs[i + 1]); } } return parameters; } @SuppressWarnings("unchecked") public static <K, V> Map<K, V> toMap(Object... pairs) { Map<K, V> ret = new HashMap<>(); if (pairs == null || pairs.length == 0) { return ret; } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not be odd number."); } int len = pairs.length / 2; for (int i = 0; i < len; i++) { ret.put((K) pairs[2 * i], (V) pairs[2 * i + 1]); } return ret; } @SuppressWarnings("unchecked") public static <K, V> Map<K, V> objToMap(Object object) throws IllegalAccessException { Map<K, V> ret = new HashMap<>(); if (object != null) { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object value = field.get(object); if (value != null) { ret.put((K) field.getName(), (V) value); } } } return ret; } /** * Return {@code true} if the supplied Collection is {@code null} or empty. * Otherwise, return {@code false}. * * @param collection the Collection to check * @return whether the given Collection is empty */ public static boolean isEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } /** * Return {@code true} if the supplied Collection is {@code not null} or not empty. * Otherwise, return {@code false}. * * @param collection the Collection to check * @return whether the given Collection is not empty */ public static boolean isNotEmpty(Collection<?> collection) { return !isEmpty(collection); } /** * Return {@code true} if the supplied Map is {@code null} or empty. * Otherwise, return {@code false}. * * @param map the Map to check * @return whether the given Map is empty */ public static boolean isEmptyMap(Map map) { return map == null || map.size() == 0; } /** * Return {@code true} if the supplied Map is {@code not null} or not empty. * Otherwise, return {@code false}. * * @param map the Map to check * @return whether the given Map is not empty */ public static boolean isNotEmptyMap(Map map) { return !isEmptyMap(map); } /** * Convert to multiple values to be {@link LinkedHashSet} * * @param values one or more values * @param <T> the type of <code>values</code> * @return read-only {@link Set} */ public static <T> Set<T> ofSet(T... values) { int size = values == null ? 0 : values.length; if (size < 1) { return emptySet(); } float loadFactor = 1f / ((size + 1) * 1.0f); if (loadFactor > 0.75f) { loadFactor = 0.75f; } Set<T> elements = new LinkedHashSet<>(size, loadFactor); for (int i = 0; i < size; i++) { elements.add(values[i]); } return unmodifiableSet(elements); } /** * Get the size of the specified {@link Collection} * * @param collection the specified {@link Collection} * @return must be positive number * @since 2.7.6 */ public static int size(Collection<?> collection) { return collection == null ? 0 : collection.size(); } /** * Compares the specified collection with another, the main implementation references * {@link AbstractSet} * * @param one {@link Collection} * @param another {@link Collection} * @return if equals, return <code>true</code>, or <code>false</code> * @since 2.7.6 */ public static boolean equals(Collection<?> one, Collection<?> another) { if (one == another) { return true; } if (isEmpty(one) && isEmpty(another)) { return true; } if (size(one) != size(another)) { return false; } try { return one.containsAll(another); } catch (ClassCastException | NullPointerException unused) { return false; } } /** * Add the multiple values into {@link Collection the specified collection} * * @param collection {@link Collection the specified collection} * @param values the multiple values * @param <T> the type of values * @return the effected count after added * @since 2.7.6 */ public static <T> int addAll(Collection<T> collection, T... values) { int size = values == null ? 0 : values.length; if (collection == null || size < 1) { return 0; } int effectedCount = 0; for (int i = 0; i < size; i++) { if (collection.add(values[i])) { effectedCount++; } } return effectedCount; } /** * Take the first element from the specified collection * * @param values the collection object * @param <T> the type of element of collection * @return if found, return the first one, or <code>null</code> * @since 2.7.6 */ public static <T> T first(Collection<T> values) { if (isEmpty(values)) { return null; } if (values instanceof List) { List<T> list = (List<T>) values; return list.get(0); } else { return values.iterator().next(); } } public static <T> Set<T> toTreeSet(Set<T> set) { if (isEmpty(set)) { return set; } if (!(set instanceof TreeSet)) { set = new TreeSet<>(set); } return set; } }
6,867
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java
/* * 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.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * MD5 util. */ public class MD5Utils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MD5Utils.class); private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private MessageDigest mdInst; public MD5Utils() { try { mdInst = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to obtain md5", e); } } /** * Calculation md5 value of specify string * * @param input */ public String getMd5(String input) { byte[] md5; // MessageDigest instance is NOT thread-safe synchronized (mdInst) { mdInst.update(input.getBytes(UTF_8)); md5 = mdInst.digest(); } int j = md5.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md5[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } }
6,868
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java
/* * 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 java.util.concurrent.atomic.AtomicIntegerFieldUpdater; public class AtomicPositiveInteger extends Number { private static final long serialVersionUID = -3038533876489105940L; private static final AtomicIntegerFieldUpdater<AtomicPositiveInteger> INDEX_UPDATER = AtomicIntegerFieldUpdater.newUpdater(AtomicPositiveInteger.class, "index"); @SuppressWarnings("unused") private volatile int index = 0; public AtomicPositiveInteger() {} public AtomicPositiveInteger(int initialValue) { INDEX_UPDATER.set(this, initialValue); } public final int getAndIncrement() { return INDEX_UPDATER.getAndIncrement(this) & Integer.MAX_VALUE; } public final int getAndDecrement() { return INDEX_UPDATER.getAndDecrement(this) & Integer.MAX_VALUE; } public final int incrementAndGet() { return INDEX_UPDATER.incrementAndGet(this) & Integer.MAX_VALUE; } public final int decrementAndGet() { return INDEX_UPDATER.decrementAndGet(this) & Integer.MAX_VALUE; } public final int get() { return INDEX_UPDATER.get(this) & Integer.MAX_VALUE; } public final void set(int newValue) { if (newValue < 0) { throw new IllegalArgumentException("new value " + newValue + " < 0"); } INDEX_UPDATER.set(this, newValue); } public final int getAndSet(int newValue) { if (newValue < 0) { throw new IllegalArgumentException("new value " + newValue + " < 0"); } return INDEX_UPDATER.getAndSet(this, newValue) & Integer.MAX_VALUE; } public final int getAndAdd(int delta) { if (delta < 0) { throw new IllegalArgumentException("delta " + delta + " < 0"); } return INDEX_UPDATER.getAndAdd(this, delta) & Integer.MAX_VALUE; } public final int addAndGet(int delta) { if (delta < 0) { throw new IllegalArgumentException("delta " + delta + " < 0"); } return INDEX_UPDATER.addAndGet(this, delta) & Integer.MAX_VALUE; } public final boolean compareAndSet(int expect, int update) { if (update < 0) { throw new IllegalArgumentException("update value " + update + " < 0"); } return INDEX_UPDATER.compareAndSet(this, expect, update); } public final boolean weakCompareAndSet(int expect, int update) { if (update < 0) { throw new IllegalArgumentException("update value " + update + " < 0"); } return INDEX_UPDATER.weakCompareAndSet(this, expect, update); } @Override public byte byteValue() { return (byte) get(); } @Override public short shortValue() { return (short) get(); } @Override public int intValue() { return get(); } @Override public long longValue() { return (long) get(); } @Override public float floatValue() { return (float) get(); } @Override public double doubleValue() { return (double) get(); } @Override public String toString() { return Integer.toString(get()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + get(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof AtomicPositiveInteger)) { return false; } AtomicPositiveInteger other = (AtomicPositiveInteger) obj; return intValue() == other.intValue(); } }
6,869
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java
/* * 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.URL; import org.apache.dubbo.common.URLStrParser; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.url.component.ServiceConfigURL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Collections.emptyMap; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CLASSIFIER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; public class UrlUtils { /** * Forbids the instantiation. */ private UrlUtils() { throw new UnsupportedOperationException("No instance of 'UrlUtils' for you! "); } /** * in the url string,mark the param begin */ private static final String URL_PARAM_STARTING_SYMBOL = "?"; public static URL parseURL(String address, Map<String, String> defaults) { if (StringUtils.isEmpty(address)) { throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter."); } String url; if (address.contains("://") || address.contains(URL_PARAM_STARTING_SYMBOL)) { url = address; } else { String[] addresses = COMMA_SPLIT_PATTERN.split(address); url = addresses[0]; if (addresses.length > 1) { StringBuilder backup = new StringBuilder(); for (int i = 1; i < addresses.length; i++) { if (i > 1) { backup.append(','); } backup.append(addresses[i]); } url += URL_PARAM_STARTING_SYMBOL + RemotingConstants.BACKUP_KEY + "=" + backup.toString(); } } String defaultProtocol = defaults == null ? null : defaults.get(PROTOCOL_KEY); if (StringUtils.isEmpty(defaultProtocol)) { defaultProtocol = DUBBO_PROTOCOL; } String defaultUsername = defaults == null ? null : defaults.get(USERNAME_KEY); String defaultPassword = defaults == null ? null : defaults.get(PASSWORD_KEY); int defaultPort = StringUtils.parseInteger(defaults == null ? null : defaults.get(PORT_KEY)); String defaultPath = defaults == null ? null : defaults.get(PATH_KEY); Map<String, String> defaultParameters = defaults == null ? null : new HashMap<>(defaults); if (defaultParameters != null) { defaultParameters.remove(PROTOCOL_KEY); defaultParameters.remove(USERNAME_KEY); defaultParameters.remove(PASSWORD_KEY); defaultParameters.remove(HOST_KEY); defaultParameters.remove(PORT_KEY); defaultParameters.remove(PATH_KEY); } URL u = URL.cacheableValueOf(url); boolean changed = false; String protocol = u.getProtocol(); String username = u.getUsername(); String password = u.getPassword(); String host = u.getHost(); int port = u.getPort(); String path = u.getPath(); Map<String, String> parameters = new HashMap<>(u.getParameters()); if (StringUtils.isEmpty(protocol)) { changed = true; protocol = defaultProtocol; } if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(defaultUsername)) { changed = true; username = defaultUsername; } if (StringUtils.isEmpty(password) && StringUtils.isNotEmpty(defaultPassword)) { changed = true; password = defaultPassword; } /*if (u.isAnyHost() || u.isLocalHost()) { changed = true; host = NetUtils.getLocalHost(); }*/ if (port <= 0) { if (defaultPort > 0) { changed = true; port = defaultPort; } else { changed = true; port = 9090; } } if (StringUtils.isEmpty(path)) { if (StringUtils.isNotEmpty(defaultPath)) { changed = true; path = defaultPath; } } if (defaultParameters != null && defaultParameters.size() > 0) { for (Map.Entry<String, String> entry : defaultParameters.entrySet()) { String key = entry.getKey(); String defaultValue = entry.getValue(); if (StringUtils.isNotEmpty(defaultValue)) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { changed = true; parameters.put(key, defaultValue); } } } } if (changed) { u = new ServiceConfigURL(protocol, username, password, host, port, path, parameters); } return u; } public static List<URL> parseURLs(String address, Map<String, String> defaults) { if (StringUtils.isEmpty(address)) { throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter."); } String[] addresses = REGISTRY_SPLIT_PATTERN.split(address); if (addresses == null || addresses.length == 0) { throw new IllegalArgumentException( "Addresses is not allowed to be empty, please re-enter."); // here won't be empty } List<URL> registries = new ArrayList<URL>(); for (String addr : addresses) { registries.add(parseURL(addr, defaults)); } return registries; } public static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register) { Map<String, Map<String, String>> newRegister = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) { String serviceName = entry.getKey(); Map<String, String> serviceUrls = entry.getValue(); if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) { String serviceUrl = entry2.getKey(); String serviceQuery = entry2.getValue(); Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); // params.remove("group"); // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; } if (StringUtils.isNotEmpty(version)) { name = name + ":" + version; } Map<String, String> newUrls = newRegister.computeIfAbsent(name, k -> new HashMap<>()); newUrls.put(serviceUrl, StringUtils.toQueryString(params)); } } else { newRegister.put(serviceName, serviceUrls); } } return newRegister; } public static Map<String, String> convertSubscribe(Map<String, String> subscribe) { Map<String, String> newSubscribe = new HashMap<>(); for (Map.Entry<String, String> entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); // params.remove("group"); // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; } if (StringUtils.isNotEmpty(version)) { name = name + ":" + version; } newSubscribe.put(name, StringUtils.toQueryString(params)); } else { newSubscribe.put(serviceName, serviceQuery); } } return newSubscribe; } public static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register) { Map<String, Map<String, String>> newRegister = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) { String serviceName = entry.getKey(); Map<String, String> serviceUrls = entry.getValue(); if (StringUtils.isContains(serviceName, ':') && StringUtils.isContains(serviceName, '/')) { for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) { String serviceUrl = entry2.getKey(); String serviceQuery = entry2.getValue(); Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String name = serviceName; int i = name.indexOf('/'); if (i >= 0) { params.put(GROUP_KEY, name.substring(0, i)); name = name.substring(i + 1); } i = name.lastIndexOf(':'); if (i >= 0) { params.put(VERSION_KEY, name.substring(i + 1)); name = name.substring(0, i); } Map<String, String> newUrls = newRegister.computeIfAbsent(name, k -> new HashMap<String, String>()); newUrls.put(serviceUrl, StringUtils.toQueryString(params)); } } else { newRegister.put(serviceName, serviceUrls); } } return newRegister; } public static Map<String, String> revertSubscribe(Map<String, String> subscribe) { Map<String, String> newSubscribe = new HashMap<>(); for (Map.Entry<String, String> entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); if (StringUtils.isContains(serviceName, ':') && StringUtils.isContains(serviceName, '/')) { Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String name = serviceName; int i = name.indexOf('/'); if (i >= 0) { params.put(GROUP_KEY, name.substring(0, i)); name = name.substring(i + 1); } i = name.lastIndexOf(':'); if (i >= 0) { params.put(VERSION_KEY, name.substring(i + 1)); name = name.substring(0, i); } newSubscribe.put(name, StringUtils.toQueryString(params)); } else { newSubscribe.put(serviceName, serviceQuery); } } return newSubscribe; } public static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify) { if (notify != null && notify.size() > 0) { Map<String, Map<String, String>> newNotify = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : notify.entrySet()) { String serviceName = entry.getKey(); Map<String, String> serviceUrls = entry.getValue(); if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { if (CollectionUtils.isNotEmptyMap(serviceUrls)) { for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) { String url = entry2.getKey(); String query = entry2.getValue(); Map<String, String> params = StringUtils.parseQueryString(query); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); // params.remove("group"); // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; } if (StringUtils.isNotEmpty(version)) { name = name + ":" + version; } Map<String, String> newUrls = newNotify.computeIfAbsent(name, k -> new HashMap<>()); newUrls.put(url, StringUtils.toQueryString(params)); } } } else { newNotify.put(serviceName, serviceUrls); } } return newNotify; } return notify; } // compatible for dubbo-2.0.0 public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (CollectionUtils.isNotEmpty(forbid)) { List<String> newForbid = new ArrayList<>(); for (String serviceName : forbid) { if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } public static URL getEmptyUrl(String service, String category) { String group = null; String version = null; int i = service.indexOf('/'); if (i > 0) { group = service.substring(0, i); service = service.substring(i + 1); } i = service.lastIndexOf(':'); if (i > 0) { version = service.substring(i + 1); service = service.substring(0, i); } return URL.valueOf(EMPTY_PROTOCOL + "://0.0.0.0/" + service + URL_PARAM_STARTING_SYMBOL + CATEGORY_KEY + "=" + category + (group == null ? "" : "&" + GROUP_KEY + "=" + group) + (version == null ? "" : "&" + VERSION_KEY + "=" + version)); } public static boolean isMatchCategory(String category, String categories) { if (categories == null || categories.length() == 0) { return DEFAULT_CATEGORY.equals(category); } else if (categories.contains(ANY_VALUE)) { return true; } else if (categories.contains(REMOVE_VALUE_PREFIX)) { return !categories.contains(REMOVE_VALUE_PREFIX + category); } else { return categories.contains(category); } } public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); // FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenarios I // think it's ok to add this condition. // Return false if the consumer interface is not equals the provider interface, // except one of the interface configurations is equals '*' (i.e. any value). if (!(ANY_VALUE.equals(consumerInterface) || ANY_VALUE.equals(providerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) { return false; } // If the category of provider URL does not match the category of consumer URL. // Usually, the provider URL's category is empty, and the default category ('providers') is present. // Hence, the category of the provider URL is 'providers'. // Through observing of debugging process, I found that the category of the consumer URL is // 'providers,configurators,routers'. if (!isMatchCategory(providerUrl.getCategory(DEFAULT_CATEGORY), consumerUrl.getCategory(DEFAULT_CATEGORY))) { return false; } // If the provider is not enabled, return false. if (!providerUrl.getParameter(ENABLED_KEY, true) && !ANY_VALUE.equals(consumerUrl.getParameter(ENABLED_KEY))) { return false; } // Obtain consumer's group, version and classifier. String consumerGroup = consumerUrl.getGroup(); String consumerVersion = consumerUrl.getVersion(); String consumerClassifier = consumerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); // Obtain provider's group, version and classifier. String providerGroup = providerUrl.getGroup(); String providerVersion = providerUrl.getVersion(); String providerClassifier = providerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); // If Group, Version, Classifier all matches, return true. boolean groupMatches = ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup); boolean versionMatches = ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion); boolean classifierMatches = consumerClassifier == null || ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier); return groupMatches && versionMatches && classifierMatches; } public static boolean isMatchGlobPattern(String pattern, String value, URL param) { if (param != null && pattern.startsWith("$")) { pattern = param.getRawParameter(pattern.substring(1)); } return isMatchGlobPattern(pattern, value); } public static boolean isMatchGlobPattern(String pattern, String value) { if ("*".equals(pattern)) { return true; } if (StringUtils.isEmpty(pattern) && StringUtils.isEmpty(value)) { return true; } if (StringUtils.isEmpty(pattern) || StringUtils.isEmpty(value)) { return false; } int i = pattern.lastIndexOf('*'); // doesn't find "*" if (i == -1) { return value.equals(pattern); } // "*" is at the end else if (i == pattern.length() - 1) { return value.startsWith(pattern.substring(0, i)); } // "*" is at the beginning else if (i == 0) { return value.endsWith(pattern.substring(i + 1)); } // "*" is in the middle else { String prefix = pattern.substring(0, i); String suffix = pattern.substring(i + 1); return value.startsWith(prefix) && value.endsWith(suffix); } } public static boolean isServiceKeyMatch(URL pattern, URL value) { return pattern.getParameter(INTERFACE_KEY).equals(value.getParameter(INTERFACE_KEY)) && isItemMatch(pattern.getGroup(), value.getGroup()) && isItemMatch(pattern.getVersion(), value.getVersion()); } public static List<URL> classifyUrls(List<URL> urls, Predicate<URL> predicate) { return urls.stream().filter(predicate).collect(Collectors.toList()); } public static boolean isConfigurator(URL url) { return OVERRIDE_PROTOCOL.equals(url.getProtocol()) || CONFIGURATORS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); } public static boolean isRoute(URL url) { return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); } public static boolean isProvider(URL url) { return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()) && PROVIDERS_CATEGORY.equals(url.getCategory(PROVIDERS_CATEGORY)); } public static boolean isRegistry(URL url) { return REGISTRY_PROTOCOL.equals(url.getProtocol()) || SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol()) || (url.getProtocol() != null && url.getProtocol().endsWith("-registry-protocol")); } /** * The specified {@link URL} is service discovery registry type or not * * @param url the {@link URL} connects to the registry * @return If it is, return <code>true</code>, or <code>false</code> * @since 2.7.5 */ public static boolean hasServiceDiscoveryRegistryTypeKey(URL url) { return hasServiceDiscoveryRegistryTypeKey(url == null ? emptyMap() : url.getParameters()); } public static boolean hasServiceDiscoveryRegistryProtocol(URL url) { return SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol()); } public static boolean isServiceDiscoveryURL(URL url) { return hasServiceDiscoveryRegistryProtocol(url) || hasServiceDiscoveryRegistryTypeKey(url); } /** * The specified parameters of {@link URL} is service discovery registry type or not * * @param parameters the parameters of {@link URL} that connects to the registry * @return If it is, return <code>true</code>, or <code>false</code> * @since 2.7.5 */ public static boolean hasServiceDiscoveryRegistryTypeKey(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return false; } return SERVICE_REGISTRY_TYPE.equals(parameters.get(REGISTRY_TYPE_KEY)); } /** * Check if the given value matches the given pattern. The pattern supports wildcard "*". * * @param pattern pattern * @param value value * @return true if match otherwise false */ static boolean isItemMatch(String pattern, String value) { if (StringUtils.isEmpty(pattern)) { return value == null; } else { return "*".equals(pattern) || pattern.equals(value); } } /** * @param serviceKey, {group}/{interfaceName}:{version} * @return [group, interfaceName, version] */ public static String[] parseServiceKey(String serviceKey) { String[] arr = new String[3]; int i = serviceKey.indexOf('/'); if (i > 0) { arr[0] = serviceKey.substring(0, i); serviceKey = serviceKey.substring(i + 1); } int j = serviceKey.indexOf(':'); if (j > 0) { arr[2] = serviceKey.substring(j + 1); serviceKey = serviceKey.substring(0, j); } arr[1] = serviceKey; return arr; } /** * NOTICE: This method allocate too much objects, we can use {@link URLStrParser#parseDecodedStr(String)} instead. * <p> * Parse url string * * @param url URL string * @return URL instance * @see URL */ public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf('?'); // separator between body and parameters if (i >= 0) { String[] parts = url.substring(i + 1).split("&"); parameters = new HashMap<>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { String key = part.substring(0, j); String value = part.substring(j + 1); parameters.put(key, value); // compatible with lower versions registering "default." keys if (key.startsWith(DEFAULT_KEY_PREFIX)) { parameters.putIfAbsent(key.substring(DEFAULT_KEY_PREFIX.length()), value); } } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf("://"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + url + "\""); } protocol = url.substring(0, i); url = url.substring(i + 3); } else { // case: file:/path/to/file.txt i = url.indexOf(":/"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + url + "\""); } protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf('/'); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.lastIndexOf('@'); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(':'); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.lastIndexOf(':'); if (i >= 0 && i < url.length() - 1) { if (url.lastIndexOf('%') > i) { // ipv6 address with scope id // e.g. fe80:0:0:0:894:aeec:f37d:23e1%en0 // see https://howdoesinternetwork.com/2013/ipv6-zone-id // ignore } else { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } } if (url.length() > 0) { host = url; } return new ServiceConfigURL(protocol, username, password, host, port, path, parameters); } public static boolean isConsumer(URL url) { return url.getProtocol().equalsIgnoreCase(CONSUMER) || url.getPort() == 0; } }
6,870
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.java
/* * 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 java.util.function.Supplier; public abstract class Assert { protected Assert() {} public static void notNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } } public static void notEmptyString(String str, String message) { if (StringUtils.isEmpty(str)) { throw new IllegalArgumentException(message); } } public static void notNull(Object obj, RuntimeException exception) { if (obj == null) { throw exception; } } public static void assertTrue(boolean condition, String message) { if (!condition) { throw new IllegalArgumentException(message); } } public static void assertTrue(boolean expression, Supplier<String> messageSupplier) { if (!expression) { throw new IllegalStateException(nullSafeGet(messageSupplier)); } } private static String nullSafeGet(Supplier<String> messageSupplier) { return (messageSupplier != null ? messageSupplier.get() : null); } }
6,871
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java
/* * 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.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.dubbo.rpc.model.ScopeModel; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.BitSet; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import static java.util.Collections.emptyList; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_NETWORK_IGNORED_INTERFACE; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PREFERRED_NETWORK_INTERFACE; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.utils.CollectionUtils.first; /** * IP and Port Helper for RPC */ public final class NetUtils { /** * Forbids instantiation. */ private NetUtils() { throw new UnsupportedOperationException("No instance of 'NetUtils' for you! "); } private static Logger logger; static { /* DO NOT replace this logger to error type aware logger (or fail-safe logger), since its logging method calls NetUtils.getLocalHost(). According to issue #4992, getLocalHost() method will be endless recursively invoked when network disconnected. */ logger = LoggerFactory.getLogger(NetUtils.class); if (logger instanceof FailsafeLogger) { logger = ((FailsafeLogger) logger).getLogger(); } } // returned port range is [30000, 39999] private static final int RND_PORT_START = 30000; private static final int RND_PORT_RANGE = 10000; // valid port range is (0, 65535] private static final int MIN_PORT = 1; private static final int MAX_PORT = 65535; private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$"); private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); private static final Map<String, String> HOST_NAME_CACHE = new LRUCache<>(1000); private static volatile InetAddress LOCAL_ADDRESS = null; private static volatile Inet6Address LOCAL_ADDRESS_V6 = null; private static final String SPLIT_IPV4_CHARACTER = "\\."; private static final String SPLIT_IPV6_CHARACTER = ":"; /** * store the used port. * the set used only on the synchronized method. */ private static BitSet USED_PORT = new BitSet(65536); public static int getRandomPort() { return RND_PORT_START + ThreadLocalRandom.current().nextInt(RND_PORT_RANGE); } public static synchronized int getAvailablePort() { int randomPort = getRandomPort(); return getAvailablePort(randomPort); } public static synchronized int getAvailablePort(int port) { if (port < MIN_PORT) { return MIN_PORT; } for (int i = port; i < MAX_PORT; i++) { if (USED_PORT.get(i)) { continue; } try (ServerSocket ignored = new ServerSocket(i)) { USED_PORT.set(i); port = i; break; } catch (IOException e) { // continue } } return port; } /** * Check the port whether is in use in os * @param port port to check * @return true if it's occupied */ public static boolean isPortInUsed(int port) { try (ServerSocket ignored = new ServerSocket(port)) { return false; } catch (IOException e) { // continue } return true; } /** * Tells whether the port to test is an invalid port. * * @implNote Numeric comparison only. * @param port port to test * @return true if invalid */ public static boolean isInvalidPort(int port) { return port < MIN_PORT || port > MAX_PORT; } /** * Tells whether the address to test is an invalid address. * * @implNote Pattern matching only. * @param address address to test * @return true if invalid */ public static boolean isValidAddress(String address) { return ADDRESS_PATTERN.matcher(address).matches(); } public static boolean isLocalHost(String host) { return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase(LOCALHOST_KEY)); } public static boolean isAnyHost(String host) { return ANYHOST_VALUE.equals(host); } public static boolean isInvalidLocalHost(String host) { return host == null || host.length() == 0 || host.equalsIgnoreCase(LOCALHOST_KEY) || host.equals(ANYHOST_VALUE) || host.startsWith("127."); } public static boolean isValidLocalHost(String host) { return !isInvalidLocalHost(host); } public static InetSocketAddress getLocalSocketAddress(String host, int port) { return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port); } static boolean isValidV4Address(InetAddress address) { if (address == null || address.isLoopbackAddress()) { return false; } String name = address.getHostAddress(); return (name != null && IP_PATTERN.matcher(name).matches() && !ANYHOST_VALUE.equals(name) && !LOCALHOST_VALUE.equals(name)); } /** * Check if an ipv6 address * * @return true if it is reachable */ static boolean isPreferIPV6Address() { return Boolean.getBoolean("java.net.preferIPv6Addresses"); } /** * normalize the ipv6 Address, convert scope name to scope id. * e.g. * convert * fe80:0:0:0:894:aeec:f37d:23e1%en0 * to * fe80:0:0:0:894:aeec:f37d:23e1%5 * <p> * The %5 after ipv6 address is called scope id. * see java doc of {@link Inet6Address} for more details. * * @param address the input address * @return the normalized address, with scope id converted to int */ static InetAddress normalizeV6Address(Inet6Address address) { String addr = address.getHostAddress(); int i = addr.lastIndexOf('%'); if (i > 0) { try { return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId()); } catch (UnknownHostException e) { // ignore logger.debug("Unknown IPV6 address: ", e); } } return address; } private static volatile String HOST_ADDRESS; private static volatile String HOST_NAME; private static volatile String HOST_ADDRESS_V6; public static String getLocalHost() { if (HOST_ADDRESS != null) { return HOST_ADDRESS; } InetAddress address = getLocalAddress(); if (address != null) { if (address instanceof Inet6Address) { String ipv6AddressString = address.getHostAddress(); if (ipv6AddressString.contains("%")) { ipv6AddressString = ipv6AddressString.substring(0, ipv6AddressString.indexOf("%")); } HOST_ADDRESS = ipv6AddressString; return HOST_ADDRESS; } HOST_ADDRESS = address.getHostAddress(); return HOST_ADDRESS; } return LOCALHOST_VALUE; } public static String getLocalHostV6() { if (StringUtils.isNotEmpty(HOST_ADDRESS_V6)) { return HOST_ADDRESS_V6; } // avoid to search network interface card many times if ("".equals(HOST_ADDRESS_V6)) { return null; } Inet6Address address = getLocalAddressV6(); if (address != null) { String ipv6AddressString = address.getHostAddress(); if (ipv6AddressString.contains("%")) { ipv6AddressString = ipv6AddressString.substring(0, ipv6AddressString.indexOf("%")); } HOST_ADDRESS_V6 = ipv6AddressString; return HOST_ADDRESS_V6; } HOST_ADDRESS_V6 = ""; return null; } public static String filterLocalHost(String host) { if (host == null || host.length() == 0) { return host; } if (host.contains("://")) { URL u = URL.valueOf(host); if (NetUtils.isInvalidLocalHost(u.getHost())) { return u.setHost(NetUtils.getLocalHost()).toFullString(); } } else if (host.contains(":")) { int i = host.lastIndexOf(':'); if (NetUtils.isInvalidLocalHost(host.substring(0, i))) { return NetUtils.getLocalHost() + host.substring(i); } } else { if (NetUtils.isInvalidLocalHost(host)) { return NetUtils.getLocalHost(); } } return host; } public static String getIpByConfig(ScopeModel scopeModel) { String configIp = ConfigurationUtils.getProperty(scopeModel, DUBBO_IP_TO_BIND); if (configIp != null) { return configIp; } return getLocalHost(); } /** * Find first valid IP from local network card * * @return first valid local IP */ public static InetAddress getLocalAddress() { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getLocalAddress0(); LOCAL_ADDRESS = localAddress; return localAddress; } public static Inet6Address getLocalAddressV6() { if (LOCAL_ADDRESS_V6 != null) { return LOCAL_ADDRESS_V6; } Inet6Address localAddress = getLocalAddress0V6(); LOCAL_ADDRESS_V6 = localAddress; return localAddress; } private static Optional<InetAddress> toValidAddress(InetAddress address) { if (address instanceof Inet6Address) { Inet6Address v6Address = (Inet6Address) address; if (isPreferIPV6Address()) { return Optional.ofNullable(normalizeV6Address(v6Address)); } } if (isValidV4Address(address)) { return Optional.of(address); } return Optional.empty(); } private static InetAddress getLocalAddress0() { InetAddress localAddress = null; // @since 2.7.6, choose the {@link NetworkInterface} first try { NetworkInterface networkInterface = findNetworkInterface(); Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement()); if (addressOp.isPresent()) { try { if (addressOp.get().isReachable(100)) { return addressOp.get(); } } catch (IOException e) { // ignore } } } } catch (Throwable e) { logger.warn(e); } try { localAddress = InetAddress.getLocalHost(); Optional<InetAddress> addressOp = toValidAddress(localAddress); if (addressOp.isPresent()) { return addressOp.get(); } } catch (Throwable e) { logger.warn(e); } localAddress = getLocalAddressV6(); return localAddress; } private static Inet6Address getLocalAddress0V6() { // @since 2.7.6, choose the {@link NetworkInterface} first try { NetworkInterface networkInterface = findNetworkInterface(); Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet6Address) { if (!address.isLoopbackAddress() // filter ::1 && !address.isAnyLocalAddress() // filter ::/128 && !address.isLinkLocalAddress() // filter fe80::/10 && !address.isSiteLocalAddress() // filter fec0::/10 && !isUniqueLocalAddress(address) // filter fd00::/8 && address.getHostAddress().contains(":")) { // filter IPv6 return (Inet6Address) address; } } } } catch (Throwable e) { logger.warn(e); } return null; } /** * If the address is Unique Local Address. * * @param address {@link InetAddress} * @return {@code true} if the address is Unique Local Address,otherwise {@code false} */ private static boolean isUniqueLocalAddress(InetAddress address) { byte[] ip = address.getAddress(); return (ip[0] & 0xff) == 0xfd; } /** * Returns {@code true} if the specified {@link NetworkInterface} should be ignored with the given conditions. * * @param networkInterface the {@link NetworkInterface} to check * @return {@code true} if the specified {@link NetworkInterface} should be ignored, otherwise {@code false} * @throws SocketException SocketException if an I/O error occurs. */ private static boolean ignoreNetworkInterface(NetworkInterface networkInterface) throws SocketException { if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) { return true; } String ignoredInterfaces = System.getProperty(DUBBO_NETWORK_IGNORED_INTERFACE); String networkInterfaceDisplayName; if (StringUtils.isNotEmpty(ignoredInterfaces) && StringUtils.isNotEmpty(networkInterfaceDisplayName = networkInterface.getDisplayName())) { for (String ignoredInterface : ignoredInterfaces.split(",")) { String trimIgnoredInterface = ignoredInterface.trim(); boolean matched = false; try { matched = networkInterfaceDisplayName.matches(trimIgnoredInterface); } catch (PatternSyntaxException e) { // if trimIgnoredInterface is an invalid regular expression, a PatternSyntaxException will be thrown // out logger.warn( "exception occurred: " + networkInterfaceDisplayName + " matches " + trimIgnoredInterface, e); } finally { if (matched) { return true; } if (networkInterfaceDisplayName.equals(trimIgnoredInterface)) { return true; } } } } return false; } /** * Get the valid {@link NetworkInterface network interfaces} * * @return the valid {@link NetworkInterface}s * @throws SocketException SocketException if an I/O error occurs. * @since 2.7.6 */ private static List<NetworkInterface> getValidNetworkInterfaces() throws SocketException { List<NetworkInterface> validNetworkInterfaces = new LinkedList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (ignoreNetworkInterface(networkInterface)) { // ignore continue; } validNetworkInterfaces.add(networkInterface); } return validNetworkInterfaces; } /** * Is preferred {@link NetworkInterface} or not * * @param networkInterface {@link NetworkInterface} * @return if the name of the specified {@link NetworkInterface} matches * the property value from {@link CommonConstants#DUBBO_PREFERRED_NETWORK_INTERFACE}, return <code>true</code>, * or <code>false</code> */ public static boolean isPreferredNetworkInterface(NetworkInterface networkInterface) { String preferredNetworkInterface = System.getProperty(DUBBO_PREFERRED_NETWORK_INTERFACE); return Objects.equals(networkInterface.getDisplayName(), preferredNetworkInterface); } /** * Get the suitable {@link NetworkInterface} * * @return If no {@link NetworkInterface} is available , return <code>null</code> * @since 2.7.6 */ public static NetworkInterface findNetworkInterface() { List<NetworkInterface> validNetworkInterfaces = emptyList(); try { validNetworkInterfaces = getValidNetworkInterfaces(); } catch (Throwable e) { logger.warn(e); } NetworkInterface result = null; // Try to find the preferred one for (NetworkInterface networkInterface : validNetworkInterfaces) { if (isPreferredNetworkInterface(networkInterface)) { result = networkInterface; break; } } if (result == null) { // If not found, try to get the first one for (NetworkInterface networkInterface : validNetworkInterfaces) { Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement()); if (addressOp.isPresent()) { try { if (addressOp.get().isReachable(100)) { return networkInterface; } } catch (IOException e) { // ignore } } } } } if (result == null) { result = first(validNetworkInterfaces); } return result; } public static String getHostName(String address) { try { int i = address.indexOf(':'); if (i > -1) { address = address.substring(0, i); } String hostname = HOST_NAME_CACHE.get(address); if (hostname != null && hostname.length() > 0) { return hostname; } InetAddress inetAddress = InetAddress.getByName(address); if (inetAddress != null) { hostname = inetAddress.getHostName(); HOST_NAME_CACHE.put(address, hostname); return hostname; } } catch (Throwable e) { // ignore } return address; } public static String getLocalHostName() { if (HOST_NAME != null) { return HOST_NAME; } try { HOST_NAME = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { HOST_NAME = Optional.ofNullable(getLocalAddress()) .map(k -> k.getHostName()) .orElse(null); } return HOST_NAME; } /** * @param hostName * @return ip address or hostName if UnknownHostException */ public static String getIpByHost(String hostName) { try { return InetAddress.getByName(hostName).getHostAddress(); } catch (UnknownHostException e) { return hostName; } } public static String toAddressString(InetSocketAddress address) { return address.getAddress().getHostAddress() + ":" + address.getPort(); } public static InetSocketAddress toAddress(String address) { int i = address.indexOf(':'); String host; int port; if (i > -1) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; port = 0; } return new InetSocketAddress(host, port); } public static String toURL(String protocol, String host, int port, String path) { StringBuilder sb = new StringBuilder(); sb.append(protocol).append("://"); sb.append(host).append(':').append(port); if (path.charAt(0) != '/') { sb.append('/'); } sb.append(path); return sb.toString(); } @SuppressWarnings("deprecation") public static void joinMulticastGroup(MulticastSocket multicastSocket, InetAddress multicastAddress) throws IOException { setInterface(multicastSocket, multicastAddress instanceof Inet6Address); // For the deprecation notice: the equivalent only appears in JDK 9+. multicastSocket.setLoopbackMode(false); multicastSocket.joinGroup(multicastAddress); } @SuppressWarnings("deprecation") public static void setInterface(MulticastSocket multicastSocket, boolean preferIpv6) throws IOException { boolean interfaceSet = false; for (NetworkInterface networkInterface : getValidNetworkInterfaces()) { Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (preferIpv6 && address instanceof Inet6Address) { try { if (address.isReachable(100)) { multicastSocket.setInterface(address); interfaceSet = true; break; } } catch (IOException e) { // ignore } } else if (!preferIpv6 && address instanceof Inet4Address) { try { if (address.isReachable(100)) { multicastSocket.setInterface(address); interfaceSet = true; break; } } catch (IOException e) { // ignore } } } if (interfaceSet) { break; } } } /** * Check if address matches with specified pattern, currently only supports ipv4, use {@link this#matchIpExpression(String, String, int)} for ipv6 addresses. * * @param pattern cird pattern * @param address 'ip:port' * @return true if address matches with the pattern */ public static boolean matchIpExpression(String pattern, String address) throws UnknownHostException { if (address == null) { return false; } String host = address; int port = 0; // only works for ipv4 address with 'ip:port' format if (address.endsWith(":")) { String[] hostPort = address.split(":"); host = hostPort[0]; port = StringUtils.parseInteger(hostPort[1]); } // if the pattern is subnet format, it will not be allowed to config port param in pattern. if (pattern.contains("/")) { CIDRUtils utils = new CIDRUtils(pattern); return utils.isInRange(host); } return matchIpRange(pattern, host, port); } public static boolean matchIpExpression(String pattern, String host, int port) throws UnknownHostException { // if the pattern is subnet format, it will not be allowed to config port param in pattern. if (pattern.contains("/")) { CIDRUtils utils = new CIDRUtils(pattern); return utils.isInRange(host); } return matchIpRange(pattern, host, port); } /** * @param pattern * @param host * @param port * @return * @throws UnknownHostException */ public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException { if (pattern == null || host == null) { throw new IllegalArgumentException( "Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host); } pattern = pattern.trim(); if ("*.*.*.*".equals(pattern) || "*".equals(pattern)) { return true; } InetAddress inetAddress = InetAddress.getByName(host); boolean isIpv4 = isValidV4Address(inetAddress); String[] hostAndPort = getPatternHostAndPort(pattern, isIpv4); if (hostAndPort[1] != null && !hostAndPort[1].equals(String.valueOf(port))) { return false; } pattern = hostAndPort[0]; String splitCharacter = SPLIT_IPV4_CHARACTER; if (!isIpv4) { splitCharacter = SPLIT_IPV6_CHARACTER; } String[] mask = pattern.split(splitCharacter); // check format of pattern checkHostPattern(pattern, mask, isIpv4); host = inetAddress.getHostAddress(); if (pattern.equals(host)) { return true; } // short name condition if (!ipPatternContainExpression(pattern)) { InetAddress patternAddress = InetAddress.getByName(pattern); return patternAddress.getHostAddress().equals(host); } String[] ipAddress = host.split(splitCharacter); for (int i = 0; i < mask.length; i++) { if ("*".equals(mask[i]) || mask[i].equals(ipAddress[i])) { continue; } else if (mask[i].contains("-")) { String[] rangeNumStrs = StringUtils.split(mask[i], '-'); if (rangeNumStrs.length != 2) { throw new IllegalArgumentException("There is wrong format of ip Address: " + mask[i]); } Integer min = getNumOfIpSegment(rangeNumStrs[0], isIpv4); Integer max = getNumOfIpSegment(rangeNumStrs[1], isIpv4); Integer ip = getNumOfIpSegment(ipAddress[i], isIpv4); if (ip < min || ip > max) { return false; } } else if ("0".equals(ipAddress[i]) && ("0".equals(mask[i]) || "00".equals(mask[i]) || "000".equals(mask[i]) || "0000".equals(mask[i]))) { continue; } else if (!mask[i].equals(ipAddress[i])) { return false; } } return true; } /** * is multicast address or not * * @param host ipv4 address * @return {@code true} if is multicast address */ public static boolean isMulticastAddress(String host) { int i = host.indexOf('.'); if (i > 0) { String prefix = host.substring(0, i); if (StringUtils.isNumber(prefix)) { int p = Integer.parseInt(prefix); return p >= 224 && p <= 239; } } return false; } private static boolean ipPatternContainExpression(String pattern) { return pattern.contains("*") || pattern.contains("-"); } private static void checkHostPattern(String pattern, String[] mask, boolean isIpv4) { if (!isIpv4) { if (mask.length != 8 && ipPatternContainExpression(pattern)) { throw new IllegalArgumentException( "If you config ip expression that contains '*' or '-', please fill qualified ip pattern like 234e:0:4567:0:0:0:3d:*. "); } if (mask.length != 8 && !pattern.contains("::")) { throw new IllegalArgumentException( "The host is ipv6, but the pattern is not ipv6 pattern : " + pattern); } } else { if (mask.length != 4) { throw new IllegalArgumentException( "The host is ipv4, but the pattern is not ipv4 pattern : " + pattern); } } } private static String[] getPatternHostAndPort(String pattern, boolean isIpv4) { String[] result = new String[2]; if (pattern.startsWith("[") && pattern.contains("]:")) { int end = pattern.indexOf("]:"); result[0] = pattern.substring(1, end); result[1] = pattern.substring(end + 2); return result; } else if (pattern.startsWith("[") && pattern.endsWith("]")) { result[0] = pattern.substring(1, pattern.length() - 1); result[1] = null; return result; } else if (isIpv4 && pattern.contains(":")) { int end = pattern.indexOf(":"); result[0] = pattern.substring(0, end); result[1] = pattern.substring(end + 1); return result; } else { result[0] = pattern; return result; } } private static Integer getNumOfIpSegment(String ipSegment, boolean isIpv4) { if (isIpv4) { return Integer.parseInt(ipSegment); } return Integer.parseInt(ipSegment, 16); } public static boolean isIPV6URLStdFormat(String ip) { if ((ip.charAt(0) == '[' && ip.indexOf(']') > 2)) { return true; } else if (ip.indexOf(":") != ip.lastIndexOf(":")) { return true; } else { return false; } } public static String getLegalIP(String ip) { // ipv6 [::FFFF:129.144.52.38]:80 int ind; if ((ip.charAt(0) == '[' && (ind = ip.indexOf(']')) > 2)) { String nhost = ip; ip = nhost.substring(0, ind + 1); ip = ip.substring(1, ind); return ip; } else { return ip; } } }
6,872
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java
/* * 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 javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.utils.ClassUtils.getAllInheritedTypes; import static org.apache.dubbo.common.utils.MemberUtils.isPrivate; import static org.apache.dubbo.common.utils.MemberUtils.isStatic; import static org.apache.dubbo.common.utils.ReflectUtils.EMPTY_CLASS_ARRAY; import static org.apache.dubbo.common.utils.ReflectUtils.resolveTypes; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; /** * Miscellaneous method utility methods. * Mainly for internal use within the framework. * * @since 2.7.2 */ public interface MethodUtils { /** * Return {@code true} if the provided method is a set method. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is setter method */ static boolean isSetter(Method method) { return method.getName().startsWith("set") && !"set".equals(method.getName()) && Modifier.isPublic(method.getModifiers()) && method.getParameterCount() == 1 && ClassUtils.isPrimitive(method.getParameterTypes()[0]); } /** * Return {@code true} if the provided method is a get method. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is getter method */ static boolean isGetter(Method method) { String name = method.getName(); return (name.startsWith("get") || name.startsWith("is")) && !"get".equals(name) && !"is".equals(name) && !"getClass".equals(name) && !"getObject".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && ClassUtils.isPrimitive(method.getReturnType()); } /** * Return {@code true} If this method is a meta method. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is meta method */ static boolean isMetaMethod(Method method) { String name = method.getName(); if (!(name.startsWith("get") || name.startsWith("is"))) { return false; } if ("get".equals(name)) { return false; } if ("getClass".equals(name)) { return false; } if (!Modifier.isPublic(method.getModifiers())) { return false; } if (method.getParameterTypes().length != 0) { return false; } if (!ClassUtils.isPrimitive(method.getReturnType())) { return false; } return true; } /** * Check if the method is a deprecated method. The standard is whether the {@link java.lang.Deprecated} annotation is declared on the class. * Return {@code true} if this annotation is present. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is deprecated method */ static boolean isDeprecated(Method method) { return method.getAnnotation(Deprecated.class) != null; } /** * Create an instance of {@link Predicate} for {@link Method} to exclude the specified declared class * * @param declaredClass the declared class to exclude * @return non-null * @since 2.7.6 */ static Predicate<Method> excludedDeclaredClass(Class<?> declaredClass) { return method -> !Objects.equals(declaredClass, method.getDeclaringClass()); } /** * Get all {@link Method methods} of the declared class * * @param declaringClass the declared class * @param includeInheritedTypes include the inherited types, e,g. super classes or interfaces * @param publicOnly only public method * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @since 2.7.6 */ static List<Method> getMethods( Class<?> declaringClass, boolean includeInheritedTypes, boolean publicOnly, Predicate<Method>... methodsToFilter) { if (declaringClass == null || declaringClass.isPrimitive()) { return emptyList(); } // All declared classes List<Class<?>> declaredClasses = new LinkedList<>(); // Add the top declaring class declaredClasses.add(declaringClass); // If the super classes are resolved, all them into declaredClasses if (includeInheritedTypes) { declaredClasses.addAll(getAllInheritedTypes(declaringClass)); } // All methods List<Method> allMethods = new LinkedList<>(); for (Class<?> classToSearch : declaredClasses) { Method[] methods = publicOnly ? classToSearch.getMethods() : classToSearch.getDeclaredMethods(); // Add the declared methods or public methods for (Method method : methods) { allMethods.add(method); } } return unmodifiableList(filterAll(allMethods, methodsToFilter)); } /** * Get all declared {@link Method methods} of the declared class, excluding the inherited methods * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getDeclaredMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, false, false, methodsToFilter); } /** * Get all public {@link Method methods} of the declared class, including the inherited methods. * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, false, true, methodsToFilter); } /** * Get all declared {@link Method methods} of the declared class, including the inherited methods. * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getAllDeclaredMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, true, false, methodsToFilter); } /** * Get all public {@link Method methods} of the declared class, including the inherited methods. * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getAllMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, true, true, methodsToFilter); } // static List<Method> getOverriderMethods(Class<?> implementationClass, Class<?>... superTypes) { // // } /** * Find the {@link Method} by the the specified type and method name without the parameter types * * @param type the target type * @param methodName the specified method name * @return if not found, return <code>null</code> * @since 2.7.6 */ static Method findMethod(Class type, String methodName) { return findMethod(type, methodName, EMPTY_CLASS_ARRAY); } /** * Find the {@link Method} by the the specified type, method name and parameter types * * @param type the target type * @param methodName the method name * @param parameterTypes the parameter types * @return if not found, return <code>null</code> * @since 2.7.6 */ static Method findMethod(Class type, String methodName, Class<?>... parameterTypes) { Method method = null; try { if (type != null && isNotEmpty(methodName)) { method = type.getDeclaredMethod(methodName, parameterTypes); } } catch (NoSuchMethodException e) { } return method; } /** * Invoke the target object and method * * @param object the target object * @param methodName the method name * @param methodParameters the method parameters * @param <T> the return type * @return the target method's execution result * @since 2.7.6 */ static <T> T invokeMethod(Object object, String methodName, Object... methodParameters) { Class type = object.getClass(); Class[] parameterTypes = resolveTypes(methodParameters); Method method = findMethod(type, methodName, parameterTypes); T value = null; if (method == null) { throw new IllegalStateException( String.format("cannot find method %s,class: %s", methodName, type.getName())); } try { final boolean isAccessible = method.isAccessible(); if (!isAccessible) { method.setAccessible(true); } value = (T) method.invoke(object, methodParameters); method.setAccessible(isAccessible); } catch (Exception e) { throw new IllegalArgumentException(e); } return value; } /** * Tests whether one method, as a member of a given type, * overrides another method. * * @param overrider the first method, possible overrider * @param overridden the second method, possibly being overridden * @return {@code true} if and only if the first method overrides * the second * @jls 8.4.8 Inheritance, Overriding, and Hiding * @jls 9.4.1 Inheritance and Overriding * @see Elements#overrides(ExecutableElement, ExecutableElement, TypeElement) */ static boolean overrides(Method overrider, Method overridden) { if (overrider == null || overridden == null) { return false; } // equality comparison: If two methods are same if (Objects.equals(overrider, overridden)) { return false; } // Modifiers comparison: Any method must be non-static method if (isStatic(overrider) || isStatic(overridden)) { // return false; } // Modifiers comparison: the accessibility of any method must not be private if (isPrivate(overrider) || isPrivate(overridden)) { return false; } // Inheritance comparison: The declaring class of overrider must be inherit from the overridden's if (!overridden.getDeclaringClass().isAssignableFrom(overrider.getDeclaringClass())) { return false; } // Method comparison: must not be "default" method if (overrider.isDefault()) { return false; } // Method comparison: The method name must be equal if (!Objects.equals(overrider.getName(), overridden.getName())) { return false; } // Method comparison: The count of method parameters must be equal if (!Objects.equals(overrider.getParameterCount(), overridden.getParameterCount())) { return false; } // Method comparison: Any parameter type of overrider must equal the overridden's for (int i = 0; i < overrider.getParameterCount(); i++) { if (!Objects.equals(overridden.getParameterTypes()[i], overrider.getParameterTypes()[i])) { return false; } } // Method comparison: The return type of overrider must be inherit from the overridden's if (!overridden.getReturnType().isAssignableFrom(overrider.getReturnType())) { return false; } // Throwable comparison: "throws" Throwable list will be ignored, trust the compiler verify return true; } /** * Find the nearest overridden {@link Method method} from the inherited class * * @param overrider the overrider {@link Method method} * @return if found, the overrider <code>method</code>, or <code>null</code> */ static Method findNearestOverriddenMethod(Method overrider) { Class<?> declaringClass = overrider.getDeclaringClass(); Method overriddenMethod = null; for (Class<?> inheritedType : getAllInheritedTypes(declaringClass)) { overriddenMethod = findOverriddenMethod(overrider, inheritedType); if (overriddenMethod != null) { break; } } return overriddenMethod; } /** * Find the overridden {@link Method method} from the declaring class * * @param overrider the overrider {@link Method method} * @param declaringClass the class that is declaring the overridden {@link Method method} * @return if found, the overrider <code>method</code>, or <code>null</code> */ static Method findOverriddenMethod(Method overrider, Class<?> declaringClass) { List<Method> matchedMethods = getAllMethods(declaringClass, method -> overrides(overrider, method)); return matchedMethods.isEmpty() ? null : matchedMethods.get(0); } /** * Extract fieldName from set/get/is method. if it's not a set/get/is method, return empty string. * If method equals get/is/getClass/getObject, also return empty string. * * @param method method * @return fieldName */ static String extractFieldName(Method method) { List<String> emptyFieldMethod = Arrays.asList("is", "get", "getObject", "getClass"); String methodName = method.getName(); String fieldName = ""; if (emptyFieldMethod.contains(methodName)) { return fieldName; } else if (methodName.startsWith("get")) { fieldName = methodName.substring("get".length()); } else if (methodName.startsWith("set")) { fieldName = methodName.substring("set".length()); } else if (methodName.startsWith("is")) { fieldName = methodName.substring("is".length()); } else { return fieldName; } if (StringUtils.isNotEmpty(fieldName)) { fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); } return fieldName; } /** * Invoke and return double value. * * @param method method * @param targetObj the object the method is invoked from * @return double value */ static double invokeAndReturnDouble(Method method, Object targetObj) { try { return method != null ? (double) method.invoke(targetObj) : Double.NaN; } catch (Exception e) { return Double.NaN; } } /** * Invoke and return long value. * * @param method method * @param targetObj the object the method is invoked from * @return long value */ static long invokeAndReturnLong(Method method, Object targetObj) { try { return method != null ? (long) method.invoke(targetObj) : -1; } catch (Exception e) { return -1; } } }
6,873
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.java
/* * 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 java.util.Comparator; /** * The {@link Comparator} for {@link CharSequence} * * @since 2.7.6 */ public class CharSequenceComparator implements Comparator<CharSequence> { public static final CharSequenceComparator INSTANCE = new CharSequenceComparator(); private CharSequenceComparator() {} @Override public int compare(CharSequence c1, CharSequence c2) { return c1.toString().compareTo(c2.toString()); } }
6,874
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.java
/* * 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 java.util.LinkedHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A 'least recently used' cache based on LinkedHashMap. * * @param <K> key * @param <V> value */ public class LRUCache<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = -5167631809472116969L; private static final float DEFAULT_LOAD_FACTOR = 0.75f; private static final int DEFAULT_MAX_CAPACITY = 1000; private final Lock lock = new ReentrantLock(); private volatile int maxCapacity; public LRUCache() { this(DEFAULT_MAX_CAPACITY); } public LRUCache(int maxCapacity) { super(16, DEFAULT_LOAD_FACTOR, true); this.maxCapacity = maxCapacity; } @Override protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) { return size() > maxCapacity; } @Override public boolean containsKey(Object key) { lock.lock(); try { return super.containsKey(key); } finally { lock.unlock(); } } @Override public V get(Object key) { lock.lock(); try { return super.get(key); } finally { lock.unlock(); } } @Override public V put(K key, V value) { lock.lock(); try { return super.put(key, value); } finally { lock.unlock(); } } @Override public V remove(Object key) { lock.lock(); try { return super.remove(key); } finally { lock.unlock(); } } @Override public int size() { lock.lock(); try { return super.size(); } finally { lock.unlock(); } } @Override public void clear() { lock.lock(); try { super.clear(); } finally { lock.unlock(); } } public void lock() { lock.lock(); } public void releaseLock() { lock.unlock(); } public int getMaxCapacity() { return maxCapacity; } public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } }
6,875
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.java
/* * 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 java.util.AbstractSet; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>, java.io.Serializable { private static final long serialVersionUID = -8672117787651310382L; private static final Object PRESENT = new Object(); private final ConcurrentMap<E, Object> map; public ConcurrentHashSet() { map = new ConcurrentHashMap<>(); } public ConcurrentHashSet(int initialCapacity) { map = new ConcurrentHashMap<>(initialCapacity); } /** * Returns an iterator over the elements in this set. The elements are * returned in no particular order. * * @return an Iterator over the elements in this set * @see ConcurrentModificationException */ @Override public Iterator<E> iterator() { return map.keySet().iterator(); } /** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality) */ @Override public int size() { return map.size(); } /** * Returns <tt>true</tt> if this set contains no elements. * * @return <tt>true</tt> if this set contains no elements */ @Override public boolean isEmpty() { return map.isEmpty(); } /** * Returns <tt>true</tt> if this set contains the specified element. More * formally, returns <tt>true</tt> if and only if this set contains an * element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element */ @Override public boolean contains(Object o) { return map.containsKey(o); } /** * Adds the specified element to this set if it is not already present. More * formally, adds the specified element <tt>e</tt> to this set if this set * contains no element <tt>e2</tt> such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. If this * set already contains the element, the call leaves the set unchanged and * returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ @Override public boolean add(E e) { return map.put(e, PRESENT) == null; } /** * Removes the specified element from this set if it is present. More * formally, removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if this * set contains such an element. Returns <tt>true</tt> if this set contained * the element (or equivalently, if this set changed as a result of the * call). (This set will not contain the element once the call returns.) * * @param o object to be removed from this set, if present * @return <tt>true</tt> if the set contained the specified element */ @Override public boolean remove(Object o) { return map.remove(o) == PRESENT; } /** * Removes all of the elements from this set. The set will be empty after * this call returns. */ @Override public void clear() { map.clear(); } }
6,876
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.java
/* * 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.config.AbstractConfig; import java.util.Arrays; import java.util.List; import java.util.Map; public class ToStringUtils { private ToStringUtils() {} public static String printToString(Object obj) { if (obj == null) { return "null"; } try { return JsonUtils.toJson(obj); } catch (Throwable throwable) { if (obj instanceof Object[]) { return Arrays.toString((Object[]) obj); } return obj.toString(); } } public static String toString(Object obj) { if (obj == null) { return "null"; } if (ClassUtils.isSimpleType(obj.getClass())) { return obj.toString(); } if (obj.getClass().isPrimitive()) { return obj.toString(); } if (obj instanceof Object[]) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); Object[] objects = (Object[]) obj; for (int i = 0; i < objects.length; i++) { stringBuilder.append(toString(objects[i])); if (i != objects.length - 1) { stringBuilder.append(", "); } } stringBuilder.append("]"); return stringBuilder.toString(); } if (obj instanceof List) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); List list = (List) obj; for (int i = 0; i < list.size(); i++) { stringBuilder.append(toString(list.get(i))); if (i != list.size() - 1) { stringBuilder.append(", "); } } stringBuilder.append("]"); return stringBuilder.toString(); } if (obj instanceof Map) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("{"); Map map = (Map) obj; int i = 0; for (Object key : map.keySet()) { stringBuilder.append(toString(key)); stringBuilder.append("="); stringBuilder.append(toString(map.get(key))); if (i != map.size() - 1) { stringBuilder.append(", "); } i++; } stringBuilder.append("}"); return stringBuilder.toString(); } if (obj instanceof AbstractConfig) { return obj.toString(); } return obj.getClass() + "@" + Integer.toHexString(System.identityHashCode(obj)); } }
6,877
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java
/* * 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 java.io.Serializable; import java.util.List; /** * The default implementation of {@link Page} * * @since 2.7.5 */ public class DefaultPage<T> implements Page<T>, Serializable { private static final long serialVersionUID = 1099331838954070419L; private final int requestOffset; private final int pageSize; private final int totalSize; private final List<T> data; private final int totalPages; private final boolean hasNext; public DefaultPage(int requestOffset, int pageSize, List<T> data, int totalSize) { this.requestOffset = requestOffset; this.pageSize = pageSize; this.data = data; this.totalSize = totalSize; int remain = totalSize % pageSize; this.totalPages = remain > 0 ? (totalSize / pageSize) + 1 : totalSize / pageSize; this.hasNext = totalSize - requestOffset - pageSize > 0; } @Override public int getOffset() { return requestOffset; } @Override public int getPageSize() { return pageSize; } @Override public int getTotalSize() { return totalSize; } @Override public int getTotalPages() { return totalPages; } @Override public List<T> getData() { return data; } @Override public boolean hasNext() { return hasNext; } }
6,878
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeCheckStatus.java
/* * 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; public enum SerializeCheckStatus { /** * Disable serialize check for all classes */ DISABLE(0), /** * Only deny danger classes, warn if other classes are not in allow list */ WARN(1), /** * Only allow classes in allow list, deny if other classes are not in allow list */ STRICT(2); private final int level; SerializeCheckStatus(int level) { this.level = level; } public int level() { return level; } }
6,879
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.java
/* * 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 java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Java Reflection {@link Member} Utilities class * * @since 2.7.6 */ public interface MemberUtils { /** * check the specified {@link Member member} is static or not ? * * @param member {@link Member} instance, e.g, {@link Constructor}, {@link Method} or {@link Field} * @return Iff <code>member</code> is static one, return <code>true</code>, or <code>false</code> */ static boolean isStatic(Member member) { return member != null && Modifier.isStatic(member.getModifiers()); } /** * check the specified {@link Member member} is private or not ? * * @param member {@link Member} instance, e.g, {@link Constructor}, {@link Method} or {@link Field} * @return Iff <code>member</code> is private one, return <code>true</code>, or <code>false</code> */ static boolean isPrivate(Member member) { return member != null && Modifier.isPrivate(member.getModifiers()); } /** * check the specified {@link Member member} is public or not ? * * @param member {@link Member} instance, e.g, {@link Constructor}, {@link Method} or {@link Field} * @return Iff <code>member</code> is public one, return <code>true</code>, or <code>false</code> */ static boolean isPublic(Member member) { return member != null && Modifier.isPublic(member.getModifiers()); } }
6,880
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.java
/* * 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 java.lang.reflect.Method; import java.util.Comparator; /** * The Comparator class for {@link Method}, the comparison rule : * <ol> * <li>Comparing to two {@link Method#getName() method names} {@link String#compareTo(String) lexicographically}. * If equals, go to step 2</li> * <li>Comparing to the count of two method parameters. If equals, go to step 3</li> * <li>Comparing to the type names of methods parameter {@link String#compareTo(String) lexicographically}</li> * </ol> * * @since 2.7.6 */ public class MethodComparator implements Comparator<Method> { public static final MethodComparator INSTANCE = new MethodComparator(); private MethodComparator() {} @Override public int compare(Method m1, Method m2) { if (m1.equals(m2)) { return 0; } // Step 1 String n1 = m1.getName(); String n2 = m2.getName(); int value = n1.compareTo(n2); if (value == 0) { // Step 2 Class[] types1 = m1.getParameterTypes(); Class[] types2 = m2.getParameterTypes(); value = types1.length - types2.length; if (value == 0) { // Step 3 for (int i = 0; i < types1.length; i++) { value = types1[i].getName().compareTo(types2[i].getName()); if (value != 0) { break; } } } } return Integer.compare(value, 0); } }
6,881
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java
/* * 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 java.util.concurrent.TimeUnit; /** * Provide currentTimeMillis acquisition for high-frequency access scenarios. */ public final class TimeUtils { private static volatile long currentTimeMillis; private static volatile boolean isTickerAlive = false; private static volatile boolean isFallback = false; private TimeUtils() {} public static long currentTimeMillis() { // When an exception occurs in the Ticker mechanism, fall back. if (isFallback) { return System.currentTimeMillis(); } if (!isTickerAlive) { try { startTicker(); } catch (Exception e) { isFallback = true; } } return currentTimeMillis; } private static synchronized void startTicker() { if (!isTickerAlive) { currentTimeMillis = System.currentTimeMillis(); Thread ticker = new Thread(() -> { while (isTickerAlive) { currentTimeMillis = System.currentTimeMillis(); try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { isTickerAlive = false; Thread.currentThread().interrupt(); } catch (Exception ignored) { // } } }); ticker.setDaemon(true); ticker.setName("time-millis-ticker-thread"); ticker.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { isFallback = true; ticker.interrupt(); })); isTickerAlive = true; } } }
6,882
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java
/* * 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.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.Iterator; import java.util.List; import org.apache.log4j.Level; public class LogUtil { private static final Logger Log = LoggerFactory.getLogger(LogUtil.class); public static void start() { DubboAppender.doStart(); } public static void stop() { DubboAppender.doStop(); } public static boolean checkNoError() { if (findLevel(Level.ERROR) == 0) { return true; } else { return false; } } public static int findName(String expectedLogName) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logName = logList.get(i).getLogName(); if (logName.contains(expectedLogName)) { count++; } } return count; } public static int findLevel(Level expectedLevel) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Level logLevel = logList.get(i).getLogLevel(); if (logLevel.equals(expectedLevel)) { count++; } } return count; } public static int findLevelWithThreadName(Level expectedLevel, String threadName) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Log log = logList.get(i); if (log.getLogLevel().equals(expectedLevel) && log.getLogThread().equals(threadName)) { count++; } } return count; } public static int findThread(String expectedThread) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logThread = logList.get(i).getLogThread(); if (logThread.contains(expectedThread)) { count++; } } return count; } public static int findMessage(String expectedMessage) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logMessage = logList.get(i).getLogMessage(); if (logMessage.contains(expectedMessage)) { count++; } } return count; } public static int findMessage(Level expectedLevel, String expectedMessage) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Level logLevel = logList.get(i).getLogLevel(); if (logLevel.equals(expectedLevel)) { String logMessage = logList.get(i).getLogMessage(); if (logMessage.contains(expectedMessage)) { count++; } } } return count; } public static <T> void printList(List<T> list) { Log.info("PrintList:"); Iterator<T> it = list.iterator(); while (it.hasNext()) { Log.info(it.next().toString()); } } }
6,883
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.java
/* * 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 java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.StringUtils.QUESTION_MASK; import static org.apache.dubbo.common.utils.StringUtils.SLASH; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; import static org.apache.dubbo.common.utils.StringUtils.replace; /** * Path Utilities class * * @since 2.7.6 */ public interface PathUtils { static String buildPath(String rootPath, String... subPaths) { Set<String> paths = new LinkedHashSet<>(); paths.add(rootPath); paths.addAll(asList(subPaths)); return normalize(paths.stream().filter(StringUtils::isNotEmpty).collect(Collectors.joining(SLASH))); } /** * Normalize path: * <ol> * <li>To remove query string if presents</li> * <li>To remove duplicated slash("/") if exists</li> * </ol> * * @param path path to be normalized * @return a normalized path if required */ static String normalize(String path) { if (isEmpty(path)) { return SLASH; } String normalizedPath = path; int index = normalizedPath.indexOf(QUESTION_MASK); if (index > -1) { normalizedPath = normalizedPath.substring(0, index); } while (normalizedPath.contains("//")) { normalizedPath = replace(normalizedPath, "//", "/"); } return normalizedPath; } }
6,884
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java
/* * 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 java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; public class CompatibleTypeUtils { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * the text to parse such as "2007-12-03T10:15:30" */ private static final int ISO_LOCAL_DATE_TIME_MIN_LEN = 19; private CompatibleTypeUtils() {} /** * Compatible type convert. Null value is allowed to pass in. If no conversion is needed, then the original value * will be returned. * <p> * Supported compatible type conversions include (primary types and corresponding wrappers are not listed): * <ul> * <li> String -> char, enum, Date * <li> byte, short, int, long -> byte, short, int, long * <li> float, double -> float, double * </ul> */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format( "CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } if (type == BigInteger.class) { return new BigInteger(string); } if (type == BigDecimal.class) { return new BigDecimal(string); } if (type == Short.class || type == short.class) { return new Short(string); } if (type == Integer.class || type == int.class) { return new Integer(string); } if (type == Long.class || type == long.class) { return new Long(string); } if (type == Double.class || type == double.class) { return new Double(string); } if (type == Float.class || type == float.class) { return new Float(string); } if (type == Byte.class || type == byte.class) { return new Byte(string); } if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } if (type == Date.class || type == java.sql.Date.class || type == java.sql.Timestamp.class || type == java.sql.Time.class) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); if (type == java.sql.Date.class) { return new java.sql.Date(date.getTime()); } if (type == java.sql.Timestamp.class) { return new java.sql.Timestamp(date.getTime()); } if (type == java.sql.Time.class) { return new java.sql.Time(date.getTime()); } return date; } catch (ParseException e) { throw new IllegalStateException( "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } if (type == java.time.LocalDateTime.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDateTime.parse(string); } if (type == java.time.LocalDate.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDate.parse(string); } if (type == java.time.LocalTime.class) { if (StringUtils.isEmpty(string)) { return null; } if (string.length() >= ISO_LOCAL_DATE_TIME_MIN_LEN) { return LocalDateTime.parse(string).toLocalTime(); } else { return LocalTime.parse(string); } } if (type == Class.class) { try { return ReflectUtils.name2class(string); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } if (char[].class.equals(type)) { // Process string to char array for generic invoke // See // - https://github.com/apache/dubbo/issues/2003 int len = string.length(); char[] chars = new char[len]; string.getChars(0, len, chars, 0); return chars; } } if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } if (type == short.class || type == Short.class) { return number.shortValue(); } if (type == int.class || type == Integer.class) { return number.intValue(); } if (type == long.class || type == Long.class) { return number.longValue(); } if (type == float.class || type == Float.class) { return number.floatValue(); } if (type == double.class || type == Double.class) { return number.doubleValue(); } if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } if (type == BigDecimal.class) { return new BigDecimal(number.toString()); } if (type == Date.class) { return new Date(number.longValue()); } if (type == boolean.class || type == Boolean.class) { return 0 != number.intValue(); } } if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } if (!type.isInterface()) { try { Collection result = (Collection) type.getDeclaredConstructor().newInstance(); result.addAll(collection); return result; } catch (Throwable ignored) { } } if (type == List.class) { return new ArrayList<Object>(collection); } if (type == Set.class) { return new HashSet<Object>(collection); } } if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { int length = Array.getLength(value); Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.getDeclaredConstructor().newInstance(); } catch (Exception e) { collection = new ArrayList<Object>(length); } } else if (type == Set.class) { collection = new HashSet<Object>(Math.max((int) (length / .75f) + 1, 16)); } else { collection = new ArrayList<Object>(length); } for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } }
6,885
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.java
/* * 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.logger.Logger; public class LogHelper { private LogHelper() {} public static void trace(Logger logger, String msg) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(msg); } } public static void trace(Logger logger, Throwable throwable) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(throwable); } } public static void trace(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(msg, e); } } public static void debug(Logger logger, String msg) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(msg); } } public static void debug(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(e); } } public static void debug(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(msg, e); } } public static void info(Logger logger, String msg) { if (logger == null) { return; } if (logger.isInfoEnabled()) { logger.info(msg); } } public static void info(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isInfoEnabled()) { logger.info(e); } } public static void info(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isInfoEnabled()) { logger.info(msg, e); } } public static void warn(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isWarnEnabled()) { logger.warn(msg, e); } } public static void warn(Logger logger, String msg) { if (logger == null) { return; } if (logger.isWarnEnabled()) { logger.warn(msg); } } public static void warn(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isWarnEnabled()) { logger.warn(e); } } public static void error(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isErrorEnabled()) { logger.error(e); } } public static void error(Logger logger, String msg) { if (logger == null) { return; } if (logger.isErrorEnabled()) { logger.error(msg); } } public static void error(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isErrorEnabled()) { logger.error(msg, e); } } }
6,886
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.java
/* * 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.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeClassLoaderListener; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST; import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST; import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL; import static org.apache.dubbo.common.constants.CommonConstants.SERIALIZE_ALLOW_LIST_FILE_PATH; import static org.apache.dubbo.common.constants.CommonConstants.SERIALIZE_BLOCKED_LIST_FILE_PATH; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class SerializeSecurityConfigurator implements ScopeClassLoaderListener<ModuleModel> { private final SerializeSecurityManager serializeSecurityManager; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityConfigurator.class); private final ModuleModel moduleModel; private volatile boolean autoTrustSerializeClass = true; private volatile int trustSerializeClassLevel = Integer.MAX_VALUE; public SerializeSecurityConfigurator(ModuleModel moduleModel) { this.moduleModel = moduleModel; moduleModel.addClassLoaderListener(this); FrameworkModel frameworkModel = moduleModel.getApplicationModel().getFrameworkModel(); serializeSecurityManager = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); refreshStatus(); refreshCheck(); refreshConfig(); onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); } public void refreshCheck() { Optional<ApplicationConfig> applicationConfig = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); autoTrustSerializeClass = applicationConfig .map(ApplicationConfig::getAutoTrustSerializeClass) .orElse(true); trustSerializeClassLevel = applicationConfig .map(ApplicationConfig::getTrustSerializeClassLevel) .orElse(Integer.MAX_VALUE); serializeSecurityManager.setCheckSerializable( applicationConfig.map(ApplicationConfig::getCheckSerializable).orElse(true)); } @Override public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { refreshClassLoader(classLoader); } @Override public void onRemoveClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { // ignore } private void refreshClassLoader(ClassLoader classLoader) { loadAllow(classLoader); loadBlocked(classLoader); } private void refreshConfig() { String allowedClassList = System.getProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "").trim(); String blockedClassList = System.getProperty(CLASS_DESERIALIZE_BLOCKED_LIST, "").trim(); if (StringUtils.isNotEmpty(allowedClassList)) { String[] classStrings = allowedClassList.trim().split(","); for (String className : classStrings) { className = className.trim(); if (StringUtils.isNotEmpty(className)) { serializeSecurityManager.addToAlwaysAllowed(className); } } } if (StringUtils.isNotEmpty(blockedClassList)) { String[] classStrings = blockedClassList.trim().split(","); for (String className : classStrings) { className = className.trim(); if (StringUtils.isNotEmpty(className)) { serializeSecurityManager.addToDisAllowed(className); } } } } private void loadAllow(ClassLoader classLoader) { Set<URL> urls = ClassLoaderResourceLoader.loadResources(SERIALIZE_ALLOW_LIST_FILE_PATH, classLoader); for (URL u : urls) { try { logger.info("Read serialize allow list from " + u); String[] lines = IOUtils.readLines(u.openStream()); for (String line : lines) { line = line.trim(); if (StringUtils.isEmpty(line) || line.startsWith("#")) { continue; } serializeSecurityManager.addToAlwaysAllowed(line); } } catch (IOException e) { logger.error( COMMON_IO_EXCEPTION, "", "", "Failed to load allow class list! Will ignore allow lis from " + u, e); } } } private void loadBlocked(ClassLoader classLoader) { Set<URL> urls = ClassLoaderResourceLoader.loadResources(SERIALIZE_BLOCKED_LIST_FILE_PATH, classLoader); for (URL u : urls) { try { logger.info("Read serialize blocked list from " + u); String[] lines = IOUtils.readLines(u.openStream()); for (String line : lines) { line = line.trim(); if (StringUtils.isEmpty(line) || line.startsWith("#")) { continue; } serializeSecurityManager.addToDisAllowed(line); } } catch (IOException e) { logger.error( COMMON_IO_EXCEPTION, "", "", "Failed to load blocked class list! Will ignore blocked lis from " + u, e); } } } public void refreshStatus() { Optional<ApplicationConfig> application = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); String statusString = application.map(ApplicationConfig::getSerializeCheckStatus).orElse(null); SerializeCheckStatus checkStatus = null; if (StringUtils.isEmpty(statusString)) { String openCheckClass = System.getProperty(CommonConstants.CLASS_DESERIALIZE_OPEN_CHECK, "true"); if (!Boolean.parseBoolean(openCheckClass)) { checkStatus = SerializeCheckStatus.DISABLE; } String blockAllClassExceptAllow = System.getProperty(CLASS_DESERIALIZE_BLOCK_ALL, "false"); if (Boolean.parseBoolean(blockAllClassExceptAllow)) { checkStatus = SerializeCheckStatus.STRICT; } } else { checkStatus = SerializeCheckStatus.valueOf(statusString); } if (checkStatus != null) { serializeSecurityManager.setCheckStatus(checkStatus); } } public synchronized void registerInterface(Class<?> clazz) { if (!autoTrustSerializeClass) { return; } Set<Type> markedClass = new HashSet<>(); checkClass(markedClass, clazz); addToAllow(clazz.getName()); Method[] methodsToExport = clazz.getMethods(); for (Method method : methodsToExport) { Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterType : parameterTypes) { checkClass(markedClass, parameterType); } Type[] genericParameterTypes = method.getGenericParameterTypes(); for (Type genericParameterType : genericParameterTypes) { checkType(markedClass, genericParameterType); } Class<?> returnType = method.getReturnType(); checkClass(markedClass, returnType); Type genericReturnType = method.getGenericReturnType(); checkType(markedClass, genericReturnType); Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { checkClass(markedClass, exceptionType); } Type[] genericExceptionTypes = method.getGenericExceptionTypes(); for (Type genericExceptionType : genericExceptionTypes) { checkType(markedClass, genericExceptionType); } } } private void checkType(Set<Type> markedClass, Type type) { if (type == null) { return; } if (type instanceof Class) { checkClass(markedClass, (Class<?>) type); return; } if (!markedClass.add(type)) { return; } if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; checkClass(markedClass, (Class<?>) parameterizedType.getRawType()); for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) { checkType(markedClass, actualTypeArgument); } } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; checkType(markedClass, genericArrayType.getGenericComponentType()); } else if (type instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) type; for (Type bound : typeVariable.getBounds()) { checkType(markedClass, bound); } } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; for (Type bound : wildcardType.getUpperBounds()) { checkType(markedClass, bound); } for (Type bound : wildcardType.getLowerBounds()) { checkType(markedClass, bound); } } } private void checkClass(Set<Type> markedClass, Class<?> clazz) { if (clazz == null) { return; } if (!markedClass.add(clazz)) { return; } addToAllow(clazz.getName()); if (ClassUtils.isSimpleType(clazz) || clazz.isPrimitive() || clazz.isArray()) { return; } String className = clazz.getName(); if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("com.sun.") || className.startsWith("sun.") || className.startsWith("jdk.")) { return; } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> interfaceClass : interfaces) { checkClass(markedClass, interfaceClass); } for (Type genericInterface : clazz.getGenericInterfaces()) { checkType(markedClass, genericInterface); } Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { checkClass(markedClass, superclass); } Type genericSuperclass = clazz.getGenericSuperclass(); if (genericSuperclass != null) { checkType(markedClass, genericSuperclass); } Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (Modifier.isTransient(field.getModifiers())) { continue; } Class<?> fieldClass = field.getType(); checkClass(markedClass, fieldClass); checkType(markedClass, field.getGenericType()); } } private void addToAllow(String className) { // ignore jdk if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("com.sun.") || className.startsWith("sun.") || className.startsWith("jdk.")) { serializeSecurityManager.addToAllowed(className); return; } // add group package String[] subs = className.split("\\."); if (subs.length > trustSerializeClassLevel) { serializeSecurityManager.addToAllowed( Arrays.stream(subs).limit(trustSerializeClassLevel).collect(Collectors.joining(".")) + "."); } else { serializeSecurityManager.addToAllowed(className); } } }
6,887
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java
/* * 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 java.io.Serializable; import org.apache.log4j.Level; public class Log implements Serializable { private static final long serialVersionUID = -534113138054377073L; private String logName; private Level logLevel; private String logMessage; private String logThread; public String getLogName() { return logName; } public void setLogName(String logName) { this.logName = logName; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getLogMessage() { return logMessage; } public void setLogMessage(String logMessage) { this.logMessage = logMessage; } public String getLogThread() { return logThread; } public void setLogThread(String logThread) { this.logThread = logThread; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((logLevel == null) ? 0 : logLevel.hashCode()); result = prime * result + ((logMessage == null) ? 0 : logMessage.hashCode()); result = prime * result + ((logName == null) ? 0 : logName.hashCode()); result = prime * result + ((logThread == null) ? 0 : logThread.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Log other = (Log) obj; if (logLevel == null) { if (other.logLevel != null) { return false; } } else if (!logLevel.equals(other.logLevel)) { return false; } if (logMessage == null) { if (other.logMessage != null) { return false; } } else if (!logMessage.equals(other.logMessage)) { return false; } if (logName == null) { if (other.logName != null) { return false; } } else if (!logName.equals(other.logName)) { return false; } if (logThread == null) { if (other.logThread != null) { return false; } } else if (!logThread.equals(other.logThread)) { return false; } return true; } }
6,888
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.java
/* * 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 java.util.ArrayList; import java.util.List; import org.apache.log4j.FileAppender; import org.apache.log4j.spi.LoggingEvent; public class DubboAppender extends FileAppender { private static final String DEFAULT_FILE_NAME = "dubbo.log"; public DubboAppender() { super(); setFile(DEFAULT_FILE_NAME); } public static boolean available = false; public static List<Log> logList = new ArrayList<>(); public static void doStart() { available = true; } public static void doStop() { available = false; } public static void clear() { logList.clear(); } @Override public void append(LoggingEvent event) { super.append(event); if (available) { Log temp = parseLog(event); logList.add(temp); } } private Log parseLog(LoggingEvent event) { Log log = new Log(); log.setLogName(event.getLogger().getName()); log.setLogLevel(event.getLevel()); log.setLogThread(event.getThreadName()); log.setLogMessage(event.getMessage().toString()); return log; } }
6,889
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.java
/* * 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 java.lang.reflect.Field; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.reflect.Modifier.isFinal; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; import static org.apache.dubbo.common.utils.FieldUtils.getFieldValue; /** * The constant field value {@link Predicate} for the specified {@link Class} * * @see Predicate * @since 2.7.8 */ public class StringConstantFieldValuePredicate implements Predicate<String> { private final Set<String> constantFieldValues; public StringConstantFieldValuePredicate(Class<?> targetClass) { this.constantFieldValues = getConstantFieldValues(targetClass); } public static Predicate<String> of(Class<?> targetClass) { return new StringConstantFieldValuePredicate(targetClass); } private Set<String> getConstantFieldValues(Class<?> targetClass) { return Stream.of(targetClass.getFields()) .filter(f -> isStatic(f.getModifiers())) // static .filter(f -> isPublic(f.getModifiers())) // public .filter(f -> isFinal(f.getModifiers())) // final .map(this::getConstantValue) .filter(v -> v instanceof String) // filters String type .map(String.class::cast) // Casts String type .collect(Collectors.toSet()); } @Override public boolean test(String s) { return constantFieldValues.contains(s); } private Object getConstantValue(Field field) { return getFieldValue(null, field); } }
6,890
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NativeUtils.java
/* * 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 static org.apache.dubbo.common.constants.CommonConstants.NATIVE; public abstract class NativeUtils { public static boolean isNative() { return Boolean.parseBoolean(System.getProperty(NATIVE, "false")); } }
6,891
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AllowClassNotifyListener.java
/* * 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 java.util.Set; public interface AllowClassNotifyListener { SerializeCheckStatus DEFAULT_STATUS = SerializeCheckStatus.STRICT; void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList); void notifyCheckStatus(SerializeCheckStatus status); void notifyCheckSerializable(boolean checkSerializable); }
6,892
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java
/* * 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 java.beans.BeanInfo; import java.beans.Introspector; import java.beans.MethodDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty; /** * ReflectUtils */ public final class ReflectUtils { /** * void(V). */ public static final char JVM_VOID = 'V'; /** * boolean(Z). */ public static final char JVM_BOOLEAN = 'Z'; /** * byte(B). */ public static final char JVM_BYTE = 'B'; /** * char(C). */ public static final char JVM_CHAR = 'C'; /** * double(D). */ public static final char JVM_DOUBLE = 'D'; /** * float(F). */ public static final char JVM_FLOAT = 'F'; /** * int(I). */ public static final char JVM_INT = 'I'; /** * long(J). */ public static final char JVM_LONG = 'J'; /** * short(S). */ public static final char JVM_SHORT = 'S'; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; public static final String JAVA_IDENT_REGEX = "(?:[_$a-zA-Z][_$a-zA-Z0-9]*)"; public static final String JAVA_NAME_REGEX = "(?:" + JAVA_IDENT_REGEX + "(?:\\." + JAVA_IDENT_REGEX + ")*)"; public static final String CLASS_DESC = "(?:L" + JAVA_IDENT_REGEX + "(?:\\/" + JAVA_IDENT_REGEX + ")*;)"; public static final String ARRAY_DESC = "(?:\\[+(?:(?:[VZBCDFIJS])|" + CLASS_DESC + "))"; public static final String DESC_REGEX = "(?:(?:[VZBCDFIJS])|" + CLASS_DESC + "|" + ARRAY_DESC + ")"; public static final Pattern DESC_PATTERN = Pattern.compile(DESC_REGEX); public static final String METHOD_DESC_REGEX = "(?:(" + JAVA_IDENT_REGEX + ")?\\((" + DESC_REGEX + "*)\\)(" + DESC_REGEX + ")?)"; public static final Pattern METHOD_DESC_PATTERN = Pattern.compile(METHOD_DESC_REGEX); public static final Pattern GETTER_METHOD_DESC_PATTERN = Pattern.compile("get([A-Z][_a-zA-Z0-9]*)\\(\\)(" + DESC_REGEX + ")"); public static final Pattern SETTER_METHOD_DESC_PATTERN = Pattern.compile("set([A-Z][_a-zA-Z0-9]*)\\((" + DESC_REGEX + ")\\)V"); public static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN = Pattern.compile("(?:is|has|can)([A-Z][_a-zA-Z0-9]*)\\(\\)Z"); private static Map<Class<?>, Object> primitiveDefaults = new HashMap<>(); static { primitiveDefaults.put(int.class, 0); primitiveDefaults.put(long.class, 0L); primitiveDefaults.put(byte.class, (byte) 0); primitiveDefaults.put(char.class, (char) 0); primitiveDefaults.put(short.class, (short) 0); primitiveDefaults.put(float.class, (float) 0); primitiveDefaults.put(double.class, (double) 0); primitiveDefaults.put(boolean.class, false); primitiveDefaults.put(void.class, null); } private ReflectUtils() {} public static boolean isPrimitives(Class<?> cls) { while (cls.isArray()) { cls = cls.getComponentType(); } return isPrimitive(cls); } public static boolean isPrimitive(Class<?> cls) { return cls.isPrimitive() || cls == String.class || cls == Boolean.class || cls == Character.class || Number.class.isAssignableFrom(cls) || Date.class.isAssignableFrom(cls); } public static Class<?> getBoxedClass(Class<?> c) { if (c == int.class) { c = Integer.class; } else if (c == boolean.class) { c = Boolean.class; } else if (c == long.class) { c = Long.class; } else if (c == float.class) { c = Float.class; } else if (c == double.class) { c = Double.class; } else if (c == char.class) { c = Character.class; } else if (c == byte.class) { c = Byte.class; } else if (c == short.class) { c = Short.class; } return c; } /** * is compatible. * * @param c class. * @param o instance. * @return compatible or not. */ public static boolean isCompatible(Class<?> c, Object o) { boolean pt = c.isPrimitive(); if (o == null) { return !pt; } if (pt) { c = getBoxedClass(c); } return c == o.getClass() || c.isInstance(o); } /** * is compatible. * * @param cs class array. * @param os object array. * @return compatible or not. */ public static boolean isCompatible(Class<?>[] cs, Object[] os) { int len = cs.length; if (len != os.length) { return false; } if (len == 0) { return true; } for (int i = 0; i < len; i++) { if (!isCompatible(cs[i], os[i])) { return false; } } return true; } public static String getCodeBase(Class<?> cls) { if (cls == null) { return null; } ProtectionDomain domain = cls.getProtectionDomain(); if (domain == null) { return null; } CodeSource source = domain.getCodeSource(); if (source == null) { return null; } URL location = source.getLocation(); if (location == null) { return null; } return location.getFile(); } /** * get name. * java.lang.Object[][].class => "java.lang.Object[][]" * * @param c class. * @return name. */ public static String getName(Class<?> c) { if (c.isArray()) { StringBuilder sb = new StringBuilder(); do { sb.append("[]"); c = c.getComponentType(); } while (c.isArray()); return c.getName() + sb.toString(); } return c.getName(); } public static Class<?> getGenericClass(Class<?> cls) { return getGenericClass(cls, 0); } public static Class<?> getGenericClass(Class<?> cls, int i) { try { ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]); Object genericClass = parameterizedType.getActualTypeArguments()[i]; // handle nested generic type if (genericClass instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) genericClass).getRawType(); } // handle array generic type if (genericClass instanceof GenericArrayType) { return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType(); } // Requires JDK 7 or higher, Foo<int[]> is no longer GenericArrayType if (((Class) genericClass).isArray()) { return ((Class) genericClass).getComponentType(); } return (Class<?>) genericClass; } catch (Throwable e) { throw new IllegalArgumentException(cls.getName() + " generic type undefined!", e); } } /** * get method name. * "void do(int)", "void do()", "int do(java.lang.String,boolean)" * * @param m method. * @return name. */ public static String getName(final Method m) { StringBuilder ret = new StringBuilder(); ret.append(getName(m.getReturnType())).append(' '); ret.append(m.getName()).append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) { ret.append(','); } ret.append(getName(parameterTypes[i])); } ret.append(')'); return ret.toString(); } public static String getSignature(String methodName, Class<?>[] parameterTypes) { StringBuilder sb = new StringBuilder(methodName); sb.append('('); if (parameterTypes != null && parameterTypes.length > 0) { boolean first = true; for (Class<?> type : parameterTypes) { if (first) { first = false; } else { sb.append(','); } sb.append(type.getName()); } } sb.append(')'); return sb.toString(); } /** * get constructor name. * "()", "(java.lang.String,int)" * * @param c constructor. * @return name. */ public static String getName(final Constructor<?> c) { StringBuilder ret = new StringBuilder("("); Class<?>[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) { ret.append(','); } ret.append(getName(parameterTypes[i])); } ret.append(')'); return ret.toString(); } /** * get class desc. * boolean[].class => "[Z" * Object.class => "Ljava/lang/Object;" * * @param c class. * @return desc. * @throws NotFoundException */ public static String getDesc(Class<?> c) { StringBuilder ret = new StringBuilder(); while (c.isArray()) { ret.append('['); c = c.getComponentType(); } if (c.isPrimitive()) { String t = c.getName(); if ("void".equals(t)) { ret.append(JVM_VOID); } else if ("boolean".equals(t)) { ret.append(JVM_BOOLEAN); } else if ("byte".equals(t)) { ret.append(JVM_BYTE); } else if ("char".equals(t)) { ret.append(JVM_CHAR); } else if ("double".equals(t)) { ret.append(JVM_DOUBLE); } else if ("float".equals(t)) { ret.append(JVM_FLOAT); } else if ("int".equals(t)) { ret.append(JVM_INT); } else if ("long".equals(t)) { ret.append(JVM_LONG); } else if ("short".equals(t)) { ret.append(JVM_SHORT); } } else { ret.append('L'); ret.append(c.getName().replace('.', '/')); ret.append(';'); } return ret.toString(); } /** * get class array desc. * [int.class, boolean[].class, Object.class] => "I[ZLjava/lang/Object;" * * @param cs class array. * @return desc. * @throws NotFoundException */ public static String getDesc(final Class<?>[] cs) { if (cs.length == 0) { return ""; } StringBuilder sb = new StringBuilder(64); for (Class<?> c : cs) { sb.append(getDesc(c)); } return sb.toString(); } /** * get method desc. * int do(int arg1) => "do(I)I" * void do(String arg1,boolean arg2) => "do(Ljava/lang/String;Z)V" * * @param m method. * @return desc. */ public static String getDesc(final Method m) { StringBuilder ret = new StringBuilder(m.getName()).append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } public static String[] getDescArray(final Method m) { Class<?>[] parameterTypes = m.getParameterTypes(); String[] arr = new String[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { arr[i] = getDesc(parameterTypes[i]); } return arr; } /** * get constructor desc. * "()V", "(Ljava/lang/String;I)V" * * @param c constructor. * @return desc */ public static String getDesc(final Constructor<?> c) { StringBuilder ret = new StringBuilder("("); Class<?>[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append('V'); return ret.toString(); } /** * get method desc. * "(I)I", "()V", "(Ljava/lang/String;Z)V" * * @param m method. * @return desc. */ public static String getDescWithoutMethodName(Method m) { StringBuilder ret = new StringBuilder(); ret.append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } /** * get class desc. * Object.class => "Ljava/lang/Object;" * boolean[].class => "[Z" * * @param c class. * @return desc. * @throws NotFoundException */ public static String getDesc(final CtClass c) throws NotFoundException { StringBuilder ret = new StringBuilder(); if (c.isArray()) { ret.append('['); ret.append(getDesc(c.getComponentType())); } else if (c.isPrimitive()) { String t = c.getName(); if ("void".equals(t)) { ret.append(JVM_VOID); } else if ("boolean".equals(t)) { ret.append(JVM_BOOLEAN); } else if ("byte".equals(t)) { ret.append(JVM_BYTE); } else if ("char".equals(t)) { ret.append(JVM_CHAR); } else if ("double".equals(t)) { ret.append(JVM_DOUBLE); } else if ("float".equals(t)) { ret.append(JVM_FLOAT); } else if ("int".equals(t)) { ret.append(JVM_INT); } else if ("long".equals(t)) { ret.append(JVM_LONG); } else if ("short".equals(t)) { ret.append(JVM_SHORT); } } else { ret.append('L'); ret.append(c.getName().replace('.', '/')); ret.append(';'); } return ret.toString(); } /** * get method desc. * "do(I)I", "do()V", "do(Ljava/lang/String;Z)V" * * @param m method. * @return desc. */ public static String getDesc(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(m.getName()).append('('); CtClass[] parameterTypes = m.getParameterTypes(); for (CtClass parameterType : parameterTypes) { ret.append(getDesc(parameterType)); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } /** * get constructor desc. * "()V", "(Ljava/lang/String;I)V" * * @param c constructor. * @return desc */ public static String getDesc(final CtConstructor c) throws NotFoundException { StringBuilder ret = new StringBuilder("("); CtClass[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append('V'); return ret.toString(); } /** * get method desc. * "(I)I", "()V", "(Ljava/lang/String;Z)V". * * @param m method. * @return desc. */ public static String getDescWithoutMethodName(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(); ret.append('('); CtClass[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } /** * name to desc. * java.util.Map[][] => "[[Ljava/util/Map;" * * @param name name. * @return desc. */ public static String name2desc(String name) { StringBuilder sb = new StringBuilder(); int c = 0, index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } while (c-- > 0) { sb.append('['); } if ("void".equals(name)) { sb.append(JVM_VOID); } else if ("boolean".equals(name)) { sb.append(JVM_BOOLEAN); } else if ("byte".equals(name)) { sb.append(JVM_BYTE); } else if ("char".equals(name)) { sb.append(JVM_CHAR); } else if ("double".equals(name)) { sb.append(JVM_DOUBLE); } else if ("float".equals(name)) { sb.append(JVM_FLOAT); } else if ("int".equals(name)) { sb.append(JVM_INT); } else if ("long".equals(name)) { sb.append(JVM_LONG); } else if ("short".equals(name)) { sb.append(JVM_SHORT); } else { sb.append('L').append(name.replace('.', '/')).append(';'); } return sb.toString(); } /** * desc to name. * "[[I" => "int[][]" * * @param desc desc. * @return name. */ public static String desc2name(String desc) { StringBuilder sb = new StringBuilder(); int c = desc.lastIndexOf('[') + 1; if (desc.length() == c + 1) { switch (desc.charAt(c)) { case JVM_VOID: { sb.append("void"); break; } case JVM_BOOLEAN: { sb.append("boolean"); break; } case JVM_BYTE: { sb.append("byte"); break; } case JVM_CHAR: { sb.append("char"); break; } case JVM_DOUBLE: { sb.append("double"); break; } case JVM_FLOAT: { sb.append("float"); break; } case JVM_INT: { sb.append("int"); break; } case JVM_LONG: { sb.append("long"); break; } case JVM_SHORT: { sb.append("short"); break; } default: throw new RuntimeException(); } } else { sb.append(desc.substring(c + 1, desc.length() - 1).replace('/', '.')); } while (c-- > 0) { sb.append("[]"); } return sb.toString(); } public static Class<?> forName(String name) { try { return name2class(name); } catch (ClassNotFoundException e) { throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e); } } public static Class<?> forName(ClassLoader cl, String name) { try { return name2class(cl, name); } catch (ClassNotFoundException e) { throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e); } } /** * name to class. * "boolean" => boolean.class * "java.util.Map[][]" => java.util.Map[][].class * * @param name name. * @return Class instance. */ public static Class<?> name2class(String name) throws ClassNotFoundException { return name2class(ClassUtils.getClassLoader(), name); } /** * name to class. * "boolean" => boolean.class * "java.util.Map[][]" => java.util.Map[][].class * * @param cl ClassLoader instance. * @param name name. * @return Class instance. */ private static Class<?> name2class(ClassLoader cl, String name) throws ClassNotFoundException { int c = 0, index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } if (c > 0) { StringBuilder sb = new StringBuilder(); while (c-- > 0) { sb.append('['); } if ("void".equals(name)) { sb.append(JVM_VOID); } else if ("boolean".equals(name)) { sb.append(JVM_BOOLEAN); } else if ("byte".equals(name)) { sb.append(JVM_BYTE); } else if ("char".equals(name)) { sb.append(JVM_CHAR); } else if ("double".equals(name)) { sb.append(JVM_DOUBLE); } else if ("float".equals(name)) { sb.append(JVM_FLOAT); } else if ("int".equals(name)) { sb.append(JVM_INT); } else if ("long".equals(name)) { sb.append(JVM_LONG); } else if ("short".equals(name)) { sb.append(JVM_SHORT); } else { // "java.lang.Object" ==> "Ljava.lang.Object;" sb.append('L').append(name).append(';'); } name = sb.toString(); } else { if ("void".equals(name)) { return void.class; } if ("boolean".equals(name)) { return boolean.class; } if ("byte".equals(name)) { return byte.class; } if ("char".equals(name)) { return char.class; } if ("double".equals(name)) { return double.class; } if ("float".equals(name)) { return float.class; } if ("int".equals(name)) { return int.class; } if ("long".equals(name)) { return long.class; } if ("short".equals(name)) { return short.class; } } if (cl == null) { cl = ClassUtils.getClassLoader(); } return Class.forName(name, true, cl); } /** * desc to class. * "[Z" => boolean[].class * "[[Ljava/util/Map;" => java.util.Map[][].class * * @param desc desc. * @return Class instance. * @throws ClassNotFoundException */ public static Class<?> desc2class(String desc) throws ClassNotFoundException { return desc2class(ClassUtils.getClassLoader(), desc); } /** * desc to class. * "[Z" => boolean[].class * "[[Ljava/util/Map;" => java.util.Map[][].class * * @param cl ClassLoader instance. * @param desc desc. * @return Class instance. * @throws ClassNotFoundException */ private static Class<?> desc2class(ClassLoader cl, String desc) throws ClassNotFoundException { switch (desc.charAt(0)) { case JVM_VOID: return void.class; case JVM_BOOLEAN: return boolean.class; case JVM_BYTE: return byte.class; case JVM_CHAR: return char.class; case JVM_DOUBLE: return double.class; case JVM_FLOAT: return float.class; case JVM_INT: return int.class; case JVM_LONG: return long.class; case JVM_SHORT: return short.class; case 'L': // "Ljava/lang/Object;" ==> "java.lang.Object" desc = desc.substring(1, desc.length() - 1).replace('/', '.'); break; case '[': // "[[Ljava/lang/Object;" ==> "[[Ljava.lang.Object;" desc = desc.replace('/', '.'); break; default: throw new ClassNotFoundException("Class not found: " + desc); } if (cl == null) { cl = ClassUtils.getClassLoader(); } return Class.forName(desc, true, cl); } /** * get class array instance. * * @param desc desc. * @return Class class array. * @throws ClassNotFoundException */ public static Class<?>[] desc2classArray(String desc) throws ClassNotFoundException { Class<?>[] ret = desc2classArray(ClassUtils.getClassLoader(), desc); return ret; } /** * get class array instance. * * @param cl ClassLoader instance. * @param desc desc. * @return Class[] class array. * @throws ClassNotFoundException */ private static Class<?>[] desc2classArray(ClassLoader cl, String desc) throws ClassNotFoundException { if (desc.length() == 0) { return EMPTY_CLASS_ARRAY; } List<Class<?>> cs = new ArrayList<>(); Matcher m = DESC_PATTERN.matcher(desc); while (m.find()) { cs.add(desc2class(cl, m.group())); } return cs.toArray(EMPTY_CLASS_ARRAY); } /** * Find method from method signature * * @param clazz Target class to find method * @param methodName Method signature, e.g.: method1(int, String). It is allowed to provide method name only, e.g.: method2 * @return target method * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws IllegalStateException when multiple methods are found (overridden method when parameter info is not provided) * @deprecated Recommend {@link MethodUtils#findMethod(Class, String, Class[])} */ @Deprecated public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = clazz.getName() + "." + methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature += StringUtils.join(parameterTypes); } Method method; if (parameterTypes == null) { List<Method> finded = new ArrayList<>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format( "Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } return method; } /** * @param clazz Target class to find method * @param methodName Method signature, e.g.: method1(int, String). It is allowed to provide method name only, e.g.: method2 * @return target method * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws IllegalStateException when multiple methods are found (overridden method when parameter info is not provided) * @deprecated Recommend {@link MethodUtils#findMethod(Class, String, Class[])} */ @Deprecated public static Method findMethodByMethodName(Class<?> clazz, String methodName) throws NoSuchMethodException, ClassNotFoundException { return findMethodByMethodSignature(clazz, methodName, null); } public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException { Constructor<?> targetConstructor; try { targetConstructor = clazz.getConstructor(new Class<?>[] {paramType}); } catch (NoSuchMethodException e) { targetConstructor = null; Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) { targetConstructor = constructor; break; } } if (targetConstructor == null) { throw e; } } return targetConstructor; } /** * Check if one object is the implementation for a given interface. * <p> * This method will not trigger classloading for the given interface, therefore it will not lead to error when * the given interface is not visible by the classloader * * @param obj Object to examine * @param interfaceClazzName The given interface * @return true if the object implements the given interface, otherwise return false */ public static boolean isInstance(Object obj, String interfaceClazzName) { for (Class<?> clazz = obj.getClass(); clazz != null && !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> itf : interfaces) { if (itf.getName().equals(interfaceClazzName)) { return true; } } } return false; } public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<>(), 0); } private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) { if (level > 2) { return null; } if (returnType == null) { return null; } if (returnType == boolean.class || returnType == Boolean.class) { return false; } if (returnType == char.class || returnType == Character.class) { return '\0'; } if (returnType == byte.class || returnType == Byte.class) { return (byte) 0; } if (returnType == short.class || returnType == Short.class) { return (short) 0; } if (returnType == int.class || returnType == Integer.class) { return 0; } if (returnType == long.class || returnType == Long.class) { return 0L; } if (returnType == float.class || returnType == Float.class) { return 0F; } if (returnType == double.class || returnType == Double.class) { return 0D; } if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); } if (returnType.isAssignableFrom(ArrayList.class)) { return new ArrayList<>(0); } if (returnType.isAssignableFrom(HashSet.class)) { return new HashSet<>(0); } if (returnType.isAssignableFrom(HashMap.class)) { return new HashMap<>(0); } if (String.class.equals(returnType)) { return ""; } if (returnType.isInterface()) { return null; } try { Object value = emptyInstances.get(returnType); if (value == null) { value = returnType.getDeclaredConstructor().newInstance(); emptyInstances.put(returnType, value); } Class<?> cls = value.getClass(); while (cls != null && cls != Object.class) { Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { if (field.isSynthetic()) { continue; } Object property = getEmptyObject(field.getType(), emptyInstances, level + 1); if (property != null) { try { if (!field.isAccessible()) { field.setAccessible(true); } field.set(value, property); } catch (Throwable ignored) { } } } cls = cls.getSuperclass(); } return value; } catch (Throwable e) { return null; } } public static Object defaultReturn(Method m) { if (m.getReturnType().isPrimitive()) { return primitiveDefaults.get(m.getReturnType()); } else { return null; } } public static Object defaultReturn(Class<?> classType) { if (classType != null && classType.isPrimitive()) { return primitiveDefaults.get(classType); } else { return null; } } public static boolean isBeanPropertyReadMethod(Method method) { return method != null && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getReturnType() != void.class && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 0 && ((method.getName().startsWith("get") && method.getName().length() > 3) || (method.getName().startsWith("is") && method.getName().length() > 2)); } public static String getPropertyNameFromBeanReadMethod(Method method) { if (isBeanPropertyReadMethod(method)) { if (method.getName().startsWith("get")) { return method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); } if (method.getName().startsWith("is")) { return method.getName().substring(2, 3).toLowerCase() + method.getName().substring(3); } } return null; } public static boolean isBeanPropertyWriteMethod(Method method) { return method != null && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 1 && method.getName().startsWith("set") && method.getName().length() > 3; } public static String getPropertyNameFromBeanWriteMethod(Method method) { if (isBeanPropertyWriteMethod(method)) { return method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); } return null; } public static boolean isPublicInstanceField(Field field) { return Modifier.isPublic(field.getModifiers()) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()) && !field.isSynthetic(); } public static Map<String, Field> getBeanPropertyFields(Class cl) { Map<String, Field> properties = new HashMap<>(); for (; cl != null; cl = cl.getSuperclass()) { Field[] fields = cl.getDeclaredFields(); for (Field field : fields) { if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { continue; } field.setAccessible(true); properties.put(field.getName(), field); } } return properties; } public static Map<String, Method> getBeanPropertyReadMethods(Class cl) { Map<String, Method> properties = new HashMap<>(); for (; cl != null; cl = cl.getSuperclass()) { Method[] methods = cl.getDeclaredMethods(); for (Method method : methods) { if (isBeanPropertyReadMethod(method)) { method.setAccessible(true); String property = getPropertyNameFromBeanReadMethod(method); properties.put(property, method); } } } return properties; } public static Type[] getReturnTypes(Method method) { Class<?> returnType = method.getReturnType(); Type genericReturnType = method.getGenericReturnType(); if (Future.class.isAssignableFrom(returnType)) { if (genericReturnType instanceof ParameterizedType) { Type actualArgType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualArgType instanceof ParameterizedType) { returnType = (Class<?>) ((ParameterizedType) actualArgType).getRawType(); genericReturnType = actualArgType; } else if (actualArgType instanceof TypeVariable) { returnType = (Class<?>) ((TypeVariable<?>) actualArgType).getBounds()[0]; genericReturnType = actualArgType; } else { returnType = (Class<?>) actualArgType; genericReturnType = returnType; } } else { returnType = null; genericReturnType = null; } } return new Type[] {returnType, genericReturnType}; } /** * Find the {@link Set} of {@link ParameterizedType} * * @param sourceClass the source {@link Class class} * @return non-null read-only {@link Set} * @since 2.7.5 */ public static Set<ParameterizedType> findParameterizedTypes(Class<?> sourceClass) { // Add Generic Interfaces List<Type> genericTypes = new LinkedList<>(asList(sourceClass.getGenericInterfaces())); // Add Generic Super Class genericTypes.add(sourceClass.getGenericSuperclass()); Set<ParameterizedType> parameterizedTypes = genericTypes.stream() .filter(type -> type instanceof ParameterizedType) // filter ParameterizedType .map(ParameterizedType.class::cast) // cast to ParameterizedType .collect(Collectors.toSet()); if (parameterizedTypes.isEmpty()) { // If not found, try to search super types recursively genericTypes.stream() .filter(type -> type instanceof Class) .map(Class.class::cast) .forEach(superClass -> parameterizedTypes.addAll(findParameterizedTypes(superClass))); } return unmodifiableSet(parameterizedTypes); // build as a Set } /** * Find the hierarchical types from the source {@link Class class} by specified {@link Class type}. * * @param sourceClass the source {@link Class class} * @param matchType the type to match * @param <T> the type to match * @return non-null read-only {@link Set} * @since 2.7.5 */ public static <T> Set<Class<T>> findHierarchicalTypes(Class<?> sourceClass, Class<T> matchType) { if (sourceClass == null) { return Collections.emptySet(); } Set<Class<T>> hierarchicalTypes = new LinkedHashSet<>(); if (matchType.isAssignableFrom(sourceClass)) { hierarchicalTypes.add((Class<T>) sourceClass); } // Find all super classes hierarchicalTypes.addAll(findHierarchicalTypes(sourceClass.getSuperclass(), matchType)); return unmodifiableSet(hierarchicalTypes); } /** * Get the value from the specified bean and its getter method. * * @param bean the bean instance * @param methodName the name of getter * @param <T> the type of property value * @return * @since 2.7.5 */ public static <T> T getProperty(Object bean, String methodName) { Class<?> beanClass = bean.getClass(); BeanInfo beanInfo = null; T propertyValue = null; try { beanInfo = Introspector.getBeanInfo(beanClass); propertyValue = (T) Stream.of(beanInfo.getMethodDescriptors()) .filter(methodDescriptor -> methodName.equals(methodDescriptor.getName())) .findFirst() .map(method -> { try { return method.getMethod().invoke(bean); } catch (Exception e) { // ignore } return null; }) .get(); } catch (Exception e) { } return propertyValue; } /** * Check target bean class whether has specify method * @param beanClass * @param methodName * @return */ public static boolean hasMethod(Class<?> beanClass, String methodName) { try { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); Optional<MethodDescriptor> descriptor = Stream.of(beanInfo.getMethodDescriptors()) .filter(methodDescriptor -> methodName.equals(methodDescriptor.getName())) .findFirst(); return descriptor.isPresent(); } catch (Exception e) { } return false; } /** * Resolve the types of the specified values * * @param values the values * @return If can't be resolved, return {@link ReflectUtils#EMPTY_CLASS_ARRAY empty class array} * @since 2.7.6 */ public static Class[] resolveTypes(Object... values) { if (isEmpty(values)) { return EMPTY_CLASS_ARRAY; } int size = values.length; Class[] types = new Class[size]; for (int i = 0; i < size; i++) { Object value = values[i]; types[i] = value == null ? null : value.getClass(); } return types; } public static boolean checkZeroArgConstructor(Class clazz) { try { clazz.getDeclaredConstructor(); return true; } catch (NoSuchMethodException e) { return false; } } public static boolean isJdk(Class clazz) { return clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax."); } /** * Copy from org.springframework.util.ReflectionUtils. * Make the given method accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active). * @param method the method to make accessible * @see java.lang.reflect.Method#setAccessible */ @SuppressWarnings("deprecation") // on JDK 9 public static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { method.setAccessible(true); } } /** * Get all field names of target type * @param type * @return */ public static Set<String> getAllFieldNames(Class<?> type) { Set<String> fieldNames = new HashSet<>(); for (Field field : type.getDeclaredFields()) { fieldNames.add(field.getName()); } Set<Class<?>> allSuperClasses = ClassUtils.getAllSuperClasses(type); for (Class<?> aClass : allSuperClasses) { for (Field field : aClass.getDeclaredFields()) { fieldNames.add(field.getName()); } } return fieldNames; } public static <T> T getFieldValue(Object obj, String fieldName) throws RuntimeException { if (obj == null) { throw new IllegalArgumentException("object is null"); } try { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return (T) field.get(obj); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } }
6,893
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java
/* * 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 java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.function.Predicates.and; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterFirst; import static org.apache.dubbo.common.utils.ClassUtils.getAllInheritedTypes; import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; import static org.apache.dubbo.common.utils.CollectionUtils.first; import static org.apache.dubbo.common.utils.MethodUtils.findMethod; import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod; /** * Commons Annotation Utilities class * * @since 2.7.6 */ public interface AnnotationUtils { /** * Resolve the annotation type by the annotated element and resolved class name * * @param annotatedElement the annotated element * @param annotationClassName the class name of annotation * @param <A> the type of annotation * @return If resolved, return the type of annotation, or <code>null</code> */ @SuppressWarnings("unchecked") static <A extends Annotation> Class<A> resolveAnnotationType( AnnotatedElement annotatedElement, String annotationClassName) { ClassLoader classLoader = annotatedElement.getClass().getClassLoader(); Class<?> annotationType = resolveClass(annotationClassName, classLoader); if (annotationType == null || !Annotation.class.isAssignableFrom(annotationType)) { return null; } return (Class<A>) annotationType; } /** * Is the specified type a generic {@link Class type} * * @param annotatedElement the annotated element * @return if <code>annotatedElement</code> is the {@link Class}, return <code>true</code>, or <code>false</code> * @see ElementType#TYPE */ static boolean isType(AnnotatedElement annotatedElement) { return annotatedElement instanceof Class; } /** * Is the type of specified annotation same to the expected type? * * @param annotation the specified {@link Annotation} * @param annotationType the expected annotation type * @return if same, return <code>true</code>, or <code>false</code> */ static boolean isSameType(Annotation annotation, Class<? extends Annotation> annotationType) { if (annotation == null || annotationType == null) { return false; } return Objects.equals(annotation.annotationType(), annotationType); } /** * Build an instance of {@link Predicate} to excluded annotation type * * @param excludedAnnotationType excluded annotation type * @return non-null */ static Predicate<Annotation> excludedType(Class<? extends Annotation> excludedAnnotationType) { return annotation -> !isSameType(annotation, excludedAnnotationType); } /** * Get the attribute from the specified {@link Annotation annotation} * * @param annotation the specified {@link Annotation annotation} * @param attributeName the attribute name * @param <T> the type of attribute * @return the attribute value * @throws IllegalArgumentException If the attribute name can't be found */ static <T> T getAttribute(Annotation annotation, String attributeName) throws IllegalArgumentException { return annotation == null ? null : invokeMethod(annotation, attributeName); } /** * Get the "value" attribute from the specified {@link Annotation annotation} * * @param annotation the specified {@link Annotation annotation} * @param <T> the type of attribute * @return the value of "value" attribute * @throws IllegalArgumentException If the attribute name can't be found */ static <T> T getValue(Annotation annotation) throws IllegalArgumentException { return getAttribute(annotation, "value"); } /** * Get the {@link Annotation} from the specified {@link AnnotatedElement the annotated element} and * {@link Annotation annotation} class name * * @param annotatedElement {@link AnnotatedElement} * @param annotationClassName the class name of annotation * @param <A> The type of {@link Annotation} * @return the {@link Annotation} if found * @throws ClassCastException If the {@link Annotation annotation} type that client requires can't match actual type */ static <A extends Annotation> A getAnnotation(AnnotatedElement annotatedElement, String annotationClassName) throws ClassCastException { Class<? extends Annotation> annotationType = resolveAnnotationType(annotatedElement, annotationClassName); if (annotationType == null) { return null; } return (A) annotatedElement.getAnnotation(annotationType); } /** * Get annotations that are <em>directly present</em> on this element. * This method ignores inherited annotations. * * @param annotatedElement the annotated element * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ static List<Annotation> getDeclaredAnnotations( AnnotatedElement annotatedElement, Predicate<Annotation>... annotationsToFilter) { if (annotatedElement == null) { return emptyList(); } return unmodifiableList(filterAll(asList(annotatedElement.getDeclaredAnnotations()), annotationsToFilter)); } /** * Get all directly declared annotations of the the annotated element, not including * meta annotations. * * @param annotatedElement the annotated element * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ static List<Annotation> getAllDeclaredAnnotations( AnnotatedElement annotatedElement, Predicate<Annotation>... annotationsToFilter) { if (isType(annotatedElement)) { return getAllDeclaredAnnotations((Class) annotatedElement, annotationsToFilter); } else { return getDeclaredAnnotations(annotatedElement, annotationsToFilter); } } /** * Get all directly declared annotations of the specified type and its' all hierarchical types, not including * meta annotations. * * @param type the specified type * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") static List<Annotation> getAllDeclaredAnnotations(Class<?> type, Predicate<Annotation>... annotationsToFilter) { if (type == null) { return emptyList(); } List<Annotation> allAnnotations = new LinkedList<>(); // All types Set<Class<?>> allTypes = new LinkedHashSet<>(); // Add current type allTypes.add(type); // Add all inherited types allTypes.addAll(getAllInheritedTypes(type, t -> !Object.class.equals(t))); for (Class<?> t : allTypes) { allAnnotations.addAll(getDeclaredAnnotations(t, annotationsToFilter)); } return unmodifiableList(allAnnotations); } /** * Get the meta-annotated {@link Annotation annotations} directly, excluding {@link Target}, {@link Retention} * and {@link Documented} * * @param annotationType the {@link Annotation annotation} type * @param metaAnnotationsToFilter the meta annotations to filter * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") static List<Annotation> getMetaAnnotations( Class<? extends Annotation> annotationType, Predicate<Annotation>... metaAnnotationsToFilter) { return getDeclaredAnnotations( annotationType, // Excludes the Java native annotation types or it causes the stack overflow, e.g, // @Target annotates itself excludedType(Target.class), excludedType(Retention.class), excludedType(Documented.class), // Add other predicates and(metaAnnotationsToFilter)); } /** * Get all meta annotations from the specified {@link Annotation annotation} type * * @param annotationType the {@link Annotation annotation} type * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") static List<Annotation> getAllMetaAnnotations( Class<? extends Annotation> annotationType, Predicate<Annotation>... annotationsToFilter) { List<Annotation> allMetaAnnotations = new LinkedList<>(); List<Annotation> metaAnnotations = getMetaAnnotations(annotationType); allMetaAnnotations.addAll(metaAnnotations); for (Annotation metaAnnotation : metaAnnotations) { // Get the nested meta annotations recursively allMetaAnnotations.addAll(getAllMetaAnnotations(metaAnnotation.annotationType())); } return unmodifiableList(filterAll(allMetaAnnotations, annotationsToFilter)); } /** * Find the annotation that is annotated on the specified element may be a meta-annotation * * @param annotatedElement the annotated element * @param annotationClassName the class name of annotation * @param <A> the required type of annotation * @return If found, return first matched-type {@link Annotation annotation}, or <code>null</code> */ static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, String annotationClassName) { return findAnnotation(annotatedElement, resolveAnnotationType(annotatedElement, annotationClassName)); } /** * Find the annotation that is annotated on the specified element may be a meta-annotation * * @param annotatedElement the annotated element * @param annotationType the type of annotation * @param <A> the required type of annotation * @return If found, return first matched-type {@link Annotation annotation}, or <code>null</code> */ @SuppressWarnings("unchecked") static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) { return (A) filterFirst(getAllDeclaredAnnotations(annotatedElement), a -> isSameType(a, annotationType)); } /** * Find the meta annotations from the the {@link Annotation annotation} type by meta annotation type * * @param annotationType the {@link Annotation annotation} type * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return if found, return all matched results, or get an {@link Collections#emptyList() empty list} */ @SuppressWarnings("unchecked") static <A extends Annotation> List<A> findMetaAnnotations( Class<? extends Annotation> annotationType, Class<A> metaAnnotationType) { return (List<A>) getAllMetaAnnotations(annotationType, a -> isSameType(a, metaAnnotationType)); } /** * Find the meta annotations from the the the annotated element by meta annotation type * * @param annotatedElement the annotated element * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return if found, return all matched results, or get an {@link Collections#emptyList() empty list} */ @SuppressWarnings("unchecked") static <A extends Annotation> List<A> findMetaAnnotations( AnnotatedElement annotatedElement, Class<A> metaAnnotationType) { List<A> metaAnnotations = new LinkedList<>(); for (Annotation annotation : getAllDeclaredAnnotations(annotatedElement)) { metaAnnotations.addAll(findMetaAnnotations(annotation.annotationType(), metaAnnotationType)); } return unmodifiableList(metaAnnotations); } /** * Find the meta annotation from the annotated element by meta annotation type * * @param annotatedElement the annotated element * @param metaAnnotationClassName the class name of meta annotation * @param <A> the type of required annotation * @return {@link #findMetaAnnotation(Class, Class)} */ static <A extends Annotation> A findMetaAnnotation( AnnotatedElement annotatedElement, String metaAnnotationClassName) { return findMetaAnnotation(annotatedElement, resolveAnnotationType(annotatedElement, metaAnnotationClassName)); } /** * Find the meta annotation from the annotation type by meta annotation type * * @param annotationType the {@link Annotation annotation} type * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return If found, return the {@link CollectionUtils#first(Collection)} matched result, return <code>null</code>. * If it requires more result, please consider to use {@link #findMetaAnnotations(Class, Class)} * @see #findMetaAnnotations(Class, Class) */ static <A extends Annotation> A findMetaAnnotation( Class<? extends Annotation> annotationType, Class<A> metaAnnotationType) { return first(findMetaAnnotations(annotationType, metaAnnotationType)); } /** * Find the meta annotation from the annotated element by meta annotation type * * @param annotatedElement the annotated element * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return If found, return the {@link CollectionUtils#first(Collection)} matched result, return <code>null</code>. * If it requires more result, please consider to use {@link #findMetaAnnotations(AnnotatedElement, Class)} * @see #findMetaAnnotations(AnnotatedElement, Class) */ static <A extends Annotation> A findMetaAnnotation(AnnotatedElement annotatedElement, Class<A> metaAnnotationType) { return first(findMetaAnnotations(annotatedElement, metaAnnotationType)); } /** * Tests the annotated element is annotated the specified annotations or not * * @param type the annotated type * @param matchAll If <code>true</code>, checking all annotation types are present or not, or match any * @param annotationTypes the specified annotation types * @return If the specified annotation types are present, return <code>true</code>, or <code>false</code> */ static boolean isAnnotationPresent( Class<?> type, boolean matchAll, Class<? extends Annotation>... annotationTypes) { int size = annotationTypes == null ? 0 : annotationTypes.length; if (size < 1) { return false; } int presentCount = 0; for (int i = 0; i < size; i++) { Class<? extends Annotation> annotationType = annotationTypes[i]; if (findAnnotation(type, annotationType) != null || findMetaAnnotation(type, annotationType) != null) { presentCount++; } } return matchAll ? presentCount == size : presentCount > 0; } /** * Tests the annotated element is annotated the specified annotation or not * * @param type the annotated type * @param annotationType the class of annotation * @return If the specified annotation type is present, return <code>true</code>, or <code>false</code> */ @SuppressWarnings("unchecked") static boolean isAnnotationPresent(Class<?> type, Class<? extends Annotation> annotationType) { return isAnnotationPresent(type, true, annotationType); } /** * Tests the annotated element is present any specified annotation types * * @param annotatedElement the annotated element * @param annotationClassName the class name of annotation * @return If any specified annotation types are present, return <code>true</code> */ @SuppressWarnings("unchecked") static boolean isAnnotationPresent(AnnotatedElement annotatedElement, String annotationClassName) { ClassLoader classLoader = annotatedElement.getClass().getClassLoader(); Class<?> resolvedType = resolveClass(annotationClassName, classLoader); if (resolvedType == null || !Annotation.class.isAssignableFrom(resolvedType)) { return false; } return isAnnotationPresent(annotatedElement, (Class<? extends Annotation>) resolvedType); } /** * Tests the annotated element is present any specified annotation types * * @param annotatedElement the annotated element * @param annotationType the class of annotation * @return If any specified annotation types are present, return <code>true</code> */ static boolean isAnnotationPresent(AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType) { if (isType(annotatedElement)) { return isAnnotationPresent((Class) annotatedElement, annotationType); } else { return annotatedElement.isAnnotationPresent(annotationType) || findMetaAnnotation(annotatedElement, annotationType) != null; // to find meta-annotation } } /** * Tests the annotated element is annotated all specified annotations or not * * @param type the annotated type * @param annotationTypes the specified annotation types * @return If the specified annotation types are present, return <code>true</code>, or <code>false</code> */ static boolean isAllAnnotationPresent(Class<?> type, Class<? extends Annotation>... annotationTypes) { return isAnnotationPresent(type, true, annotationTypes); } /** * Tests the annotated element is present any specified annotation types * * @param type the annotated type * @param annotationTypes the specified annotation types * @return If any specified annotation types are present, return <code>true</code> */ static boolean isAnyAnnotationPresent(Class<?> type, Class<? extends Annotation>... annotationTypes) { return isAnnotationPresent(type, false, annotationTypes); } /** * Get the default value of attribute on the specified annotation * * @param annotation {@link Annotation} object * @param attributeName the name of attribute * @param <T> the type of value * @return <code>null</code> if not found * @since 2.7.9 */ static <T> T getDefaultValue(Annotation annotation, String attributeName) { return getDefaultValue(annotation.annotationType(), attributeName); } /** * Get the default value of attribute on the specified annotation * * @param annotationType the type of {@link Annotation} * @param attributeName the name of attribute * @param <T> the type of value * @return <code>null</code> if not found * @since 2.7.9 */ @SuppressWarnings("unchecked") static <T> T getDefaultValue(Class<? extends Annotation> annotationType, String attributeName) { Method method = findMethod(annotationType, attributeName); return (T) (method == null ? null : method.getDefaultValue()); } /** * Filter default value of Annotation type * @param annotationType annotation type from {@link Annotation#annotationType()} * @param attributes * @return */ static Map<String, Object> filterDefaultValues( Class<? extends Annotation> annotationType, Map<String, Object> attributes) { Map<String, Object> filteredAttributes = new LinkedHashMap<>(attributes.size()); attributes.forEach((key, val) -> { if (!Objects.deepEquals(val, getDefaultValue(annotationType, key))) { filteredAttributes.put(key, val); } }); // remove void class, compatible with spring 3.x Object interfaceClassValue = filteredAttributes.get("interfaceClass"); if (interfaceClassValue instanceof String && StringUtils.isEquals((String) interfaceClassValue, "void")) { filteredAttributes.remove("interfaceClass"); } return filteredAttributes; } /** * Filter default value of Annotation type * @param annotation * @param attributes * @return */ static Map<String, Object> filterDefaultValues(Annotation annotation, Map<String, Object> attributes) { return filterDefaultValues(annotation.annotationType(), attributes); } /** * Get attributes of annotation * @param annotation * @return */ static Map<String, Object> getAttributes(Annotation annotation, boolean filterDefaultValue) { Class<?> annotationType = annotation.annotationType(); Method[] methods = annotationType.getMethods(); Map<String, Object> attributes = new LinkedHashMap<>(methods.length); for (Method method : methods) { try { if (method.getDeclaringClass() == Annotation.class) { continue; } String name = method.getName(); Object value = method.invoke(annotation); if (!filterDefaultValue || !Objects.deepEquals(value, method.getDefaultValue())) { attributes.put(name, value); } } catch (Exception e) { throw new IllegalStateException("get attribute value of annotation failed: " + method, e); } } return attributes; } }
6,894
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.java
/* * 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.constants.CommonConstants; import java.util.Comparator; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Regex matching of keys is supported. */ public class RegexProperties extends Properties { @Override public String getProperty(String key) { String value = super.getProperty(key); if (value != null) { return value; } // Sort the keys to solve the problem of matching priority. List<String> sortedKeyList = keySet().stream() .map(k -> (String) k) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); String keyPattern = sortedKeyList.stream() .filter(k -> { String matchingKey = k; if (matchingKey.startsWith(CommonConstants.ANY_VALUE)) { matchingKey = CommonConstants.HIDE_KEY_PREFIX + matchingKey; } return Pattern.matches(matchingKey, key); }) .findFirst() .orElse(null); return keyPattern == null ? null : super.getProperty(keyPattern); } }
6,895
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.java
/* * 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 java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * A utility class that provides methods for accessing and manipulating private fields and methods of an object. * This is useful for white-box testing, where the internal workings of a class need to be tested directly. * <p> * Note: Usage of this class should be limited to testing purposes only, as it violates the encapsulation principle. */ public class ReflectionUtils { private ReflectionUtils() {} /** * Retrieves the value of the specified field from the given object. * * @param source The object from which to retrieve the field value. * @param fieldName The name of the field to retrieve. * @return The value of the specified field in the given object. * @throws RuntimeException If the specified field does not exist. */ public static Object getField(Object source, String fieldName) { try { Field f = source.getClass().getDeclaredField(fieldName); f.setAccessible(true); return f.get(source); } catch (Exception e) { throw new ReflectionException(e); } } /** * Invokes the specified method on the given object with the provided parameters. * * @param source The object on which to invoke the method. * @param methodName The name of the method to invoke. * @param params The parameters to pass to the method. * @return The result of invoking the specified method on the given object. */ public static Object invoke(Object source, String methodName, Object... params) { try { Class<?>[] classes = Arrays.stream(params) .map(param -> param != null ? param.getClass() : null) .toArray(Class<?>[]::new); for (Method method : source.getClass().getDeclaredMethods()) { if (method.getName().equals(methodName) && matchParameters(method.getParameterTypes(), classes)) { method.setAccessible(true); return method.invoke(source, params); } } throw new NoSuchMethodException("No method found with the specified name and parameter types"); } catch (Exception e) { throw new ReflectionException(e); } } private static boolean matchParameters(Class<?>[] methodParamTypes, Class<?>[] givenParamTypes) { if (methodParamTypes.length != givenParamTypes.length) { return false; } for (int i = 0; i < methodParamTypes.length; i++) { if (givenParamTypes[i] == null) { if (methodParamTypes[i].isPrimitive()) { return false; } } else if (!methodParamTypes[i].isAssignableFrom(givenParamTypes[i])) { return false; } } return true; } /** * Returns a list of distinct {@link Class} objects representing the generics of the given class that implement the * given interface. * * @param clazz the class to retrieve the generics for * @param interfaceClass the interface to retrieve the generics for * @return a list of distinct {@link Class} objects representing the generics of the given class that implement the * given interface */ public static List<Class<?>> getClassGenerics(Class<?> clazz, Class<?> interfaceClass) { List<Class<?>> generics = new ArrayList<>(); Type[] genericInterfaces = clazz.getGenericInterfaces(); for (Type genericInterface : genericInterfaces) { if (genericInterface instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericInterface; Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class && interfaceClass.isAssignableFrom((Class<?>) rawType)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { if (actualTypeArgument instanceof Class) { generics.add((Class<?>) actualTypeArgument); } } } } } Type genericSuperclass = clazz.getGenericSuperclass(); if (genericSuperclass instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { if (actualTypeArgument instanceof Class) { generics.add((Class<?>) actualTypeArgument); } } } Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { generics.addAll(getClassGenerics(superclass, interfaceClass)); } return generics.stream().distinct().collect(Collectors.toList()); } public static class ReflectionException extends RuntimeException { public ReflectionException(Throwable cause) { super(cause); } } public static boolean match(Class<?> clazz, Class<?> interfaceClass, Object event) { List<Class<?>> eventTypes = ReflectionUtils.getClassGenerics(clazz, interfaceClass); return eventTypes.stream().allMatch(eventType -> eventType.isInstance(event)); } }
6,896
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.java
/* * 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 java.util.Objects; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; /** * ConcurrentHashMap util */ public class ConcurrentHashMapUtils { /** * A temporary workaround for Java 8 ConcurrentHashMap#computeIfAbsent specific performance issue: JDK-8161372.</br> * @see <a href="https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a> * */ public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K key, Function<? super K, ? extends V> func) { Objects.requireNonNull(func); if (JRE.JAVA_8.isCurrentVersion()) { V v = map.get(key); if (null == v) { // issue#11986 lock bug // v = map.computeIfAbsent(key, func); // this bug fix methods maybe cause `func.apply` multiple calls. v = func.apply(key); if (null == v) { return null; } final V res = map.putIfAbsent(key, v); if (null != res) { // if pre value present, means other thread put value already, and putIfAbsent not effect // return exist value return res; } // if pre value is null, means putIfAbsent effected, return current value } return v; } else { return map.computeIfAbsent(key, func); } } }
6,897
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java
/* * 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.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; public class ExecutorUtil { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExecutorUtil.class); private static final ThreadPoolExecutor SHUTDOWN_EXECUTOR = new ThreadPoolExecutor( 0, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100), new NamedThreadFactory("Close-ExecutorService-Timer", true)); public static boolean isTerminated(Executor executor) { if (!(executor instanceof ExecutorService)) { return false; } return ((ExecutorService) executor).isTerminated(); } public static boolean isShutdown(Executor executor) { if (!(executor instanceof ExecutorService)) { return false; } return ((ExecutorService) executor).isShutdown(); } /** * Use the shutdown pattern from: * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html * * @param executor the Executor to shutdown * @param timeout the timeout in milliseconds before termination */ public static void gracefulShutdown(Executor executor, int timeout) { if (!(executor instanceof ExecutorService) || isTerminated(executor)) { return; } final ExecutorService es = (ExecutorService) executor; try { // Disable new tasks from being submitted es.shutdown(); } catch (SecurityException | NullPointerException ex2) { return; } try { // Wait a while for existing tasks to terminate if (!es.awaitTermination(timeout, TimeUnit.MILLISECONDS)) { es.shutdownNow(); } } catch (InterruptedException ex) { es.shutdownNow(); Thread.currentThread().interrupt(); } if (!isTerminated(es)) { newThreadToCloseExecutor(es); } } public static void shutdownNow(Executor executor, final int timeout) { if (!(executor instanceof ExecutorService) || isTerminated(executor)) { return; } final ExecutorService es = (ExecutorService) executor; try { es.shutdownNow(); } catch (SecurityException | NullPointerException ex2) { return; } try { es.awaitTermination(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (!isTerminated(es)) { newThreadToCloseExecutor(es); } } private static void newThreadToCloseExecutor(final ExecutorService es) { if (!isTerminated(es)) { SHUTDOWN_EXECUTOR.execute(() -> { try { for (int i = 0; i < 1000; i++) { es.shutdownNow(); if (es.awaitTermination(10, TimeUnit.MILLISECONDS)) { break; } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (Throwable e) { logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", e.getMessage(), e); } }); } } /** * append thread name with url address * * @return new url with updated thread name */ public static URL setThreadName(URL url, String defaultName) { String name = url.getParameter(THREAD_NAME_KEY, defaultName); name = name + "-" + url.getAddress(); url = url.addParameter(THREAD_NAME_KEY, name); return url; } public static void cancelScheduledFuture(ScheduledFuture<?> scheduledFuture) { ScheduledFuture<?> future = scheduledFuture; if (future != null && !future.isCancelled()) { future.cancel(true); } } }
6,898
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java
/* * 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.constants.CommonConstants; import org.apache.dubbo.common.json.JSON; import org.apache.dubbo.common.json.impl.FastJson2Impl; import org.apache.dubbo.common.json.impl.FastJsonImpl; import org.apache.dubbo.common.json.impl.GsonImpl; import org.apache.dubbo.common.json.impl.JacksonImpl; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; import java.util.Map; public class JsonUtils { private static volatile JSON json; protected static JSON getJson() { if (json == null) { synchronized (JsonUtils.class) { if (json == null) { String preferJsonFrameworkName = System.getProperty(CommonConstants.PREFER_JSON_FRAMEWORK_NAME); if (StringUtils.isNotEmpty(preferJsonFrameworkName)) { try { JSON instance = null; switch (preferJsonFrameworkName) { case "fastjson2": instance = new FastJson2Impl(); break; case "fastjson": instance = new FastJsonImpl(); break; case "gson": instance = new GsonImpl(); break; case "jackson": instance = new JacksonImpl(); break; } if (instance != null && instance.isSupport()) { json = instance; } } catch (Throwable ignore) { } } if (json == null) { List<Class<? extends JSON>> jsonClasses = Arrays.asList( FastJson2Impl.class, FastJsonImpl.class, GsonImpl.class, JacksonImpl.class); for (Class<? extends JSON> jsonClass : jsonClasses) { try { JSON instance = jsonClass.getConstructor().newInstance(); if (instance.isSupport()) { json = instance; break; } } catch (Throwable ignore) { } } } if (json == null) { throw new IllegalStateException( "Dubbo unable to find out any json framework (e.g. fastjson2, fastjson, gson, jackson) from jvm env. " + "Please import at least one json framework."); } } } } return json; } /** * @deprecated for uts only */ @Deprecated protected static void setJson(JSON json) { JsonUtils.json = json; } public static <T> T toJavaObject(String json, Type type) { return getJson().toJavaObject(json, type); } public static <T> List<T> toJavaList(String json, Class<T> clazz) { return getJson().toJavaList(json, clazz); } public static String toJson(Object obj) { return getJson().toJson(obj); } public static List<?> getList(Map<String, ?> obj, String key) { return getJson().getList(obj, key); } public static List<Map<String, ?>> getListOfObjects(Map<String, ?> obj, String key) { return getJson().getListOfObjects(obj, key); } public static List<String> getListOfStrings(Map<String, ?> obj, String key) { return getJson().getListOfStrings(obj, key); } public static Map<String, ?> getObject(Map<String, ?> obj, String key) { return getJson().getObject(obj, key); } public static Double getNumberAsDouble(Map<String, ?> obj, String key) { return getJson().getNumberAsDouble(obj, key); } public static Integer getNumberAsInteger(Map<String, ?> obj, String key) { return getJson().getNumberAsInteger(obj, key); } public static Long getNumberAsLong(Map<String, ?> obj, String key) { return getJson().getNumberAsLong(obj, key); } public static String getString(Map<String, ?> obj, String key) { return getJson().getString(obj, key); } public static List<Map<String, ?>> checkObjectList(List<?> rawList) { return getJson().checkObjectList(rawList); } public static List<String> checkStringList(List<?> rawList) { return getJson().checkStringList(rawList); } }
6,899