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
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.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; /** * LRU-2 * </p> * When the data accessed for the first time, add it to history list. If the size of history list reaches max capacity, eliminate the earliest data (first in first out). * When the data already exists in the history list, and be accessed for the second time, then it will be put into cache. * * TODO, consider replacing with ConcurrentHashMap to improve performance under concurrency */ public class LRU2Cache<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; // as history list private final PreCache<K, Boolean> preCache; public LRU2Cache() { this(DEFAULT_MAX_CAPACITY); } public LRU2Cache(int maxCapacity) { super(16, DEFAULT_LOAD_FACTOR, true); this.maxCapacity = maxCapacity; this.preCache = new PreCache<>(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 { if (preCache.containsKey(key)) { // add it to cache preCache.remove(key); return super.put(key, value); } else { // add it to history list preCache.put(key, true); return value; } } finally { lock.unlock(); } } @Override public V remove(Object key) { lock.lock(); try { preCache.remove(key); 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 { preCache.clear(); super.clear(); } finally { lock.unlock(); } } public int getMaxCapacity() { return maxCapacity; } public void setMaxCapacity(int maxCapacity) { preCache.setMaxCapacity(maxCapacity); this.maxCapacity = maxCapacity; } static class PreCache<K, V> extends LinkedHashMap<K, V> { private volatile int maxCapacity; public PreCache() { this(DEFAULT_MAX_CAPACITY); } public PreCache(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; } public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } } }
6,900
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/FieldUtils.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 static org.apache.dubbo.common.utils.ClassUtils.getAllInheritedTypes; /** * The utilities class for Java Reflection {@link Field} * * @since 2.7.6 */ public interface FieldUtils { /** * Like the {@link Class#getDeclaredField(String)} method without throwing any {@link Exception} * * @param declaredClass the declared class * @param fieldName the name of {@link Field} * @return if field can't be found, return <code>null</code> */ static Field getDeclaredField(Class<?> declaredClass, String fieldName) { try { Field[] fields = declaredClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equals(fieldName)) { return fields[i]; } } return null; } catch (Exception exception) { throw new RuntimeException(exception); } } /** * Find the {@link Field} by the name in the specified class and its inherited types * * @param declaredClass the declared class * @param fieldName the name of {@link Field} * @return if can't be found, return <code>null</code> */ static Field findField(Class<?> declaredClass, String fieldName) { Field field = getDeclaredField(declaredClass, fieldName); if (field != null) { return field; } for (Class superType : getAllInheritedTypes(declaredClass)) { field = getDeclaredField(superType, fieldName); if (field != null) { break; } } if (field == null) { throw new IllegalStateException(String.format("cannot find field %s,field is null", fieldName)); } return field; } /** * Find the {@link Field} by the name in the specified class and its inherited types * * @param object the object whose field should be modified * @param fieldName the name of {@link Field} * @return if can't be found, return <code>null</code> */ static Field findField(Object object, String fieldName) { return findField(object.getClass(), fieldName); } /** * Get the value of the specified {@link Field} * * @param object the object whose field should be modified * @param fieldName the name of {@link Field} * @return the value of the specified {@link Field} */ static Object getFieldValue(Object object, String fieldName) { return getFieldValue(object, findField(object, fieldName)); } /** * Get the value of the specified {@link Field} * * @param object the object whose field should be modified * @param field {@link Field} * @return the value of the specified {@link Field} */ static <T> T getFieldValue(Object object, Field field) { boolean accessible = field.isAccessible(); Object value = null; try { if (!accessible) { field.setAccessible(true); } value = field.get(object); } catch (IllegalAccessException ignored) { } finally { field.setAccessible(accessible); } return (T) value; } /** * Set the value for the specified {@link Field} * * @param object the object whose field should be modified * @param fieldName the name of {@link Field} * @param value the value of field to be set * @return the previous value of the specified {@link Field} */ static <T> T setFieldValue(Object object, String fieldName, T value) { return setFieldValue(object, findField(object, fieldName), value); } /** * Set the value for the specified {@link Field} * * @param object the object whose field should be modified * @param field {@link Field} * @param value the value of field to be set * @return the previous value of the specified {@link Field} */ static <T> T setFieldValue(Object object, Field field, T value) { boolean accessible = field.isAccessible(); Object previousValue = null; try { if (!accessible) { field.setAccessible(true); } previousValue = field.get(object); field.set(object, value); } catch (IllegalAccessException ignored) { } finally { field.setAccessible(accessible); } return (T) previousValue; } }
6,901
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/ClassLoaderResourceLoader.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 org.apache.dubbo.common.resource.GlobalResourcesRepository; import java.io.IOException; import java.lang.ref.SoftReference; import java.lang.reflect.Field; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class ClassLoaderResourceLoader { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ClassLoaderResourceLoader.class); private static SoftReference<Map<ClassLoader, Map<String, Set<URL>>>> classLoaderResourcesCache = null; static { // register resources destroy listener GlobalResourcesRepository.registerGlobalDisposable(ClassLoaderResourceLoader::destroy); } public static Map<ClassLoader, Set<URL>> loadResources(String fileName, Collection<ClassLoader> classLoaders) throws InterruptedException { Map<ClassLoader, Set<URL>> resources = new ConcurrentHashMap<>(); CountDownLatch countDownLatch = new CountDownLatch(classLoaders.size()); for (ClassLoader classLoader : classLoaders) { GlobalResourcesRepository.getGlobalExecutorService().submit(() -> { resources.put(classLoader, loadResources(fileName, classLoader)); countDownLatch.countDown(); }); } countDownLatch.await(); return Collections.unmodifiableMap(new LinkedHashMap<>(resources)); } public static Set<URL> loadResources(String fileName, ClassLoader currentClassLoader) { Map<ClassLoader, Map<String, Set<URL>>> classLoaderCache; if (classLoaderResourcesCache == null || (classLoaderCache = classLoaderResourcesCache.get()) == null) { synchronized (ClassLoaderResourceLoader.class) { if (classLoaderResourcesCache == null || (classLoaderCache = classLoaderResourcesCache.get()) == null) { classLoaderCache = new ConcurrentHashMap<>(); classLoaderResourcesCache = new SoftReference<>(classLoaderCache); } } } if (!classLoaderCache.containsKey(currentClassLoader)) { classLoaderCache.putIfAbsent(currentClassLoader, new ConcurrentHashMap<>()); } Map<String, Set<URL>> urlCache = classLoaderCache.get(currentClassLoader); if (!urlCache.containsKey(fileName)) { Set<URL> set = new LinkedHashSet<>(); Enumeration<URL> urls; try { urls = currentClassLoader.getResources(fileName); boolean isNative = NativeUtils.isNative(); if (urls != null) { while (urls.hasMoreElements()) { URL url = urls.nextElement(); if (isNative) { // In native mode, the address of each URL is the same instead of different paths, so it is // necessary to set the ref to make it different setRef(url); } set.add(url); } } } catch (IOException e) { logger.error( COMMON_IO_EXCEPTION, "", "", "Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: " + currentClassLoader, e); } urlCache.put(fileName, set); } return urlCache.get(fileName); } public static void destroy() { synchronized (ClassLoaderResourceLoader.class) { classLoaderResourcesCache = null; } } private static void setRef(URL url) { try { Field field = URL.class.getDeclaredField("ref"); field.setAccessible(true); field.set(url, UUID.randomUUID().toString()); } catch (Throwable ignore) { } } // for test protected static SoftReference<Map<ClassLoader, Map<String, Set<URL>>>> getClassLoaderResourcesCache() { return classLoaderResourcesCache; } }
6,902
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/ClassHelper.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; /** * @see org.apache.dubbo.common.utils.ClassUtils * @deprecated Replace to <code>ClassUtils</code> */ public class ClassHelper { public static Class<?> forNameWithThreadContextClassLoader(String name) throws ClassNotFoundException { return ClassUtils.forName(name, Thread.currentThread().getContextClassLoader()); } public static Class<?> forNameWithCallerClassLoader(String name, Class<?> caller) throws ClassNotFoundException { return ClassUtils.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) { return ClassUtils.getClassLoader(clazz); } /** * 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(ClassHelper.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 { return ClassUtils.forName(name, classLoader); } /** * 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) { return ClassUtils.resolvePrimitiveClassName(name); } public static String toShortString(Object obj) { return ClassUtils.toShortString(obj); } public static String simpleClassName(Class<?> clazz) { return ClassUtils.simpleClassName(clazz); } /** * @see org.apache.dubbo.common.utils.MethodUtils#isSetter(Method) * @deprecated Replace to <code>MethodUtils#isSetter(Method)</code> */ public static boolean isSetter(Method method) { return MethodUtils.isSetter(method); } /** * @see org.apache.dubbo.common.utils.MethodUtils#isGetter(Method) (Method) * @deprecated Replace to <code>MethodUtils#isGetter(Method)</code> */ public static boolean isGetter(Method method) { return MethodUtils.isGetter(method); } public static boolean isPrimitive(Class<?> type) { return ClassUtils.isPrimitive(type); } public static Object convertPrimitive(Class<?> type, String value) { return ClassUtils.convertPrimitive(type, value); } /** * We only check boolean value at this moment. * * @param type * @param value * @return */ public static boolean isTypeMatch(Class<?> type, String value) { return ClassUtils.isTypeMatch(type, value); } }
6,903
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/Stack.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.EmptyStackException; import java.util.List; /** * Stack. */ public class Stack<E> { private int mSize = 0; private final List<E> mElements = new ArrayList<E>(); public Stack() {} /** * push. * * @param ele */ public void push(E ele) { if (mElements.size() > mSize) { mElements.set(mSize, ele); } else { mElements.add(ele); } mSize++; } /** * pop. * * @return the last element. */ public E pop() { if (mSize == 0) { throw new EmptyStackException(); } return mElements.set(--mSize, null); } /** * peek. * * @return the last element. */ public E peek() { if (mSize == 0) { throw new EmptyStackException(); } return mElements.get(mSize - 1); } /** * get. * * @param index index. * @return element. */ public E get(int index) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } return index < 0 ? mElements.get(index + mSize) : mElements.get(index); } /** * set. * * @param index index. * @param value element. * @return old element. */ public E set(int index, E value) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } return mElements.set(index < 0 ? index + mSize : index, value); } /** * remove. * * @param index * @return element */ public E remove(int index) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } E ret = mElements.remove(index < 0 ? index + mSize : index); mSize--; return ret; } /** * get stack size. * * @return size. */ public int size() { return mSize; } /** * is empty. * * @return empty or not. */ public boolean isEmpty() { return mSize == 0; } /** * clear stack. */ public void clear() { mSize = 0; mElements.clear(); } }
6,904
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/Utf8Utils.java
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.apache.dubbo.common.utils; import static java.lang.Character.MIN_HIGH_SURROGATE; import static java.lang.Character.MIN_LOW_SURROGATE; import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; /** * See original <a href= * "https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/Utf8.java" * >Utf8.java</a> */ public final class Utf8Utils { private Utf8Utils() { //empty } public static int decodeUtf8(byte[] srcBytes, int srcIdx, int srcSize, char[] destChars, int destIdx) { // Bitwise OR combines the sign bits so any negative value fails the check. if ((srcIdx | srcSize | srcBytes.length - srcIdx - srcSize) < 0 || (destIdx | destChars.length - destIdx - srcSize) < 0) { String exMsg = String.format("buffer srcBytes.length=%d, srcIdx=%d, srcSize=%d, destChars.length=%d, " + "destIdx=%d", srcBytes.length, srcIdx, srcSize, destChars.length, destIdx); throw new ArrayIndexOutOfBoundsException( exMsg); } int offset = srcIdx; final int limit = offset + srcSize; final int destIdx0 = destIdx; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (offset < limit) { byte b = srcBytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByteSafe(b, destChars, destIdx++); } while (offset < limit) { byte byte1 = srcBytes[offset++]; if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByteSafe(byte1, destChars, destIdx++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (offset < limit) { byte b = srcBytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByteSafe(b, destChars, destIdx++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (offset >= limit) { throw new IllegalArgumentException("invalid UTF-8."); } DecodeUtil.handleTwoBytesSafe(byte1, /* byte2 */ srcBytes[offset++], destChars, destIdx++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (offset >= limit - 1) { throw new IllegalArgumentException("invalid UTF-8."); } DecodeUtil.handleThreeBytesSafe( byte1, /* byte2 */ srcBytes[offset++], /* byte3 */ srcBytes[offset++], destChars, destIdx++); } else { if (offset >= limit - 2) { throw new IllegalArgumentException("invalid UTF-8."); } DecodeUtil.handleFourBytesSafe( byte1, /* byte2 */ srcBytes[offset++], /* byte3 */ srcBytes[offset++], /* byte4 */ srcBytes[offset++], destChars, destIdx); destIdx += 2; } } return destIdx - destIdx0; } private static class DecodeUtil { /** * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ private static boolean isOneByte(byte b) { return b >= 0; } /** * Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */ private static boolean isTwoBytes(byte b) { return b < (byte) 0xE0; } /** * Returns whether this is a three-byte codepoint with the form '110XXXXX'. */ private static boolean isThreeBytes(byte b) { return b < (byte) 0xF0; } private static void handleOneByteSafe(byte byte1, char[] resultArr, int resultPos) { resultArr[resultPos] = (char) byte1; } private static void handleTwoBytesSafe(byte byte1, byte byte2, char[] resultArr, int resultPos) { checkUtf8(byte1, byte2); resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); } private static void checkUtf8(byte byte1, byte byte2) { // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and // overlong 2-byte, '11000001'. if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) { throw new IllegalArgumentException("invalid UTF-8."); } } private static void handleThreeBytesSafe(byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos) { checkUtf8(byte1, byte2, byte3); resultArr[resultPos] = (char) (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); } private static void checkUtf8(byte byte1, byte byte2, byte byte3) { if (isNotTrailingByte(byte2) // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) || isNotTrailingByte(byte3)) { throw new IllegalArgumentException("invalid UTF-8."); } } private static void handleFourBytesSafe(byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) { checkUtf8(byte1, byte2, byte3, byte4); int codepoint = ((byte1 & 0x07) << 18) | (trailingByteValue(byte2) << 12) | (trailingByteValue(byte3) << 6) | trailingByteValue(byte4); resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); } private static void checkUtf8(byte byte1, byte byte2, byte byte3, byte byte4) { if (isNotTrailingByte(byte2) // Check that 1 <= plane <= 16. Tricky optimized form of: // valid 4-byte leading byte? // if (byte1 > (byte) 0xF4 || // overlong? 4 most significant bits must not all be zero // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // codepoint larger than the highest code point (U+10FFFF)? // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 || isNotTrailingByte(byte3) || isNotTrailingByte(byte4)) { throw new IllegalArgumentException("invalid UTF-8."); } } /** * Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ private static boolean isNotTrailingByte(byte b) { return b > (byte) 0xBF; } /** * Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ private static int trailingByteValue(byte b) { return b & 0x3F; } private static char highSurrogate(int codePoint) { return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10)); } private static char lowSurrogate(int codePoint) { return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff)); } } }
6,905
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/DefaultSerializeClassChecker.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 org.apache.dubbo.rpc.model.FrameworkModel; import java.io.Serializable; import java.util.Arrays; import java.util.Set; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNTRUSTED_SERIALIZE_CLASS; /** * Inspired by Fastjson2 * see com.alibaba.fastjson2.filter.ContextAutoTypeBeforeHandler#apply(java.lang.String, java.lang.Class, long) */ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { private static final long MAGIC_HASH_CODE = 0xcbf29ce484222325L; private static final long MAGIC_PRIME = 0x100000001b3L; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultSerializeClassChecker.class); private volatile SerializeCheckStatus checkStatus = AllowClassNotifyListener.DEFAULT_STATUS; private volatile boolean checkSerializable = true; private final SerializeSecurityManager serializeSecurityManager; private volatile long[] allowPrefixes = new long[0]; private volatile long[] disAllowPrefixes = new long[0]; public DefaultSerializeClassChecker(FrameworkModel frameworkModel) { serializeSecurityManager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class); serializeSecurityManager.registerListener(this); } @Override public synchronized void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) { this.allowPrefixes = loadPrefix(allowedList); this.disAllowPrefixes = loadPrefix(disAllowedList); } @Override public synchronized void notifyCheckStatus(SerializeCheckStatus status) { this.checkStatus = status; } @Override public synchronized void notifyCheckSerializable(boolean checkSerializable) { this.checkSerializable = checkSerializable; } private static long[] loadPrefix(Set<String> allowedList) { long[] array = new long[allowedList.size()]; int index = 0; for (String name : allowedList) { if (name == null || name.isEmpty()) { continue; } long hashCode = MAGIC_HASH_CODE; for (int j = 0; j < name.length(); ++j) { char ch = name.charAt(j); if (ch == '$') { ch = '.'; } hashCode ^= ch; hashCode *= MAGIC_PRIME; } array[index++] = hashCode; } if (index != array.length) { array = Arrays.copyOf(array, index); } Arrays.sort(array); return array; } /** * Try load class * * @param className class name * @throws IllegalArgumentException if class is blocked */ public Class<?> loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException { Class<?> aClass = loadClass0(classLoader, className); if (checkSerializable && !aClass.isPrimitive() && !Serializable.class.isAssignableFrom(aClass)) { String msg = "[Serialization Security] Serialized class " + className + " has not implement Serializable interface. " + "Current mode is strict check, will disallow to deserialize it by default. "; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } return aClass; } private Class<?> loadClass0(ClassLoader classLoader, String className) throws ClassNotFoundException { if (checkStatus == SerializeCheckStatus.DISABLE) { return ClassUtils.forName(className, classLoader); } long hash = MAGIC_HASH_CODE; for (int i = 0, typeNameLength = className.length(); i < typeNameLength; ++i) { char ch = className.charAt(i); if (ch == '$') { ch = '.'; } hash ^= ch; hash *= MAGIC_PRIME; if (Arrays.binarySearch(allowPrefixes, hash) >= 0) { return ClassUtils.forName(className, classLoader); } } if (checkStatus == SerializeCheckStatus.STRICT) { String msg = "[Serialization Security] Serialized class " + className + " is not in allow list. " + "Current mode is `STRICT`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } hash = MAGIC_HASH_CODE; for (int i = 0, typeNameLength = className.length(); i < typeNameLength; ++i) { char ch = className.charAt(i); if (ch == '$') { ch = '.'; } hash ^= ch; hash *= MAGIC_PRIME; if (Arrays.binarySearch(disAllowPrefixes, hash) >= 0) { String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + "Current mode is `WARN`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } } hash = MAGIC_HASH_CODE; for (int i = 0, typeNameLength = className.length(); i < typeNameLength; ++i) { char ch = Character.toLowerCase(className.charAt(i)); if (ch == '$') { ch = '.'; } hash ^= ch; hash *= MAGIC_PRIME; if (Arrays.binarySearch(disAllowPrefixes, hash) >= 0) { String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + "Current mode is `WARN`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } } Class<?> clazz = ClassUtils.forName(className, classLoader); if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn( PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", "[Serialization Security] Serialized class " + className + " is not in allow list. " + "Current mode is `WARN`, will allow to deserialize it by default. " + "Dubbo will set to `STRICT` mode by default in the future. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."); } return clazz; } public static DefaultSerializeClassChecker getInstance() { return FrameworkModel.defaultModel().getBeanFactory().getBean(DefaultSerializeClassChecker.class); } public boolean isCheckSerializable() { return checkSerializable; } }
6,906
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/status/Status.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.status; /** * Status */ public class Status { private final Level level; private final String message; private final String description; public Status(Level level) { this(level, null, null); } public Status(Level level, String message) { this(level, message, null); } public Status(Level level, String message, String description) { this.level = level; this.message = message; this.description = description; } public Level getLevel() { return level; } public String getMessage() { return message; } public String getDescription() { return description; } /** * Level */ public enum Level { /** * OK */ OK, /** * WARN */ WARN, /** * ERROR */ ERROR, /** * UNKNOWN */ UNKNOWN } }
6,907
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/status/StatusChecker.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.status; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * StatusChecker */ @SPI(scope = ExtensionScope.APPLICATION) public interface StatusChecker { /** * check status * * @return status */ Status check(); }
6,908
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.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.status.reporter; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.util.HashMap; import java.util.Set; public class FrameworkStatusReportService implements ScopeModelAware { private static final Logger logger = LoggerFactory.getLogger(FrameworkStatusReporter.class); public static final String REGISTRATION_STATUS = "registration"; public static final String ADDRESS_CONSUMPTION_STATUS = "consumption"; public static final String MIGRATION_STEP_STATUS = "migrationStepStatus"; private ApplicationModel applicationModel; private Set<FrameworkStatusReporter> reporters; @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; reporters = applicationModel .getExtensionLoader(FrameworkStatusReporter.class) .getSupportedExtensionInstances(); } public void reportRegistrationStatus(Object obj) { doReport(REGISTRATION_STATUS, obj); } public void reportConsumptionStatus(Object obj) { doReport(ADDRESS_CONSUMPTION_STATUS, obj); } public void reportMigrationStepStatus(Object obj) { doReport(MIGRATION_STEP_STATUS, obj); } public boolean hasReporter() { return reporters.size() > 0; } private void doReport(String type, Object obj) { // TODO, report asynchronously try { if (CollectionUtils.isNotEmpty(reporters)) { for (FrameworkStatusReporter reporter : reporters) { reporter.report(type, obj); } } } catch (Exception e) { logger.info("Report " + type + " status failed because of " + e.getMessage()); } } public String createRegistrationReport(String status) { HashMap<String, String> registration = new HashMap<>(); registration.put("application", applicationModel.getApplicationName()); registration.put("status", status); return JsonUtils.toJson(registration); } public String createConsumptionReport(String interfaceName, String version, String group, String status) { HashMap<String, String> migrationStatus = new HashMap<>(); migrationStatus.put("type", "consumption"); migrationStatus.put("application", applicationModel.getApplicationName()); migrationStatus.put("service", interfaceName); migrationStatus.put("version", version); migrationStatus.put("group", group); migrationStatus.put("status", status); return JsonUtils.toJson(migrationStatus); } public String createMigrationStepReport( String interfaceName, String version, String group, String originStep, String newStep, String success) { HashMap<String, String> migrationStatus = new HashMap<>(); migrationStatus.put("type", "migrationStepStatus"); migrationStatus.put("application", applicationModel.getApplicationName()); migrationStatus.put("service", interfaceName); migrationStatus.put("version", version); migrationStatus.put("group", group); migrationStatus.put("originStep", originStep); migrationStatus.put("newStep", newStep); migrationStatus.put("success", success); return JsonUtils.toJson(migrationStatus); } }
6,909
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.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.status.reporter; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ScopeModelAware; @SPI(scope = ExtensionScope.APPLICATION) public interface FrameworkStatusReporter extends ScopeModelAware { void report(String type, Object obj); }
6,910
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.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.status.support; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; /** * MemoryStatus */ @Activate public class MemoryStatusChecker implements StatusChecker { @Override public Status check() { Runtime runtime = Runtime.getRuntime(); long freeMemory = runtime.freeMemory(); long totalMemory = runtime.totalMemory(); long maxMemory = runtime.maxMemory(); boolean ok = (maxMemory - (totalMemory - freeMemory) > 2 * 1024 * 1024); // Alarm when spare memory < 2M String msg = "max:" + (maxMemory / 1024 / 1024) + "M,total:" + (totalMemory / 1024 / 1024) + "M,used:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M,free:" + (freeMemory / 1024 / 1024) + "M"; return new Status(ok ? Status.Level.OK : Status.Level.WARN, msg); } }
6,911
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.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.status.support; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.Status.Level; import java.util.Map; /** * StatusManager */ public class StatusUtils { public static Status getSummaryStatus(Map<String, Status> statuses) { Level level = Level.OK; StringBuilder msg = new StringBuilder(); for (Map.Entry<String, Status> entry : statuses.entrySet()) { String key = entry.getKey(); Status status = entry.getValue(); Level l = status.getLevel(); if (Level.ERROR.equals(l)) { level = Level.ERROR; if (msg.length() > 0) { msg.append(','); } msg.append(key); } else if (Level.WARN.equals(l)) { if (!Level.ERROR.equals(level)) { level = Level.WARN; } if (msg.length() > 0) { msg.append(','); } msg.append(key); } } return new Status(level, msg.toString()); } }
6,912
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.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.status.support; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.system.OperatingSystemBeanManager; /** * Load Status */ @Activate public class LoadStatusChecker implements StatusChecker { @Override public Status check() { double load = OperatingSystemBeanManager.getOperatingSystemBean().getSystemLoadAverage(); if (load == -1) { load = OperatingSystemBeanManager.getSystemCpuUsage(); } int cpu = OperatingSystemBeanManager.getOperatingSystemBean().getAvailableProcessors(); Status.Level level; if (load < 0) { level = Status.Level.UNKNOWN; } else if (load < cpu) { level = Status.Level.OK; } else { level = Status.Level.WARN; } String message = (load < 0 ? "" : "load:" + load + ",") + "cpu:" + cpu; return new Status(level, message); } }
6,913
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/function/ThrowableFunction.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.function; import java.util.function.Function; /** * {@link Function} with {@link Throwable} * * @param <T> the source type * @param <R> the return type * @see Function * @see Throwable * @since 2.7.5 */ @FunctionalInterface public interface ThrowableFunction<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result * @throws Throwable if met with any error */ R apply(T t) throws Throwable; /** * Executes {@link ThrowableFunction} * * @param t the function argument * @return the function result * @throws RuntimeException wrappers {@link Throwable} */ default R execute(T t) throws RuntimeException { R result = null; try { result = apply(t); } catch (Throwable e) { throw new RuntimeException(e); } return result; } /** * Executes {@link ThrowableFunction} * * @param t the function argument * @param function {@link ThrowableFunction} * @param <T> the source type * @param <R> the return type * @return the result after execution */ static <T, R> R execute(T t, ThrowableFunction<T, R> function) { return function.execute(t); } }
6,914
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/function/Predicates.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.function; import java.util.function.Predicate; import static java.util.stream.Stream.of; /** * The utilities class for Java {@link Predicate} * * @since 2.7.5 */ public interface Predicates { Predicate[] EMPTY_ARRAY = new Predicate[0]; /** * {@link Predicate} always return <code>true</code> * * @param <T> the type to test * @return <code>true</code> */ static <T> Predicate<T> alwaysTrue() { return e -> true; } /** * {@link Predicate} always return <code>false</code> * * @param <T> the type to test * @return <code>false</code> */ static <T> Predicate<T> alwaysFalse() { return e -> false; } /** * a composed predicate that represents a short-circuiting logical AND of {@link Predicate predicates} * * @param predicates {@link Predicate predicates} * @param <T> the type to test * @return non-null */ static <T> Predicate<T> and(Predicate<T>... predicates) { return of(predicates).reduce(Predicate::and).orElseGet(Predicates::alwaysTrue); } /** * a composed predicate that represents a short-circuiting logical OR of {@link Predicate predicates} * * @param predicates {@link Predicate predicates} * @param <T> the detected type * @return non-null */ static <T> Predicate<T> or(Predicate<T>... predicates) { return of(predicates).reduce(Predicate::or).orElse(e -> true); } }
6,915
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/function/ThrowableAction.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.function; import java.util.function.Function; /** * A function interface for action with {@link Throwable} * * @see Function * @see Throwable * @since 2.7.5 */ @FunctionalInterface public interface ThrowableAction { /** * Executes the action * * @throws Throwable if met with error */ void execute() throws Throwable; /** * Executes {@link ThrowableAction} * * @param action {@link ThrowableAction} * @throws RuntimeException wrap {@link Exception} to {@link RuntimeException} */ static void execute(ThrowableAction action) throws RuntimeException { try { action.execute(); } catch (Throwable e) { throw new RuntimeException(e); } } }
6,916
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/function/Streams.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.function; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static java.util.stream.StreamSupport.stream; import static org.apache.dubbo.common.function.Predicates.and; import static org.apache.dubbo.common.function.Predicates.or; /** * The utilities class for {@link Stream} * * @since 2.7.5 */ public interface Streams { static <T, S extends Iterable<T>> Stream<T> filterStream(S values, Predicate<T> predicate) { return stream(values.spliterator(), false).filter(predicate); } static <T, S extends Iterable<T>> List<T> filterList(S values, Predicate<T> predicate) { return filterStream(values, predicate).collect(toList()); } static <T, S extends Iterable<T>> Set<T> filterSet(S values, Predicate<T> predicate) { // new Set with insertion order return filterStream(values, predicate).collect(LinkedHashSet::new, Set::add, Set::addAll); } @SuppressWarnings("unchecked") static <T, S extends Iterable<T>> S filter(S values, Predicate<T> predicate) { final boolean isSet = Set.class.isAssignableFrom(values.getClass()); return (S) (isSet ? filterSet(values, predicate) : filterList(values, predicate)); } static <T, S extends Iterable<T>> S filterAll(S values, Predicate<T>... predicates) { return filter(values, and(predicates)); } static <T, S extends Iterable<T>> S filterAny(S values, Predicate<T>... predicates) { return filter(values, or(predicates)); } static <T> T filterFirst(Iterable<T> values, Predicate<T>... predicates) { return stream(values.spliterator(), false) .filter(and(predicates)) .findFirst() .orElse(null); } }
6,917
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/function/ThrowableConsumer.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.function; import java.util.function.Consumer; import java.util.function.Function; /** * {@link Consumer} with {@link Throwable} * * @param <T> the source type * @see Function * @see Throwable * @since 2.7.5 */ @FunctionalInterface public interface ThrowableConsumer<T> { /** * Applies this function to the given argument. * * @param t the function argument * @throws Throwable if met with any error */ void accept(T t) throws Throwable; /** * Executes {@link ThrowableConsumer} * * @param t the function argument * @throws RuntimeException wrappers {@link Throwable} */ default void execute(T t) throws RuntimeException { try { accept(t); } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e.getCause()); } } /** * Executes {@link ThrowableConsumer} * * @param t the function argument * @param consumer {@link ThrowableConsumer} * @param <T> the source type */ static <T> void execute(T t, ThrowableConsumer<T> consumer) { consumer.execute(t); } }
6,918
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/threadpool/ThreadPool.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.threadpool; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.concurrent.Executor; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; /** * ThreadPool */ // TODO which scope for ThreadPool? APPLICATION or FRAMEWORK @SPI(value = "fixed", scope = ExtensionScope.FRAMEWORK) public interface ThreadPool { /** * Thread pool * * @param url URL contains thread parameter * @return thread pool */ @Adaptive({THREADPOOL_KEY}) Executor getExecutor(URL url); }
6,919
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/threadpool/MemoryLimitedLinkedBlockingQueue.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.threadpool; import java.lang.instrument.Instrumentation; import java.util.Collection; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * Can completely solve the OOM problem caused by {@link java.util.concurrent.LinkedBlockingQueue}. */ public class MemoryLimitedLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> { private static final long serialVersionUID = 1374792064759926198L; private final MemoryLimiter memoryLimiter; public MemoryLimitedLinkedBlockingQueue(Instrumentation inst) { this(Integer.MAX_VALUE, inst); } public MemoryLimitedLinkedBlockingQueue(long memoryLimit, Instrumentation inst) { super(Integer.MAX_VALUE); this.memoryLimiter = new MemoryLimiter(memoryLimit, inst); } public MemoryLimitedLinkedBlockingQueue(Collection<? extends E> c, long memoryLimit, Instrumentation inst) { super(c); this.memoryLimiter = new MemoryLimiter(memoryLimit, inst); } public void setMemoryLimit(long memoryLimit) { memoryLimiter.setMemoryLimit(memoryLimit); } public long getMemoryLimit() { return memoryLimiter.getMemoryLimit(); } public long getCurrentMemory() { return memoryLimiter.getCurrentMemory(); } public long getCurrentRemainMemory() { return memoryLimiter.getCurrentRemainMemory(); } @Override public void put(E e) throws InterruptedException { memoryLimiter.acquireInterruptibly(e); super.put(e); } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { return memoryLimiter.acquire(e, timeout, unit) && super.offer(e, timeout, unit); } @Override public boolean offer(E e) { return memoryLimiter.acquire(e) && super.offer(e); } @Override public E take() throws InterruptedException { final E e = super.take(); memoryLimiter.releaseInterruptibly(e); return e; } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { final E e = super.poll(timeout, unit); memoryLimiter.releaseInterruptibly(e, timeout, unit); return e; } @Override public E poll() { final E e = super.poll(); memoryLimiter.release(e); return e; } @Override public boolean remove(Object o) { final boolean success = super.remove(o); if (success) { memoryLimiter.release(o); } return success; } @Override public void clear() { super.clear(); memoryLimiter.clear(); } }
6,920
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/threadpool/MemorySafeLinkedBlockingQueue.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.threadpool; import org.apache.dubbo.common.concurrent.DiscardPolicy; import org.apache.dubbo.common.concurrent.Rejector; import java.util.Collection; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * Can completely solve the OOM problem caused by {@link java.util.concurrent.LinkedBlockingQueue}, * does not depend on {@link java.lang.instrument.Instrumentation} and is easier to use than * {@link MemoryLimitedLinkedBlockingQueue}. * * @see <a href="https://github.com/apache/incubator-shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/concurrent/MemorySafeLinkedBlockingQueue.java">MemorySafeLinkedBlockingQueue</a> */ public class MemorySafeLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> { private static final long serialVersionUID = 8032578371739960142L; public static int THE_256_MB = 256 * 1024 * 1024; private long maxFreeMemory; private Rejector<E> rejector; public MemorySafeLinkedBlockingQueue() { this(THE_256_MB); } public MemorySafeLinkedBlockingQueue(final long maxFreeMemory) { super(Integer.MAX_VALUE); this.maxFreeMemory = maxFreeMemory; // default as DiscardPolicy to ensure compatibility with the old version this.rejector = new DiscardPolicy<>(); } public MemorySafeLinkedBlockingQueue(final Collection<? extends E> c, final int maxFreeMemory) { super(c); this.maxFreeMemory = maxFreeMemory; // default as DiscardPolicy to ensure compatibility with the old version this.rejector = new DiscardPolicy<>(); } /** * set the max free memory. * * @param maxFreeMemory the max free memory */ public void setMaxFreeMemory(final int maxFreeMemory) { this.maxFreeMemory = maxFreeMemory; } /** * get the max free memory. * * @return the max free memory limit */ public long getMaxFreeMemory() { return maxFreeMemory; } /** * set the rejector. * * @param rejector the rejector */ public void setRejector(final Rejector<E> rejector) { this.rejector = rejector; } /** * determine if there is any remaining free memory. * * @return true if has free memory */ public boolean hasRemainedMemory() { return MemoryLimitCalculator.maxAvailable() > maxFreeMemory; } @Override public void put(final E e) throws InterruptedException { if (hasRemainedMemory()) { super.put(e); } else { rejector.reject(e, this); } } @Override public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { if (!hasRemainedMemory()) { rejector.reject(e, this); return false; } return super.offer(e, timeout, unit); } @Override public boolean offer(final E e) { if (!hasRemainedMemory()) { rejector.reject(e, this); return false; } return super.offer(e); } }
6,921
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/threadpool/ThreadlessExecutor.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.threadpool; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; /** * The most important difference between this Executor and other normal Executor is that this one doesn't manage * any thread. * <p> * Tasks submitted to this executor through {@link #execute(Runnable)} will not get scheduled to a specific thread, though normal executors always do the schedule. * Those tasks are stored in a blocking queue and will only be executed when a thread calls {@link #waitAndDrain()}, the thread executing the task * is exactly the same as the one calling waitAndDrain. */ public class ThreadlessExecutor extends AbstractExecutorService { private static final Logger logger = LoggerFactory.getLogger(ThreadlessExecutor.class.getName()); private static final Object SHUTDOWN = new Object(); private final Queue<Runnable> queue = new ConcurrentLinkedQueue<>(); /** * Wait thread. It must be visible to other threads and does not need to be thread-safe */ private final AtomicReference<Object> waiter = new AtomicReference<>(); /** * Waits until there is a task, executes the task and all queued tasks (if there're any). The task is either a normal * response or a timeout response. */ public void waitAndDrain(long deadline) throws InterruptedException { throwIfInterrupted(); Runnable runnable = queue.poll(); if (runnable == null) { if (waiter.compareAndSet(null, Thread.currentThread())) { try { while ((runnable = queue.poll()) == null && waiter.get() == Thread.currentThread()) { long restTime = deadline - System.nanoTime(); if (restTime <= 0) { return; } LockSupport.parkNanos(this, restTime); throwIfInterrupted(); } } finally { waiter.compareAndSet(Thread.currentThread(), null); } } } do { if (runnable != null) { runnable.run(); } } while ((runnable = queue.poll()) != null); } private static void throwIfInterrupted() throws InterruptedException { if (Thread.interrupted()) { throw new InterruptedException(); } } /** * If the calling thread is still waiting for a callback task, add the task into the blocking queue to wait for schedule. * Otherwise, submit to shared callback executor directly. * * @param runnable */ @Override public void execute(Runnable runnable) { RunnableWrapper run = new RunnableWrapper(runnable); queue.add(run); if (waiter.get() != SHUTDOWN) { LockSupport.unpark((Thread) waiter.get()); } else if (queue.remove(run)) { throw new RejectedExecutionException(); } } /** * The following methods are still not supported */ @Override public void shutdown() { shutdownNow(); } @Override public List<Runnable> shutdownNow() { if (waiter.get() != SHUTDOWN) { LockSupport.unpark((Thread) waiter.get()); } waiter.set(SHUTDOWN); Runnable runnable; while ((runnable = queue.poll()) != null) { runnable.run(); } return Collections.emptyList(); } @Override public boolean isShutdown() { return waiter.get() == SHUTDOWN; } @Override public boolean isTerminated() { return isShutdown(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) { return false; } private static class RunnableWrapper implements Runnable { private final Runnable runnable; public RunnableWrapper(Runnable runnable) { this.runnable = runnable; } @Override public void run() { try { runnable.run(); } catch (Throwable t) { logger.info(t); } } } }
6,922
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/threadpool/MemoryLimitCalculator.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.threadpool; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.utils.NamedThreadFactory; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * {@link java.lang.Runtime#freeMemory()} technology is used to calculate the * memory limit by using the percentage of the current maximum available memory, * which can be used with {@link MemoryLimiter}. * * @see MemoryLimiter * @see <a href="https://github.com/apache/incubator-shenyu/blob/master/shenyu-common/src/main/java/org/apache/shenyu/common/concurrent/MemoryLimitCalculator.java">MemoryLimitCalculator</a> */ public class MemoryLimitCalculator { private static volatile long maxAvailable; private static final AtomicBoolean refreshStarted = new AtomicBoolean(false); private static void refresh() { maxAvailable = Runtime.getRuntime().freeMemory(); } private static void checkAndScheduleRefresh() { if (!refreshStarted.get()) { // immediately refresh when first call to prevent maxAvailable from being 0 // to ensure that being refreshed before refreshStarted being set as true // notice: refresh may be called for more than once because there is no lock refresh(); if (refreshStarted.compareAndSet(false, true)) { ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Memory-Calculator")); // check every 50 ms to improve performance scheduledExecutorService.scheduleWithFixedDelay( MemoryLimitCalculator::refresh, 50, 50, TimeUnit.MILLISECONDS); GlobalResourcesRepository.registerGlobalDisposable(() -> { refreshStarted.set(false); scheduledExecutorService.shutdown(); }); } } } /** * Get the maximum available memory of the current JVM. * * @return maximum available memory */ public static long maxAvailable() { checkAndScheduleRefresh(); return maxAvailable; } /** * Take the current JVM's maximum available memory * as a percentage of the result as the limit. * * @param percentage percentage * @return available memory */ public static long calculate(final float percentage) { if (percentage <= 0 || percentage > 1) { throw new IllegalArgumentException(); } checkAndScheduleRefresh(); return (long) (maxAvailable() * percentage); } /** * By default, it takes 80% of the maximum available memory of the current JVM. * * @return available memory */ public static long defaultLimit() { checkAndScheduleRefresh(); return (long) (maxAvailable() * 0.8); } }
6,923
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/threadpool/MemoryLimiter.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.threadpool; import java.lang.instrument.Instrumentation; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * memory limiter. */ public class MemoryLimiter { private final Instrumentation inst; private long memoryLimit; private final LongAdder memory = new LongAdder(); private final ReentrantLock acquireLock = new ReentrantLock(); private final Condition notLimited = acquireLock.newCondition(); private final ReentrantLock releaseLock = new ReentrantLock(); private final Condition notEmpty = releaseLock.newCondition(); public MemoryLimiter(Instrumentation inst) { this(Integer.MAX_VALUE, inst); } public MemoryLimiter(long memoryLimit, Instrumentation inst) { if (memoryLimit <= 0) { throw new IllegalArgumentException(); } this.memoryLimit = memoryLimit; this.inst = inst; } public void setMemoryLimit(long memoryLimit) { if (memoryLimit <= 0) { throw new IllegalArgumentException(); } this.memoryLimit = memoryLimit; } public long getMemoryLimit() { return memoryLimit; } public long getCurrentMemory() { return memory.sum(); } public long getCurrentRemainMemory() { return getMemoryLimit() - getCurrentMemory(); } private void signalNotEmpty() { releaseLock.lock(); try { notEmpty.signal(); } finally { releaseLock.unlock(); } } private void signalNotLimited() { acquireLock.lock(); try { notLimited.signal(); } finally { acquireLock.unlock(); } } /** * Locks to prevent both acquires and releases. */ private void fullyLock() { acquireLock.lock(); releaseLock.lock(); } /** * Unlocks to allow both acquires and releases. */ private void fullyUnlock() { releaseLock.unlock(); acquireLock.unlock(); } public boolean acquire(Object e) { if (e == null) { throw new NullPointerException(); } if (memory.sum() >= memoryLimit) { return false; } acquireLock.lock(); try { final long sum = memory.sum(); final long objectSize = inst.getObjectSize(e); if (sum + objectSize >= memoryLimit) { return false; } memory.add(objectSize); // see https://github.com/apache/incubator-shenyu/pull/3356 if (memory.sum() < memoryLimit) { notLimited.signal(); } } finally { acquireLock.unlock(); } if (memory.sum() > 0) { signalNotEmpty(); } return true; } public void acquireInterruptibly(Object e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } acquireLock.lockInterruptibly(); try { final long objectSize = inst.getObjectSize(e); // see https://github.com/apache/incubator-shenyu/pull/3335 while (memory.sum() + objectSize >= memoryLimit) { notLimited.await(); } memory.add(objectSize); if (memory.sum() < memoryLimit) { notLimited.signal(); } } finally { acquireLock.unlock(); } if (memory.sum() > 0) { signalNotEmpty(); } } public boolean acquire(Object e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } long nanos = unit.toNanos(timeout); acquireLock.lockInterruptibly(); try { final long objectSize = inst.getObjectSize(e); while (memory.sum() + objectSize >= memoryLimit) { if (nanos <= 0) { return false; } nanos = notLimited.awaitNanos(nanos); } memory.add(objectSize); if (memory.sum() < memoryLimit) { notLimited.signal(); } } finally { acquireLock.unlock(); } if (memory.sum() > 0) { signalNotEmpty(); } return true; } public void release(Object e) { if (null == e) { return; } if (memory.sum() == 0) { return; } releaseLock.lock(); try { final long objectSize = inst.getObjectSize(e); if (memory.sum() > 0) { memory.add(-objectSize); if (memory.sum() > 0) { notEmpty.signal(); } } } finally { releaseLock.unlock(); } if (memory.sum() < memoryLimit) { signalNotLimited(); } } public void releaseInterruptibly(Object e) throws InterruptedException { if (null == e) { return; } releaseLock.lockInterruptibly(); try { final long objectSize = inst.getObjectSize(e); while (memory.sum() == 0) { notEmpty.await(); } memory.add(-objectSize); if (memory.sum() > 0) { notEmpty.signal(); } } finally { releaseLock.unlock(); } if (memory.sum() < memoryLimit) { signalNotLimited(); } } public void releaseInterruptibly(Object e, long timeout, TimeUnit unit) throws InterruptedException { if (null == e) { return; } long nanos = unit.toNanos(timeout); releaseLock.lockInterruptibly(); try { final long objectSize = inst.getObjectSize(e); while (memory.sum() == 0) { if (nanos <= 0) { return; } nanos = notEmpty.awaitNanos(nanos); } memory.add(-objectSize); if (memory.sum() > 0) { notEmpty.signal(); } } finally { releaseLock.unlock(); } if (memory.sum() < memoryLimit) { signalNotLimited(); } } public void clear() { fullyLock(); try { if (memory.sumThenReset() < memoryLimit) { notLimited.signal(); } } finally { fullyUnlock(); } } }
6,924
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/Ring.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.threadpool.manager; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; public class Ring<T> { AtomicInteger count = new AtomicInteger(); private final List<T> itemList = new CopyOnWriteArrayList<>(); public void addItem(T t) { if (t != null) { itemList.add(t); } } public T pollItem() { if (itemList.isEmpty()) { return null; } if (itemList.size() == 1) { return itemList.get(0); } if (count.intValue() > Integer.MAX_VALUE - 10000) { count.set(count.get() % itemList.size()); } int index = Math.abs(count.getAndIncrement()) % itemList.size(); return itemList.get(index); } public T peekItem() { if (itemList.isEmpty()) { return null; } if (itemList.size() == 1) { return itemList.get(0); } int index = Math.abs(count.get()) % itemList.size(); return itemList.get(index); } public List<T> listItems() { return Collections.unmodifiableList(itemList); } }
6,925
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.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.threadpool.manager; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.executor.ExecutorSupport; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION; /** * */ @SPI(value = "isolation", scope = ExtensionScope.APPLICATION) public interface ExecutorRepository { /** * Called by both Client and Server. TODO, consider separate these two parts. * When the Client or Server starts for the first time, generate a new threadpool according to the parameters specified. * * @param url * @return */ ExecutorService createExecutorIfAbsent(URL url); /** * Be careful,The semantics of this method are getOrDefaultExecutor * * @param url * @return */ ExecutorService getExecutor(URL url); ExecutorService getExecutor(ServiceModel serviceModel, URL url); /** * Modify some of the threadpool's properties according to the url, for example, coreSize, maxSize, ... * * @param url * @param executor */ void updateThreadpool(URL url, ExecutorService executor); ScheduledExecutorService getServiceExportExecutor(); /** * The executor only used in bootstrap currently, we should call this method to release the resource * after the async export is done. */ void shutdownServiceExportExecutor(); ExecutorService getServiceReferExecutor(); /** * The executor only used in bootstrap currently, we should call this method to release the resource * after the async refer is done. */ void shutdownServiceReferExecutor(); /** * Destroy all executors that are not in shutdown state */ void destroyAll(); /** * Returns a scheduler from the scheduler list, call this method whenever you need a scheduler for a cron job. * If your cron cannot burden the possible schedule delay caused by sharing the same scheduler, please consider define a dedicate one. * * @deprecated use {@link FrameworkExecutorRepository#nextScheduledExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService nextScheduledExecutor(); /** * @deprecated use {@link FrameworkExecutorRepository#nextExecutorExecutor()} instead * @return ExecutorService */ @Deprecated ExecutorService nextExecutorExecutor(); /** * @deprecated use {@link FrameworkExecutorRepository#getServiceDiscoveryAddressNotificationExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor(); /** * @deprecated use {@link FrameworkExecutorRepository#getMetadataRetryExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService getMetadataRetryExecutor(); /** * Scheduled executor handle registry notification. * * @deprecated use {@link FrameworkExecutorRepository#getRegistryNotificationExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService getRegistryNotificationExecutor(); /** * Get the default shared threadpool. * * @deprecated use {@link FrameworkExecutorRepository#getSharedExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ExecutorService getSharedExecutor(); /** * Get the shared schedule executor * * @deprecated use {@link FrameworkExecutorRepository#getSharedScheduledExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService getSharedScheduledExecutor(); /** * @deprecated use {@link FrameworkExecutorRepository#getPoolRouterExecutor()} instead * @return ExecutorService */ @Deprecated ExecutorService getPoolRouterExecutor(); /** * Scheduled executor handle connectivity check task * * @deprecated use {@link FrameworkExecutorRepository#getConnectivityScheduledExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService getConnectivityScheduledExecutor(); /** * Scheduler used to refresh file based caches from memory to disk. * * @deprecated use {@link FrameworkExecutorRepository#getCacheRefreshingScheduledExecutor()} instead * @return ScheduledExecutorService */ @Deprecated ScheduledExecutorService getCacheRefreshingScheduledExecutor(); /** * Executor used to run async mapping tasks * * @deprecated use {@link FrameworkExecutorRepository#getMappingRefreshingExecutor()} instead * @return ExecutorService */ @Deprecated ExecutorService getMappingRefreshingExecutor(); ExecutorSupport getExecutorSupport(URL url); static ExecutorRepository getInstance(ApplicationModel applicationModel) { ExtensionLoader<ExecutorRepository> extensionLoader = applicationModel.getExtensionLoader(ExecutorRepository.class); String mode = getMode(applicationModel); return StringUtils.isNotEmpty(mode) ? extensionLoader.getExtension(mode) : extensionLoader.getDefaultExtension(); } static String getMode(ApplicationModel applicationModel) { Optional<ApplicationConfig> optional = applicationModel.getApplicationConfigManager().getApplication(); return optional.map(ApplicationConfig::getExecutorManagementMode).orElse(EXECUTOR_MANAGEMENT_MODE_ISOLATION); } }
6,926
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.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.threadpool.manager; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; public class FrameworkExecutorRepository implements Disposable { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FrameworkExecutorRepository.class); private final ExecutorService sharedExecutor; private final ScheduledExecutorService sharedScheduledExecutor; private final Ring<ScheduledExecutorService> scheduledExecutors = new Ring<>(); private final ScheduledExecutorService connectivityScheduledExecutor; private final ScheduledExecutorService cacheRefreshingScheduledExecutor; private final ExecutorService mappingRefreshingExecutor; public final Ring<ScheduledExecutorService> registryNotificationExecutorRing = new Ring<>(); private final Ring<ScheduledExecutorService> serviceDiscoveryAddressNotificationExecutorRing = new Ring<>(); private final ScheduledExecutorService metadataRetryExecutor; private final ExecutorService poolRouterExecutor; private final Ring<ExecutorService> executorServiceRing = new Ring<>(); private final ExecutorService internalServiceExecutor; public FrameworkExecutorRepository() { sharedExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-framework-shared-handler", true)); sharedScheduledExecutor = Executors.newScheduledThreadPool(8, new NamedThreadFactory("Dubbo-framework-shared-scheduler", true)); int availableProcessors = Runtime.getRuntime().availableProcessors(); for (int i = 0; i < availableProcessors; i++) { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("Dubbo-framework-scheduler-" + i, true)); scheduledExecutors.addItem(scheduler); executorServiceRing.addItem(new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), new NamedInternalThreadFactory("Dubbo-framework-state-router-loop-" + i, true), new ThreadPoolExecutor.AbortPolicy())); } connectivityScheduledExecutor = Executors.newScheduledThreadPool( availableProcessors, new NamedThreadFactory("Dubbo-framework-connectivity-scheduler", true)); cacheRefreshingScheduledExecutor = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("Dubbo-framework-cache-refreshing-scheduler", true)); mappingRefreshingExecutor = Executors.newFixedThreadPool( availableProcessors, new NamedThreadFactory("Dubbo-framework-mapping-refreshing-scheduler", true)); poolRouterExecutor = new ThreadPoolExecutor( 1, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), new NamedInternalThreadFactory("Dubbo-framework-state-router-pool-router", true), new ThreadPoolExecutor.AbortPolicy()); for (int i = 0; i < availableProcessors; i++) { ScheduledExecutorService serviceDiscoveryAddressNotificationExecutor = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("Dubbo-framework-SD-address-refresh-" + i)); ScheduledExecutorService registryNotificationExecutor = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("Dubbo-framework-registry-notification-" + i)); serviceDiscoveryAddressNotificationExecutorRing.addItem(serviceDiscoveryAddressNotificationExecutor); registryNotificationExecutorRing.addItem(registryNotificationExecutor); } metadataRetryExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-metadata-retry")); internalServiceExecutor = new ThreadPoolExecutor( 0, 100, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new NamedInternalThreadFactory("Dubbo-internal-service", true), new ThreadPoolExecutor.AbortPolicy()); } /** * Returns a scheduler from the scheduler list, call this method whenever you need a scheduler for a cron job. * If your cron cannot burden the possible schedule delay caused by sharing the same scheduler, please consider define a dedicated one. * * @return ScheduledExecutorService */ public ScheduledExecutorService nextScheduledExecutor() { return scheduledExecutors.pollItem(); } public ExecutorService nextExecutorExecutor() { return executorServiceRing.pollItem(); } /** * Scheduled executor handle registry notification. * * @return ScheduledExecutorService */ public ScheduledExecutorService getRegistryNotificationExecutor() { return registryNotificationExecutorRing.pollItem(); } public ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor() { return serviceDiscoveryAddressNotificationExecutorRing.pollItem(); } public ScheduledExecutorService getMetadataRetryExecutor() { return metadataRetryExecutor; } public ExecutorService getInternalServiceExecutor() { return internalServiceExecutor; } /** * Get the default shared thread pool. * * @return ExecutorService */ public ExecutorService getSharedExecutor() { return sharedExecutor; } /** * Get the shared schedule executor * * @return ScheduledExecutorService */ public ScheduledExecutorService getSharedScheduledExecutor() { return sharedScheduledExecutor; } public ExecutorService getPoolRouterExecutor() { return poolRouterExecutor; } /** * Scheduled executor handle connectivity check task * * @return ScheduledExecutorService */ public ScheduledExecutorService getConnectivityScheduledExecutor() { return connectivityScheduledExecutor; } /** * Scheduler used to refresh file based caches from memory to disk. * * @return ScheduledExecutorService */ public ScheduledExecutorService getCacheRefreshingScheduledExecutor() { return cacheRefreshingScheduledExecutor; } /** * Executor used to run async mapping tasks * * @return ExecutorService */ public ExecutorService getMappingRefreshingExecutor() { return mappingRefreshingExecutor; } @Override public void destroy() { logger.info("destroying framework executor repository .."); shutdownExecutorService(poolRouterExecutor, "poolRouterExecutor"); shutdownExecutorService(metadataRetryExecutor, "metadataRetryExecutor"); shutdownExecutorService(internalServiceExecutor, "internalServiceExecutor"); // scheduledExecutors shutdownExecutorServices(scheduledExecutors.listItems(), "scheduledExecutors"); // executorServiceRing shutdownExecutorServices(executorServiceRing.listItems(), "executorServiceRing"); // connectivityScheduledExecutor shutdownExecutorService(connectivityScheduledExecutor, "connectivityScheduledExecutor"); shutdownExecutorService(cacheRefreshingScheduledExecutor, "cacheRefreshingScheduledExecutor"); // shutdown share executor shutdownExecutorService(sharedExecutor, "sharedExecutor"); shutdownExecutorService(sharedScheduledExecutor, "sharedScheduledExecutor"); // serviceDiscoveryAddressNotificationExecutorRing shutdownExecutorServices( serviceDiscoveryAddressNotificationExecutorRing.listItems(), "serviceDiscoveryAddressNotificationExecutorRing"); // registryNotificationExecutorRing shutdownExecutorServices(registryNotificationExecutorRing.listItems(), "registryNotificationExecutorRing"); // mappingRefreshingExecutor shutdownExecutorService(mappingRefreshingExecutor, "mappingRefreshingExecutor"); } private void shutdownExecutorServices(List<? extends ExecutorService> executorServices, String msg) { for (ExecutorService executorService : executorServices) { shutdownExecutorService(executorService, msg); } } private void shutdownExecutorService(ExecutorService executorService, String name) { try { executorService.shutdownNow(); if (!executorService.awaitTermination( ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) { logger.warn( COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", "Wait global executor service terminated timeout."); } } catch (Exception e) { String msg = "shutdown executor service [" + name + "] failed: "; logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", msg + e.getMessage(), e); } } }
6,927
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/IsolationExecutorRepository.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.threadpool.manager; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.executor.ExecutorSupport; import org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; import java.util.concurrent.ExecutorService; import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_EXECUTOR; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * Thread pool isolation between services, that is, a service has its own thread pool and not interfere with each other */ public class IsolationExecutorRepository extends DefaultExecutorRepository { public IsolationExecutorRepository(ApplicationModel applicationModel) { super(applicationModel); } @Override protected URL setThreadNameIfAbsent(URL url, String executorCacheKey) { if (url.getParameter(THREAD_NAME_KEY) == null) { url = url.putAttribute(THREAD_NAME_KEY, "isolation-" + executorCacheKey); } return url; } @Override protected String getProviderKey(URL url) { if (url.getAttributes().containsKey(SERVICE_EXECUTOR)) { return url.getServiceKey(); } else { return super.getProviderKey(url); } } @Override protected String getProviderKey(ProviderModel providerModel, URL url) { if (url.getAttributes().containsKey(SERVICE_EXECUTOR)) { return providerModel.getServiceKey(); } else { return super.getProviderKey(url); } } @Override protected ExecutorService createExecutor(URL url) { Object executor = url.getAttributes().get(SERVICE_EXECUTOR); if (executor instanceof ExecutorService) { return (ExecutorService) executor; } return super.createExecutor(url); } @Override public ExecutorSupport getExecutorSupport(URL url) { return IsolationExecutorSupportFactory.getIsolationExecutorSupport(url); } }
6,928
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.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.threadpool.manager; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionAccessorAware; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.rpc.executor.DefaultExecutorSupport; import org.apache.dubbo.rpc.executor.ExecutorSupport; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_EXPORT_THREAD_NUM; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_REFER_THREAD_NUM; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_USE_THREAD_POOL; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_EXECUTORS_NO_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; /** * Consider implementing {@code Lifecycle} to enable executors shutdown when the process stops. */ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionAccessorAware { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultExecutorRepository.class); private static final String MAX_KEY = String.valueOf(Integer.MAX_VALUE); private volatile ScheduledExecutorService serviceExportExecutor; private volatile ExecutorService serviceReferExecutor; private final ConcurrentMap<String, ConcurrentMap<String, ExecutorService>> data = new ConcurrentHashMap<>(); private final Object LOCK = new Object(); private ExtensionAccessor extensionAccessor; private final ApplicationModel applicationModel; private final FrameworkExecutorRepository frameworkExecutorRepository; private ExecutorSupport executorSupport; private final DataStore dataStore; public DefaultExecutorRepository(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.frameworkExecutorRepository = applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); this.dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); } /** * Get called when the server or client instance initiating. * * @param url * @return */ @Override public synchronized ExecutorService createExecutorIfAbsent(URL url) { String executorKey = getExecutorKey(url); ConcurrentMap<String, ExecutorService> executors = ConcurrentHashMapUtils.computeIfAbsent(data, executorKey, k -> new ConcurrentHashMap<>()); String executorCacheKey = getExecutorSecondKey(url); url = setThreadNameIfAbsent(url, executorCacheKey); URL finalUrl = url; ExecutorService executor = ConcurrentHashMapUtils.computeIfAbsent(executors, executorCacheKey, k -> createExecutor(finalUrl)); // If executor has been shut down, create a new one if (executor.isShutdown() || executor.isTerminated()) { executors.remove(executorCacheKey); executor = createExecutor(url); executors.put(executorCacheKey, executor); } dataStore.put(executorKey, executorCacheKey, executor); return executor; } protected URL setThreadNameIfAbsent(URL url, String executorCacheKey) { if (url.getParameter(THREAD_NAME_KEY) == null) { String protocol = url.getProtocol(); if (StringUtils.isEmpty(protocol)) { protocol = DEFAULT_PROTOCOL; } url = url.putAttribute(THREAD_NAME_KEY, protocol + "-protocol-" + executorCacheKey); } return url; } private String getExecutorSecondKey(URL url) { if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) { return getConsumerKey(url); } else { return getProviderKey(url); } } private String getExecutorSecondKey(ServiceModel serviceModel, URL url) { if (serviceModel instanceof ConsumerModel) { return getConsumerKey(serviceModel); } else { return getProviderKey((ProviderModel) serviceModel, url); } } private String getConsumerKey(URL url) { // Consumer's executor is sharing globally, key=Integer.MAX_VALUE return String.valueOf(Integer.MAX_VALUE); } private String getConsumerKey(ServiceModel serviceModel) { // Consumer's executor is sharing globally, key=Integer.MAX_VALUE return MAX_KEY; } protected String getProviderKey(URL url) { // Provider's executor is sharing by protocol. return String.valueOf(url.getPort()); } protected String getProviderKey(ProviderModel providerModel, URL url) { // Provider's executor is sharing by protocol. return String.valueOf(url.getPort()); } /** * Return the executor key based on the type (internal or biz) of the current service. * * @param url * @return */ private String getExecutorKey(URL url) { if (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) { return CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; } return EXECUTOR_SERVICE_COMPONENT_KEY; } private String getExecutorKey(ServiceModel serviceModel) { if (serviceModel instanceof ProviderModel) { return EXECUTOR_SERVICE_COMPONENT_KEY; } else { return CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; } } protected ExecutorService createExecutor(URL url) { return (ExecutorService) extensionAccessor .getExtensionLoader(ThreadPool.class) .getAdaptiveExtension() .getExecutor(url); } @Override public ExecutorService getExecutor(URL url) { Map<String, ExecutorService> executors = data.get(getExecutorKey(url)); /* * It's guaranteed that this method is called after {@link #createExecutorIfAbsent(URL)}, so data should already * have Executor instances generated and stored. */ if (executors == null) { logger.warn( COMMON_EXECUTORS_NO_FOUND, "", "", "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + "before coming to here."); return null; } // Consumer's executor is sharing globally, key=Integer.MAX_VALUE. Provider's executor is sharing by protocol. String executorCacheKey = getExecutorSecondKey(url); ExecutorService executor = executors.get(executorCacheKey); if (executor != null && (executor.isShutdown() || executor.isTerminated())) { executors.remove(executorCacheKey); // Does not re-create a shutdown executor, use SHARED_EXECUTOR for downgrade. executor = null; logger.info("Executor for " + url + " is shutdown."); } if (executor == null) { return frameworkExecutorRepository.getSharedExecutor(); } else { return executor; } } @Override public ExecutorService getExecutor(ServiceModel serviceModel, URL url) { Map<String, ExecutorService> executors = data.get(getExecutorKey(serviceModel)); /* * It's guaranteed that this method is called after {@link #createExecutorIfAbsent(URL)}, so data should already * have Executor instances generated and stored. */ if (executors == null) { logger.warn( COMMON_EXECUTORS_NO_FOUND, "", "", "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + "before coming to here."); return null; } // Consumer's executor is sharing globally, key=Integer.MAX_VALUE. Provider's executor is sharing by protocol. String executorCacheKey = getExecutorSecondKey(serviceModel, url); ExecutorService executor = executors.get(executorCacheKey); if (executor != null && (executor.isShutdown() || executor.isTerminated())) { executors.remove(executorCacheKey); // Does not re-create a shutdown executor, use SHARED_EXECUTOR for downgrade. executor = null; logger.info("Executor for " + url + " is shutdown."); } if (executor == null) { return frameworkExecutorRepository.getSharedExecutor(); } else { return executor; } } @Override public void updateThreadpool(URL url, ExecutorService executor) { try { if (url.hasParameter(THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; int threads = url.getParameter(THREADS_KEY, 0); int max = threadPoolExecutor.getMaximumPoolSize(); int core = threadPoolExecutor.getCorePoolSize(); if (threads > 0 && (threads != max || threads != core)) { if (threads < core) { threadPoolExecutor.setCorePoolSize(threads); if (core == max) { threadPoolExecutor.setMaximumPoolSize(threads); } } else { threadPoolExecutor.setMaximumPoolSize(threads); if (core == max) { threadPoolExecutor.setCorePoolSize(threads); } } } } } catch (Throwable t) { logger.error(COMMON_ERROR_USE_THREAD_POOL, "", "", t.getMessage(), t); } } @Override public ScheduledExecutorService getServiceExportExecutor() { synchronized (LOCK) { if (serviceExportExecutor == null) { int coreSize = getExportThreadNum(); String applicationName = applicationModel.tryGetApplicationName(); applicationName = StringUtils.isEmpty(applicationName) ? "app" : applicationName; serviceExportExecutor = Executors.newScheduledThreadPool( coreSize, new NamedThreadFactory("Dubbo-" + applicationName + "-service-export", true)); } } return serviceExportExecutor; } @Override public void shutdownServiceExportExecutor() { synchronized (LOCK) { if (serviceExportExecutor != null && !serviceExportExecutor.isShutdown()) { try { serviceExportExecutor.shutdown(); } catch (Throwable ignored) { // ignored logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored); } } serviceExportExecutor = null; } } @Override public ExecutorService getServiceReferExecutor() { synchronized (LOCK) { if (serviceReferExecutor == null) { int coreSize = getReferThreadNum(); String applicationName = applicationModel.tryGetApplicationName(); applicationName = StringUtils.isEmpty(applicationName) ? "app" : applicationName; serviceReferExecutor = Executors.newFixedThreadPool( coreSize, new NamedThreadFactory("Dubbo-" + applicationName + "-service-refer", true)); } } return serviceReferExecutor; } @Override public void shutdownServiceReferExecutor() { synchronized (LOCK) { if (serviceReferExecutor != null && !serviceReferExecutor.isShutdown()) { try { serviceReferExecutor.shutdown(); } catch (Throwable ignored) { logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored); } } serviceReferExecutor = null; } } private Integer getExportThreadNum() { Integer threadNum = null; ApplicationModel applicationModel = ApplicationModel.ofNullable(this.applicationModel); for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) { threadNum = getExportThreadNum(moduleModel); if (threadNum != null) { break; } } if (threadNum == null) { logger.info("Cannot get config `export-thread-num` from module config, using default: " + DEFAULT_EXPORT_THREAD_NUM); return DEFAULT_EXPORT_THREAD_NUM; } return threadNum; } private Integer getExportThreadNum(ModuleModel moduleModel) { ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElse(null); if (moduleConfig == null) { return null; } Integer threadNum = moduleConfig.getExportThreadNum(); if (threadNum == null) { threadNum = moduleModel.getConfigManager().getProviders().stream() .map(ProviderConfig::getExportThreadNum) .filter(k -> k != null && k > 0) .findAny() .orElse(null); } return threadNum; } private Integer getReferThreadNum() { Integer threadNum = null; ApplicationModel applicationModel = ApplicationModel.ofNullable(this.applicationModel); for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) { threadNum = getReferThreadNum(moduleModel); if (threadNum != null) { break; } } if (threadNum == null) { logger.info("Cannot get config `refer-thread-num` from module config, using default: " + DEFAULT_REFER_THREAD_NUM); return DEFAULT_REFER_THREAD_NUM; } return threadNum; } private Integer getReferThreadNum(ModuleModel moduleModel) { ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElse(null); if (moduleConfig == null) { return null; } Integer threadNum = moduleConfig.getReferThreadNum(); if (threadNum == null) { threadNum = moduleModel.getConfigManager().getConsumers().stream() .map(ConsumerConfig::getReferThreadNum) .filter(k -> k != null && k > 0) .findAny() .orElse(null); } return threadNum; } @Override public void destroyAll() { logger.info("destroying application executor repository .."); shutdownServiceExportExecutor(); shutdownServiceReferExecutor(); data.values().forEach(executors -> { if (executors != null) { executors.values().forEach(executor -> { if (executor != null && !executor.isShutdown()) { try { ExecutorUtil.shutdownNow(executor, 100); } catch (Throwable ignored) { // ignored logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", ignored.getMessage(), ignored); } } }); } }); data.clear(); } private void shutdownExecutorService(ExecutorService executorService, String name) { try { executorService.shutdownNow(); } catch (Exception e) { String msg = "shutdown executor service [" + name + "] failed: "; logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", msg + e.getMessage(), e); } } @Override public void setExtensionAccessor(ExtensionAccessor extensionAccessor) { this.extensionAccessor = extensionAccessor; } @Override public ScheduledExecutorService nextScheduledExecutor() { return frameworkExecutorRepository.nextScheduledExecutor(); } @Override public ExecutorService nextExecutorExecutor() { return frameworkExecutorRepository.nextExecutorExecutor(); } @Override public ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor() { return frameworkExecutorRepository.getServiceDiscoveryAddressNotificationExecutor(); } @Override public ScheduledExecutorService getMetadataRetryExecutor() { return frameworkExecutorRepository.getMetadataRetryExecutor(); } @Override public ScheduledExecutorService getRegistryNotificationExecutor() { return frameworkExecutorRepository.getRegistryNotificationExecutor(); } @Override public ExecutorService getSharedExecutor() { return frameworkExecutorRepository.getSharedExecutor(); } @Override public ScheduledExecutorService getSharedScheduledExecutor() { return frameworkExecutorRepository.getSharedScheduledExecutor(); } @Override public ExecutorService getPoolRouterExecutor() { return frameworkExecutorRepository.getPoolRouterExecutor(); } @Override public ScheduledExecutorService getConnectivityScheduledExecutor() { return frameworkExecutorRepository.getConnectivityScheduledExecutor(); } @Override public ScheduledExecutorService getCacheRefreshingScheduledExecutor() { return frameworkExecutorRepository.getCacheRefreshingScheduledExecutor(); } @Override public ExecutorService getMappingRefreshingExecutor() { return frameworkExecutorRepository.getMappingRefreshingExecutor(); } @Override public ExecutorSupport getExecutorSupport(URL url) { if (executorSupport == null) { executorSupport = new DefaultExecutorSupport(url); } return executorSupport; } }
6,929
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.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.threadpool.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.JVMUtil; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import static java.lang.String.format; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_ENABLE; 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.CommonConstants.THREAD_POOL_EXHAUSTED_LISTENERS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_POOL_EXHAUSTED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_CREATE_DUMP; /** * Abort Policy. * Log warn info when abort. */ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbortPolicyWithReport.class); private final String threadName; private final URL url; protected static volatile long lastPrintTime = 0; private static final long TEN_MINUTES_MILLS = 10 * 60 * 1000; private static final String WIN_DATETIME_FORMAT = "yyyy-MM-dd_HH-mm-ss"; private static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd_HH:mm:ss"; protected static Semaphore guard = new Semaphore(1); private static final String USER_HOME = System.getProperty("user.home"); private final Set<ThreadPoolExhaustedListener> listeners = new ConcurrentHashSet<>(); public AbortPolicyWithReport(String threadName, URL url) { this.threadName = threadName; this.url = url; String threadPoolExhaustedListeners = url.getParameter( THREAD_POOL_EXHAUSTED_LISTENERS_KEY, (String) url.getAttribute(THREAD_POOL_EXHAUSTED_LISTENERS_KEY)); Set<String> listenerKeys = StringUtils.splitToSet(threadPoolExhaustedListeners, COMMA_SEPARATOR_CHAR, true); FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ExtensionLoader<ThreadPoolExhaustedListener> extensionLoader = frameworkModel.getExtensionLoader(ThreadPoolExhaustedListener.class); listenerKeys.forEach(key -> { if (extensionLoader.hasExtension(key)) { addThreadPoolExhaustedEventListener(extensionLoader.getExtension(key)); } }); } @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { String msg = String.format( "Thread pool is EXHAUSTED!" + " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d)," + " Task: %d (completed: %d)," + " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!", threadName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), e.getLargestPoolSize(), e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating(), url.getProtocol(), url.getIp(), url.getPort()); // 0-1 - Thread pool is EXHAUSTED! logger.warn(COMMON_THREAD_POOL_EXHAUSTED, "too much client requesting provider", "", msg); if (Boolean.parseBoolean(url.getParameter(DUMP_ENABLE, "true"))) { dumpJStack(); } dispatchThreadPoolExhaustedEvent(msg); throw new RejectedExecutionException(msg); } public void addThreadPoolExhaustedEventListener(ThreadPoolExhaustedListener listener) { listeners.add(listener); } public void removeThreadPoolExhaustedEventListener(ThreadPoolExhaustedListener listener) { listeners.remove(listener); } /** * dispatch ThreadPoolExhaustedEvent * * @param msg */ public void dispatchThreadPoolExhaustedEvent(String msg) { listeners.forEach(listener -> listener.onEvent(new ThreadPoolExhaustedEvent(msg))); } private void dumpJStack() { long now = System.currentTimeMillis(); // dump every 10 minutes if (now - lastPrintTime < TEN_MINUTES_MILLS) { return; } if (!guard.tryAcquire()) { return; } // To avoid multiple dump, check again if (System.currentTimeMillis() - lastPrintTime < TEN_MINUTES_MILLS) { return; } ExecutorService pool = Executors.newSingleThreadExecutor(); try { pool.execute(() -> { String dumpPath = getDumpPath(); SimpleDateFormat sdf; String os = System.getProperty(OS_NAME_KEY).toLowerCase(); // window system don't support ":" in file name if (os.contains(OS_WIN_PREFIX)) { sdf = new SimpleDateFormat(WIN_DATETIME_FORMAT); } else { sdf = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT); } String dateStr = sdf.format(new Date()); // try-with-resources try (FileOutputStream jStackStream = new FileOutputStream(new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) { jstack(jStackStream); } catch (Exception t) { logger.error(COMMON_UNEXPECTED_CREATE_DUMP, "", "", "dump jStack error", t); } finally { lastPrintTime = System.currentTimeMillis(); guard.release(); } }); } finally { // must shutdown thread pool ,if not will lead to OOM pool.shutdown(); } } protected void jstack(FileOutputStream jStackStream) throws Exception { JVMUtil.jstack(jStackStream); } protected String getDumpPath() { final String dumpPath = url.getParameter(DUMP_DIRECTORY); if (StringUtils.isEmpty(dumpPath)) { return USER_HOME; } final File dumpDirectory = new File(dumpPath); if (!dumpDirectory.exists()) { if (dumpDirectory.mkdirs()) { logger.info(format("Dubbo dump directory[%s] created", dumpDirectory.getAbsolutePath())); } else { logger.warn( COMMON_UNEXPECTED_CREATE_DUMP, "", "", format( "Dubbo dump directory[%s] can't be created, use the 'user.home'[%s]", dumpDirectory.getAbsolutePath(), USER_HOME)); return USER_HOME; } } return dumpPath; } }
6,930
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.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.threadpool.support.cached; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ALIVE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * This thread pool is self-tuned. Thread will be recycled after idle for one minute, and new thread will be created for * the upcoming request. * * @see java.util.concurrent.Executors#newCachedThreadPool() */ public class CachedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); int alive = url.getParameter(ALIVE_KEY, DEFAULT_ALIVE); BlockingQueue<Runnable> blockingQueue; if (queues == 0) { blockingQueue = new SynchronousQueue<>(); } else if (queues < 0) { blockingQueue = new MemorySafeLinkedBlockingQueue<>(); } else { blockingQueue = new LinkedBlockingQueue<>(queues); } return new ThreadPoolExecutor( cores, threads, alive, TimeUnit.MILLISECONDS, blockingQueue, new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } }
6,931
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.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.threadpool.support.fixed; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * Creates a thread pool that reuses a fixed number of threads * * @see java.util.concurrent.Executors#newFixedThreadPool(int) */ public class FixedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); BlockingQueue<Runnable> blockingQueue; if (queues == 0) { blockingQueue = new SynchronousQueue<>(); } else if (queues < 0) { blockingQueue = new MemorySafeLinkedBlockingQueue<>(); } else { blockingQueue = new LinkedBlockingQueue<>(queues); } return new ThreadPoolExecutor( threads, threads, 0, TimeUnit.MILLISECONDS, blockingQueue, new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } }
6,932
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.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.threadpool.support.limited; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * Creates a thread pool that creates new threads as needed until limits reaches. This thread pool will not shrink * automatically. */ public class LimitedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); BlockingQueue<Runnable> blockingQueue; if (queues == 0) { blockingQueue = new SynchronousQueue<>(); } else if (queues < 0) { blockingQueue = new MemorySafeLinkedBlockingQueue<>(); } else { blockingQueue = new LinkedBlockingQueue<>(queues); } return new ThreadPoolExecutor( cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS, blockingQueue, new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } }
6,933
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.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.threadpool.support.eager; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ALIVE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CORE_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_QUEUES; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * EagerThreadPool * When the core threads are all in busy, * create new thread instead of putting task into blocking queue. */ public class EagerThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); int alive = url.getParameter(ALIVE_KEY, DEFAULT_ALIVE); // init queue and executor TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues <= 0 ? 1 : queues); EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor( cores, threads, alive, TimeUnit.MILLISECONDS, taskQueue, new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); taskQueue.setExecutor(executor); return executor; } }
6,934
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.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.threadpool.support.eager; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * EagerThreadPoolExecutor */ public class EagerThreadPoolExecutor extends ThreadPoolExecutor { public EagerThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, TaskQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } @Override public void execute(Runnable command) { if (command == null) { throw new NullPointerException(); } try { super.execute(command); } catch (RejectedExecutionException rx) { // retry to offer the task into queue. final TaskQueue queue = (TaskQueue) super.getQueue(); try { if (!queue.retryOffer(command, 0, TimeUnit.MILLISECONDS)) { throw new RejectedExecutionException("Queue capacity is full.", rx); } } catch (InterruptedException x) { throw new RejectedExecutionException(x); } } } }
6,935
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.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.threadpool.support.eager; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; /** * TaskQueue in the EagerThreadPoolExecutor * It offer a task if the executor's submittedTaskCount less than currentPoolThreadSize * or the currentPoolThreadSize more than executor's maximumPoolSize. * That can make the executor create new worker * when the task num is bigger than corePoolSize but less than maximumPoolSize. */ public class TaskQueue<R extends Runnable> extends LinkedBlockingQueue<Runnable> { private static final long serialVersionUID = -2635853580887179627L; private EagerThreadPoolExecutor executor; public TaskQueue(int capacity) { super(capacity); } public void setExecutor(EagerThreadPoolExecutor exec) { executor = exec; } @Override public boolean offer(Runnable runnable) { if (executor == null) { throw new RejectedExecutionException("The task queue does not have executor!"); } int currentPoolThreadSize = executor.getPoolSize(); // have free worker. put task into queue to let the worker deal with task. if (executor.getActiveCount() < currentPoolThreadSize) { return super.offer(runnable); } // return false to let executor create new worker. if (currentPoolThreadSize < executor.getMaximumPoolSize()) { return false; } // currentPoolThreadSize >= max return super.offer(runnable); } /** * retry offer task * * @param o task * @return offer success or not * @throws RejectedExecutionException if executor is terminated. */ public boolean retryOffer(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if (executor.isShutdown()) { throw new RejectedExecutionException("Executor is shutdown!"); } return super.offer(o, timeout, unit); } }
6,936
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.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.threadpool.concurrent; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; public class ScheduledCompletableFuture { public static <T> CompletableFuture<T> schedule( ScheduledExecutorService executor, Supplier<T> task, long delay, TimeUnit unit) { CompletableFuture<T> completableFuture = new CompletableFuture<>(); executor.schedule( () -> { try { return completableFuture.complete(task.get()); } catch (Throwable t) { return completableFuture.completeExceptionally(t); } }, delay, unit); return completableFuture; } public static <T> CompletableFuture<T> submit(ScheduledExecutorService executor, Supplier<T> task) { CompletableFuture<T> completableFuture = new CompletableFuture<>(); executor.submit(() -> { try { return completableFuture.complete(task.get()); } catch (Throwable t) { return completableFuture.completeExceptionally(t); } }); return completableFuture; } }
6,937
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEvent.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.threadpool.event; /** * An Event when the Dubbo thread pool is exhausted. */ public class ThreadPoolExhaustedEvent { final String msg; public ThreadPoolExhaustedEvent(String msg) { this.msg = msg; } public String getMsg() { return msg; } }
6,938
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedListener.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.threadpool.event; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.FRAMEWORK) public interface ThreadPoolExhaustedListener { /** * Notify when the thread pool is exhausted. * {@link org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport} */ void onEvent(ThreadPoolExhaustedEvent event); }
6,939
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java
/* * Copyright 2014 The gRPC Authors * * Licensed 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.threadpool.serial; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadlocal.InternalThreadLocalMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_RUN_THREAD_TASK; import static org.apache.dubbo.common.utils.ExecutorUtil.isShutdown; /** * Executor ensuring that all {@link Runnable} tasks submitted are executed in order * using the provided {@link Executor}, and serially such that no two will ever be * running at the same time. */ public final class SerializingExecutor implements Executor, Runnable { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(SerializingExecutor.class); /** * Use false to stop and true to run */ private final AtomicBoolean atomicBoolean = new AtomicBoolean(); private final Executor executor; private final Queue<Runnable> runQueue = new ConcurrentLinkedQueue<>(); /** * Creates a SerializingExecutor, running tasks using {@code executor}. * * @param executor Executor in which tasks should be run. Must not be null. */ public SerializingExecutor(Executor executor) { this.executor = executor; } /** * Runs the given runnable strictly after all Runnables that were submitted * before it, and using the {@code executor} passed to the constructor. . */ @Override public void execute(Runnable r) { runQueue.add(r); schedule(r); } private void schedule(Runnable removable) { if (atomicBoolean.compareAndSet(false, true)) { boolean success = false; try { if (!isShutdown(executor)) { executor.execute(this); success = true; } } finally { // It is possible that at this point that there are still tasks in // the queue, it would be nice to keep trying but the error may not // be recoverable. So we update our state and propagate so that if // our caller deems it recoverable we won't be stuck. if (!success) { if (removable != null) { // This case can only be reached if 'this' was not currently running, and we failed to // reschedule. The item should still be in the queue for removal. // ConcurrentLinkedQueue claims that null elements are not allowed, but seems to not // throw if the item to remove is null. If removable is present in the queue twice, // the wrong one may be removed. It doesn't seem possible for this case to exist today. // This is important to run in case of RejectedExecutionException, so that future calls // to execute don't succeed and accidentally run a previous runnable. runQueue.remove(removable); } atomicBoolean.set(false); } } } } @Override public void run() { Runnable r; try { while ((r = runQueue.poll()) != null) { InternalThreadLocalMap internalThreadLocalMap = InternalThreadLocalMap.getAndRemove(); try { r.run(); } catch (RuntimeException e) { LOGGER.error(COMMON_ERROR_RUN_THREAD_TASK, "", "", "Exception while executing runnable " + r, e); } finally { InternalThreadLocalMap.set(internalThreadLocalMap); } } } finally { atomicBoolean.set(false); } if (!runQueue.isEmpty()) { // we didn't enqueue anything but someone else did. schedule(null); } } }
6,940
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.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.url.component; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.Objects; public class PathURLAddress extends URLAddress { private String protocol; private String username; private String password; private String path; private transient String address; private transient String ip; public PathURLAddress(String protocol, String username, String password, String path, String host, int port) { this(protocol, username, password, path, host, port, null); } public PathURLAddress( String protocol, String username, String password, String path, String host, int port, String rawAddress) { super(host, port, rawAddress); this.protocol = protocol; this.username = username; this.password = password; // trim the beginning "/" while (path != null && path.startsWith("/")) { path = path.substring(1); } if (path != null) { path = path.intern(); } this.path = path; } public String getProtocol() { return protocol; } public URLAddress setProtocol(String protocol) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getUsername() { return username; } public URLAddress setUsername(String username) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getPassword() { return password; } public PathURLAddress setPassword(String password) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getPath() { return path; } public PathURLAddress setPath(String path) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } @Override public URLAddress setHost(String host) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } @Override public URLAddress setPort(int port) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } @Override public URLAddress setAddress(String host, int port) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getAddress() { if (address == null) { address = getAddress(getHost(), getPort()); } return address; } /** * Fetch IP address for this URL. * <p> * Pls. note that IP should be used instead of Host when to compare with socket's address or to search in a map * which use address as its key. * * @return ip in string format */ public String getIp() { if (ip == null) { ip = NetUtils.getIpByHost(getHost()); } return ip; } @Override public int hashCode() { return Objects.hash(protocol, username, password, path, host, port); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof URLAddress)) return false; URLAddress that = (URLAddress) obj; return Objects.equals(this.getProtocol(), that.getProtocol()) && Objects.equals(this.getUsername(), that.getUsername()) && Objects.equals(this.getPassword(), that.getPassword()) && Objects.equals(this.getPath(), that.getPath()) && Objects.equals(this.getHost(), that.getHost()) && Objects.equals(this.getPort(), that.getPort()); } @Override public String toString() { if (rawAddress != null) { return rawAddress; } StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(protocol)) { buf.append(protocol); buf.append("://"); } // // if (StringUtils.isNotEmpty(username)) { // buf.append(username); // if (StringUtils.isNotEmpty(password)) { // buf.append(":"); // buf.append(password); // } // buf.append("@"); // } if (StringUtils.isNotEmpty(host)) { buf.append(host); if (port > 0) { buf.append(':'); buf.append(port); } } if (StringUtils.isNotEmpty(path)) { buf.append('/'); buf.append(path); } return buf.toString(); } }
6,941
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; public class DubboServiceAddressURL extends ServiceAddressURL { public static DubboServiceAddressURL valueOf(String rawURL, URL consumerURL) { return valueOf(rawURL, consumerURL, null); } public static DubboServiceAddressURL valueOf(String rawURL, URL consumerURL, ServiceConfigURL overriddenURL) { URL url = valueOf(rawURL, true); return new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, overriddenURL); } private ServiceConfigURL overrideURL; public DubboServiceAddressURL( URLAddress urlAddress, URLParam urlParam, URL consumerURL, ServiceConfigURL overrideURL) { super(urlAddress, urlParam, consumerURL); this.overrideURL = overrideURL; } @Override protected <T extends URL> T newURL(URLAddress urlAddress, URLParam urlParam) { return (T) new DubboServiceAddressURL(urlAddress, urlParam, this.consumerURL, this.overrideURL); } @Override public String getSide() { return consumerURL.getParameter(SIDE_KEY); } @Override public String getParameter(String key) { String value = null; if (overrideURL != null) { value = overrideURL.getParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getParameter(key); } return value; } @Override public String getMethodParameter(String method, String key) { String value = null; if (overrideURL != null) { value = overrideURL.getMethodParameterStrict(method, key); } if (StringUtils.isEmpty(value)) { value = super.getMethodParameter(method, key); } return value; } @Override public String getAnyMethodParameter(String key) { String value = null; if (overrideURL != null) { value = overrideURL.getAnyMethodParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getAnyMethodParameter(key); } return value; } /** * The returned parameters is imprecise regarding override priorities of consumer url and provider url. * This method is only used to pass the configuration in the 'client'. */ @Override public Map<String, String> getAllParameters() { Map<String, String> allParameters = new HashMap<>((int) (super.getParameters().size() / .75 + 1)); allParameters.putAll(super.getParameters()); if (consumerURL != null) { allParameters.putAll(consumerURL.getParameters()); } if (overrideURL != null) { allParameters.putAll(overrideURL.getParameters()); } return Collections.unmodifiableMap(allParameters); } public ServiceConfigURL getOverrideURL() { return overrideURL; } public void setOverrideURL(ServiceConfigURL overrideURL) { this.overrideURL = overrideURL; } @Override public ScopeModel getScopeModel() { return consumerURL.getScopeModel(); } @Override public ServiceModel getServiceModel() { return consumerURL.getServiceModel(); } @Override public int hashCode() { final int prime = 31; return prime * super.hashCode() + (overrideURL == null ? 0 : overrideURL.hashCode()); } /** * ignore consumer url compare. * It's only meaningful for comparing two AddressURLs related to the same consumerURL. * * @param obj * @return */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof DubboServiceAddressURL)) { return false; } if (overrideURL == null) { return super.equals(obj); } else { DubboServiceAddressURL other = (DubboServiceAddressURL) obj; boolean overrideEquals = Objects.equals( overrideURL.getParameters(), other.getOverrideURL().getParameters()); if (!overrideEquals) { return false; } Map<String, String> params = this.getParameters(); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (overrideURL.getParameters().containsKey(key)) { continue; } if (!entry.getValue().equals(other.getUrlParam().getParameter(key))) { return false; } } } return true; } }
6,942
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ServiceConfigURL extends URL { private transient volatile ConcurrentMap<String, URL> urls; private transient volatile ConcurrentMap<String, Number> numbers; private transient volatile ConcurrentMap<String, Map<String, Number>> methodNumbers; private transient volatile String full; private transient volatile String string; private transient volatile String identity; private transient volatile String parameter; public ServiceConfigURL() { super(); } public ServiceConfigURL(URLAddress urlAddress, URLParam urlParam, Map<String, Object> attributes) { super(urlAddress, urlParam, attributes); } public ServiceConfigURL(String protocol, String host, int port) { this(protocol, null, null, host, port, null, (Map<String, String>) null); } public ServiceConfigURL( String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead. this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } public ServiceConfigURL(String protocol, String host, int port, Map<String, String> parameters) { this(protocol, null, null, host, port, null, parameters); } public ServiceConfigURL(String protocol, String host, int port, String path) { this(protocol, null, null, host, port, path, (Map<String, String>) null); } public ServiceConfigURL(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public ServiceConfigURL(String protocol, String host, int port, String path, Map<String, String> parameters) { this(protocol, null, null, host, port, path, parameters); } public ServiceConfigURL(String protocol, String username, String password, String host, int port, String path) { this(protocol, username, password, host, port, path, (Map<String, String>) null); } public ServiceConfigURL( String protocol, String username, String password, String host, int port, String path, String... pairs) { this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } public ServiceConfigURL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { this(new PathURLAddress(protocol, username, password, path, host, port), URLParam.parse(parameters), null); } public ServiceConfigURL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, Map<String, Object> attributes) { this( new PathURLAddress(protocol, username, password, path, host, port), URLParam.parse(parameters), attributes); } @Override protected <T extends URL> T newURL(URLAddress urlAddress, URLParam urlParam) { return (T) new ServiceConfigURL(urlAddress, urlParam, attributes); } @Override public URL addAttributes(Map<String, Object> attributes) { Map<String, Object> newAttributes = new HashMap<>(); if (this.attributes != null) { newAttributes.putAll(this.attributes); } newAttributes.putAll(attributes); return new ServiceConfigURL(getUrlAddress(), getUrlParam(), newAttributes); } @Override public ServiceConfigURL putAttribute(String key, Object obj) { Map<String, Object> newAttributes = new HashMap<>(); if (attributes != null) { newAttributes.putAll(attributes); } newAttributes.put(key, obj); return new ServiceConfigURL(getUrlAddress(), getUrlParam(), newAttributes); } @Override public URL removeAttribute(String key) { Map<String, Object> newAttributes = new HashMap<>(); if (attributes != null) { newAttributes.putAll(attributes); } newAttributes.remove(key); return new ServiceConfigURL(getUrlAddress(), getUrlParam(), newAttributes); } @Override public String toString() { if (string != null) { return string; } return string = super.toString(); } @Override public String toFullString() { if (full != null) { return full; } return full = super.toFullString(); } @Override public String toIdentityString() { if (identity != null) { return identity; } return identity = super.toIdentityString(); } @Override public String toParameterString() { if (parameter != null) { return parameter; } return parameter = super.toParameterString(); } @Override public URL getUrlParameter(String key) { URL u = getUrls().get(key); if (u != null) { return u; } String value = getParameterAndDecoded(key); if (StringUtils.isEmpty(value)) { return null; } u = URL.valueOf(value); getUrls().put(key, u); return u; } @Override public double getParameter(String key, double defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.doubleValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); getNumbers().put(key, d); return d; } @Override public float getParameter(String key, float defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.floatValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); getNumbers().put(key, f); return f; } @Override public long getParameter(String key, long defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.longValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); getNumbers().put(key, l); return l; } @Override public int getParameter(String key, int defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.intValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); getNumbers().put(key, i); return i; } @Override public short getParameter(String key, short defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.shortValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); getNumbers().put(key, s); return s; } @Override public byte getParameter(String key, byte defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.byteValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); getNumbers().put(key, b); return b; } @Override public double getMethodParameter(String method, String key, double defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.doubleValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); updateCachedNumber(method, key, d); return d; } @Override public float getMethodParameter(String method, String key, float defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.floatValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); updateCachedNumber(method, key, f); return f; } @Override public long getMethodParameter(String method, String key, long defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.longValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); updateCachedNumber(method, key, l); return l; } @Override public int getMethodParameter(String method, String key, int defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.intValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); updateCachedNumber(method, key, i); return i; } @Override public short getMethodParameter(String method, String key, short defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.shortValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); updateCachedNumber(method, key, s); return s; } @Override public byte getMethodParameter(String method, String key, byte defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.byteValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); updateCachedNumber(method, key, b); return b; } @Override public double getServiceParameter(String service, String key, double defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.doubleValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); getNumbers().put(key, d); return d; } @Override public float getServiceParameter(String service, String key, float defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.floatValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); getNumbers().put(key, f); return f; } @Override public long getServiceParameter(String service, String key, long defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.longValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); getNumbers().put(key, l); return l; } @Override public short getServiceParameter(String service, String key, short defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.shortValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); getNumbers().put(key, s); return s; } @Override public byte getServiceParameter(String service, String key, byte defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.byteValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); getNumbers().put(key, b); return b; } @Override public double getServiceMethodParameter(String service, String method, String key, double defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.doubleValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); updateCachedNumber(method, key, d); return d; } @Override public float getServiceMethodParameter(String service, String method, String key, float defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.floatValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); updateCachedNumber(method, key, f); return f; } @Override public long getServiceMethodParameter(String service, String method, String key, long defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.longValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); updateCachedNumber(method, key, l); return l; } @Override public int getServiceMethodParameter(String service, String method, String key, int defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.intValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); updateCachedNumber(method, key, i); return i; } @Override public short getServiceMethodParameter(String service, String method, String key, short defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.shortValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); updateCachedNumber(method, key, s); return s; } @Override public byte getServiceMethodParameter(String service, String method, String key, byte defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.byteValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); updateCachedNumber(method, key, b); return b; } private Map<String, URL> getUrls() { // concurrent initialization is tolerant if (urls == null) { urls = new ConcurrentHashMap<>(); } return urls; } protected Map<String, Number> getNumbers() { // concurrent initialization is tolerant if (numbers == null) { numbers = new ConcurrentHashMap<>(); } return numbers; } private Number getCachedNumber(String method, String key) { Map<String, Number> keyNumber = getMethodNumbers().get(method); if (keyNumber != null) { return keyNumber.get(key); } return null; } private void updateCachedNumber(String method, String key, Number n) { Map<String, Number> keyNumber = ConcurrentHashMapUtils.computeIfAbsent(getMethodNumbers(), method, m -> new HashMap<>()); keyNumber.put(key, n); } protected ConcurrentMap<String, Map<String, Number>> getMethodNumbers() { if (methodNumbers == null) { // concurrent initialization is tolerant methodNumbers = new ConcurrentHashMap<>(); } return methodNumbers; } protected Map<String, Number> getServiceNumbers(String service) { return getNumbers(); } protected Map<String, Map<String, Number>> getServiceMethodNumbers(String service) { return getMethodNumbers(); } }
6,943
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_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.PROVIDERS_CATEGORY; public abstract class ServiceAddressURL extends URL { protected final transient URL consumerURL; // cache private transient Map<String, String> concatenatedPrams; // private transient Map<String, String> allParameters; public ServiceAddressURL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, URL consumerURL) { super(protocol, username, password, host, port, path, parameters); this.consumerURL = consumerURL; } public ServiceAddressURL(URLAddress urlAddress, URLParam urlParam, URL consumerURL) { super(urlAddress, urlParam); this.consumerURL = consumerURL; } @Override public String getPath() { String path = super.getPath(); if (StringUtils.isNotEmpty(path)) { return path; } return consumerURL.getPath(); } @Override public String getServiceInterface() { return consumerURL.getServiceInterface(); } @Override public String getApplication() { return consumerURL.getApplication(); } @Override public String getRemoteApplication() { return super.getParameter(APPLICATION_KEY); } @Override public String getGroup() { return super.getParameter(GROUP_KEY); } @Override public String getVersion() { return super.getParameter(VERSION_KEY); } @Override public String getOriginalParameter(String key) { // call corresponding methods directly, then we can remove the following if branches. if (GROUP_KEY.equals(key)) { return getGroup(); } else if (VERSION_KEY.equals(key)) { return getVersion(); } else if (APPLICATION_KEY.equals(key)) { return getRemoteApplication(); } else if (SIDE_KEY.equals(key)) { return getSide(); } else if (CATEGORY_KEY.equals(key)) { return getCategory(); } return super.getParameter(key); } @Override public String getParameter(String key) { // call corresponding methods directly, then we can remove the following if branches. if (GROUP_KEY.equals(key)) { return getGroup(); } else if (VERSION_KEY.equals(key)) { return getVersion(); } else if (APPLICATION_KEY.equals(key)) { return getRemoteApplication(); } else if (SIDE_KEY.equals(key)) { return getSide(); } else if (CATEGORY_KEY.equals(key)) { return getCategory(); } String value = null; if (consumerURL != null) { value = consumerURL.getParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getParameter(key); } return value; } @Override public String getMethodParameter(String method, String key) { String value = null; if (consumerURL != null) { value = consumerURL.getMethodParameterStrict(method, key); } if (StringUtils.isEmpty(value)) { value = super.getMethodParameterStrict(method, key); } if (StringUtils.isEmpty(value)) { value = getParameter(key); } return value; } @Override public String getAnyMethodParameter(String key) { String value = null; if (consumerURL != null) { value = consumerURL.getAnyMethodParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getAnyMethodParameter(key); } return value; } @Override public String getConcatenatedParameter(String key) { if (concatenatedPrams == null) { concatenatedPrams = new HashMap<>(1); } String value = concatenatedPrams.get(key); if (StringUtils.isNotEmpty(value)) { return value; } // Combine filters and listeners on Provider and Consumer String remoteValue = super.getParameter(key); String localValue = consumerURL.getParameter(key); if (remoteValue != null && remoteValue.length() > 0 && localValue != null && localValue.length() > 0) { value = remoteValue + "," + localValue; concatenatedPrams.put(key, value); return value; } if (localValue != null && localValue.length() > 0) { value = localValue; } else if (remoteValue != null && remoteValue.length() > 0) { value = remoteValue; } concatenatedPrams.put(key, value); return value; } @Override public String getCategory() { return PROVIDERS_CATEGORY; } @Override public String getSide() { return CONSUMER_SIDE; } public URL getConsumerURL() { return consumerURL; } @Override public int hashCode() { return super.hashCode(); } @Override public ScopeModel getScopeModel() { return consumerURL.getScopeModel(); } @Override public ServiceModel getServiceModel() { return consumerURL.getServiceModel(); } @Override public URL setScopeModel(ScopeModel scopeModel) { throw new UnsupportedOperationException("setScopeModel is forbidden for ServiceAddressURL"); } @Override public URL setServiceModel(ServiceModel serviceModel) { throw new UnsupportedOperationException("setServiceModel is forbidden for ServiceAddressURL"); } /** * ignore consumer url compare. * It's only meaningful for comparing two address urls related to the same consumerURL. * * @param obj * @return */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ServiceAddressURL)) { return false; } return super.equals(obj); } @Override public String toString() { URLParam totalParam = getUrlParam().addParametersIfAbsent(consumerURL.getParameters()); return new ServiceConfigURL(getUrlAddress(), totalParam, null).toString(); } }
6,944
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.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.url.component; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; public class URLAddress implements Serializable { private static final long serialVersionUID = -1985165475234910535L; protected String host; protected int port; // cache protected transient String rawAddress; protected transient long timestamp; public URLAddress(String host, int port) { this(host, port, null); } public URLAddress(String host, int port, String rawAddress) { this.host = host; port = Math.max(port, 0); this.port = port; this.rawAddress = rawAddress; this.timestamp = System.currentTimeMillis(); } public String getProtocol() { return ""; } public URLAddress setProtocol(String protocol) { return this; } public String getUsername() { return ""; } public URLAddress setUsername(String username) { return this; } public String getPassword() { return ""; } public URLAddress setPassword(String password) { return this; } public String getPath() { return ""; } public URLAddress setPath(String path) { return this; } public String getHost() { return host; } public URLAddress setHost(String host) { return new URLAddress(host, port, null); } public int getPort() { return port; } public URLAddress setPort(int port) { return new URLAddress(host, port, null); } public String getAddress() { if (rawAddress == null) { rawAddress = getAddress(getHost(), getPort()); } return rawAddress; } public URLAddress setAddress(String host, int port) { return new URLAddress(host, port, rawAddress); } public String getIp() { return NetUtils.getIpByHost(getHost()); } public String getRawAddress() { return rawAddress; } protected String getAddress(String host, int port) { return port <= 0 ? host : host + ':' + port; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public int hashCode() { return host.hashCode() * 31 + port; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof URLAddress)) return false; URLAddress that = (URLAddress) obj; return Objects.equals(this.getProtocol(), that.getProtocol()) && Objects.equals(this.getUsername(), that.getUsername()) && Objects.equals(this.getPassword(), that.getPassword()) && Objects.equals(this.getPath(), that.getPath()) && Objects.equals(this.getHost(), that.getHost()) && Objects.equals(this.getPort(), that.getPort()); } @Override public String toString() { if (rawAddress != null) { return rawAddress; } StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(host)) { buf.append(host); if (port > 0) { buf.append(':'); buf.append(port); } } return buf.toString(); } public static URLAddress parse(String rawAddress, String defaultProtocol, boolean encoded) { try { String decodeStr = rawAddress; if (encoded) { decodeStr = URLDecoder.decode(rawAddress, "UTF-8"); } boolean isPathAddress = decodeStr.contains(PATH_SEPARATOR); if (isPathAddress) { return createPathURLAddress(decodeStr, rawAddress, defaultProtocol); } return createURLAddress(decodeStr, rawAddress, defaultProtocol); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } private static URLAddress createURLAddress(String decodeStr, String rawAddress, String defaultProtocol) { String host = null; int port = 0; int i = decodeStr.lastIndexOf(':'); if (i >= 0 && i < decodeStr.length() - 1) { if (decodeStr.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(decodeStr.substring(i + 1)); host = decodeStr.substring(0, i); } } else { host = decodeStr; } return new URLAddress(host, port, rawAddress); } private static PathURLAddress createPathURLAddress(String decodeStr, String rawAddress, String defaultProtocol) { String protocol = defaultProtocol; String path = null, username = null, password = null, host = null; int port = 0; int i = decodeStr.indexOf("://"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + decodeStr + "\""); } protocol = decodeStr.substring(0, i); decodeStr = decodeStr.substring(i + 3); } else { // case: file:/path/to/file.txt i = decodeStr.indexOf(":/"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + decodeStr + "\""); } protocol = decodeStr.substring(0, i); decodeStr = decodeStr.substring(i + 1); } } i = decodeStr.indexOf('/'); if (i >= 0) { path = decodeStr.substring(i + 1); decodeStr = decodeStr.substring(0, i); } i = decodeStr.lastIndexOf('@'); if (i >= 0) { username = decodeStr.substring(0, i); int j = username.indexOf(':'); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } decodeStr = decodeStr.substring(i + 1); } i = decodeStr.lastIndexOf(':'); if (i >= 0 && i < decodeStr.length() - 1) { if (decodeStr.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(decodeStr.substring(i + 1)); host = decodeStr.substring(0, i); } } // check cache protocol = URLItemCache.intern(protocol); path = URLItemCache.checkPath(path); return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } }
6,945
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.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.url.component; import java.io.Serializable; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Act like URLParam, will not use DynamicParamTable to compress parameters, * which can support serializer serialization and deserialization. * DynamicParamTable is environment hard related. */ public class URLPlainParam extends URLParam implements Serializable { private static final long serialVersionUID = 4722019979665434393L; protected URLPlainParam( BitSet key, int[] value, Map<String, String> extraParams, Map<String, Map<String, String>> methodParameters, String rawParam) { super(key, value, extraParams, methodParameters, rawParam); this.enableCompressed = false; } public static URLPlainParam toURLPlainParam(URLParam urlParam) { Map<String, String> params = Collections.unmodifiableMap(new HashMap<>(urlParam.getParameters())); return new URLPlainParam( new BitSet(), new int[0], params, urlParam.getMethodParameters(), urlParam.getRawParam()); } }
6,946
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLItemCache.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.url.component; import org.apache.dubbo.common.utils.LRUCache; import org.apache.dubbo.common.utils.StringUtils; import java.util.Map; public class URLItemCache { // thread safe with limited size, by default 1000 private static final Map<String, String> PARAM_KEY_CACHE = new LRUCache<>(10000); private static final Map<String, String> PARAM_VALUE_CACHE = new LRUCache<>(50000); private static final Map<String, String> PATH_CACHE = new LRUCache<>(10000); private static final Map<String, String> REVISION_CACHE = new LRUCache<>(10000); public static void putParams(Map<String, String> params, String key, String value) { String cachedKey = PARAM_KEY_CACHE.get(key); if (StringUtils.isBlank(cachedKey)) { cachedKey = key; PARAM_KEY_CACHE.put(key, key); } String cachedValue = PARAM_VALUE_CACHE.get(value); if (StringUtils.isBlank(cachedValue)) { cachedValue = value; PARAM_VALUE_CACHE.put(value, value); } params.put(cachedKey, cachedValue); } public static String checkPath(String path) { if (StringUtils.isBlank(path)) { return path; } String cachedPath = PATH_CACHE.putIfAbsent(path, path); if (StringUtils.isNotBlank(cachedPath)) { return cachedPath; } return path; } public static String checkRevision(String revision) { if (StringUtils.isBlank(revision)) { return revision; } String cachedRevision = REVISION_CACHE.putIfAbsent(revision, revision); if (StringUtils.isNotBlank(cachedRevision)) { return cachedRevision; } return revision; } public static String intern(String protocol) { if (StringUtils.isBlank(protocol)) { return protocol; } return protocol.intern(); } public static void putParamsIntern(Map<String, String> params, String key, String value) { if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) { params.put(key, value); return; } key = key.intern(); value = value.intern(); params.put(key, value); } }
6,947
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLStrParser; import org.apache.dubbo.common.url.component.param.DynamicParamTable; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.AbstractMap; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.StringJoiner; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; /** * A class which store parameters for {@link URL} * <br/> * Using {@link DynamicParamTable} to compress common keys (i.e. side, version) * <br/> * {@link DynamicParamTable} allow to use only two integer value named `key` and * `value-offset` to find a unique string to string key-pair. Also, `value-offset` * is not required if the real value is the default value. * <br/> * URLParam should operate as Copy-On-Write, each modify actions will return a new Object * <br/> * <p> * NOTE: URLParam is not support serialization! {@link DynamicParamTable} is related with * current running environment. If you want to make URL as a parameter, please call * {@link URL#toSerializableURL()} to create {@link URLPlainParam} instead. * * @since 3.0 */ public class URLParam { /** * Maximum size of key-pairs requested using array moving to add into URLParam. * If user request like addParameter for only one key-pair, adding value into a array * on moving is more efficient. However when add more than ADD_PARAMETER_ON_MOVE_THRESHOLD * size of key-pairs, recover compressed array back to map can reduce operation count * when putting objects. */ private static final int ADD_PARAMETER_ON_MOVE_THRESHOLD = 1; /** * the original parameters string, empty if parameters have been modified or init by {@link Map} */ private final String rawParam; /** * using bit to save if index exist even if value is default value */ private final BitSet KEY; /** * an array which contains value-offset */ private final int[] VALUE; /** * store extra parameters which key not match in {@link DynamicParamTable} */ private final Map<String, String> EXTRA_PARAMS; /** * store method related parameters * <p> * K - key * V - * K - method * V - value * <p> * e.g. method1.mock=true => ( mock, (method1, true) ) */ private final Map<String, Map<String, String>> METHOD_PARAMETERS; private transient long timestamp; /** * Whether to enable DynamicParamTable compression */ protected boolean enableCompressed; private static final URLParam EMPTY_PARAM = new URLParam(new BitSet(0), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), ""); protected URLParam() { this.rawParam = null; this.KEY = null; this.VALUE = null; this.EXTRA_PARAMS = null; this.METHOD_PARAMETERS = null; this.enableCompressed = true; } protected URLParam( BitSet key, Map<Integer, Integer> value, Map<String, String> extraParams, Map<String, Map<String, String>> methodParameters, String rawParam) { this.KEY = key; this.VALUE = new int[value.size()]; for (int i = key.nextSetBit(0), offset = 0; i >= 0; i = key.nextSetBit(i + 1)) { if (value.containsKey(i)) { VALUE[offset++] = value.get(i); } else { throw new IllegalArgumentException(); } } this.EXTRA_PARAMS = Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); this.METHOD_PARAMETERS = Collections.unmodifiableMap( (methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); this.rawParam = rawParam; this.timestamp = System.currentTimeMillis(); this.enableCompressed = true; } protected URLParam( BitSet key, int[] value, Map<String, String> extraParams, Map<String, Map<String, String>> methodParameters, String rawParam) { this.KEY = key; this.VALUE = value; this.EXTRA_PARAMS = Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); this.METHOD_PARAMETERS = Collections.unmodifiableMap( (methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); this.rawParam = rawParam; this.timestamp = System.currentTimeMillis(); this.enableCompressed = true; } /** * Weather there contains some parameter match method * * @param method method name * @return contains or not */ public boolean hasMethodParameter(String method) { if (method == null) { return false; } String methodsString = getParameter(METHODS_KEY); if (StringUtils.isNotEmpty(methodsString)) { if (!methodsString.contains(method)) { return false; } } for (Map.Entry<String, Map<String, String>> methods : METHOD_PARAMETERS.entrySet()) { if (methods.getValue().containsKey(method)) { return true; } } return false; } /** * Get method related parameter. If not contains, use getParameter(key) instead. * Specially, in some situation like `method1.1.callback=true`, key is `1.callback`. * * @param method method name * @param key key * @return value */ public String getMethodParameter(String method, String key) { String strictResult = getMethodParameterStrict(method, key); return StringUtils.isNotEmpty(strictResult) ? strictResult : getParameter(key); } /** * Get method related parameter. If not contains, return null. * Specially, in some situation like `method1.1.callback=true`, key is `1.callback`. * * @param method method name * @param key key * @return value */ public String getMethodParameterStrict(String method, String key) { String methodsString = getParameter(METHODS_KEY); if (StringUtils.isNotEmpty(methodsString)) { if (!methodsString.contains(method)) { return null; } } Map<String, String> methodMap = METHOD_PARAMETERS.get(key); if (CollectionUtils.isNotEmptyMap(methodMap)) { return methodMap.get(method); } else { return null; } } public static Map<String, Map<String, String>> initMethodParameters(Map<String, String> parameters) { Map<String, Map<String, String>> methodParameters = new HashMap<>(); if (parameters == null) { return methodParameters; } String methodsString = parameters.get(METHODS_KEY); if (StringUtils.isNotEmpty(methodsString)) { String[] methods = methodsString.split(","); for (Map.Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); for (String method : methods) { String methodPrefix = method + '.'; if (key.startsWith(methodPrefix)) { String realKey = key.substring(methodPrefix.length()); URL.putMethodParameter(method, realKey, entry.getValue(), methodParameters); } } } } else { for (Map.Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); int methodSeparator = key.indexOf('.'); if (methodSeparator > 0) { String method = key.substring(0, methodSeparator); String realKey = key.substring(methodSeparator + 1); URL.putMethodParameter(method, realKey, entry.getValue(), methodParameters); } } } return methodParameters; } /** * An embedded Map adapt to URLParam * <br/> * copy-on-write mode, urlParam reference will be changed after modify actions. * If wishes to get the result after modify, please use {@link URLParamMap#getUrlParam()} */ public static class URLParamMap extends AbstractMap<String, String> { private URLParam urlParam; public URLParamMap(URLParam urlParam) { this.urlParam = urlParam; } public static class Node implements Map.Entry<String, String> { private final String key; private String value; public Node(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public String getValue() { return value; } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return Objects.equals(key, node.key) && Objects.equals(value, node.value); } @Override public int hashCode() { return Objects.hash(key, value); } } @Override public int size() { return urlParam.KEY.cardinality() + urlParam.EXTRA_PARAMS.size(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(Object key) { if (key instanceof String) { return urlParam.hasParameter((String) key); } else { return false; } } @Override public boolean containsValue(Object value) { return values().contains(value); } @Override public String get(Object key) { if (key instanceof String) { return urlParam.getParameter((String) key); } else { return null; } } @Override public String put(String key, String value) { String previous = urlParam.getParameter(key); urlParam = urlParam.addParameter(key, value); return previous; } @Override public String remove(Object key) { if (key instanceof String) { String previous = urlParam.getParameter((String) key); urlParam = urlParam.removeParameters((String) key); return previous; } else { return null; } } @Override public void putAll(Map<? extends String, ? extends String> m) { urlParam = urlParam.addParameters((Map<String, String>) m); } @Override public void clear() { urlParam = urlParam.clearParameters(); } @Override public Set<String> keySet() { Set<String> set = new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { set.add(DynamicParamTable.getKey(i)); } for (Entry<String, String> entry : urlParam.EXTRA_PARAMS.entrySet()) { set.add(entry.getKey()); } return Collections.unmodifiableSet(set); } @Override public Collection<String> values() { Set<String> set = new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { String value; int offset = urlParam.keyIndexToOffset(i); value = DynamicParamTable.getValue(i, offset); set.add(value); } for (Entry<String, String> entry : urlParam.EXTRA_PARAMS.entrySet()) { set.add(entry.getValue()); } return Collections.unmodifiableSet(set); } @Override public Set<Entry<String, String>> entrySet() { Set<Entry<String, String>> set = new LinkedHashSet<>((int) ((urlParam.KEY.cardinality() + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { String value; int offset = urlParam.keyIndexToOffset(i); value = DynamicParamTable.getValue(i, offset); set.add(new Node(DynamicParamTable.getKey(i), value)); } for (Entry<String, String> entry : urlParam.EXTRA_PARAMS.entrySet()) { set.add(new Node(entry.getKey(), entry.getValue())); } return Collections.unmodifiableSet(set); } public URLParam getUrlParam() { return urlParam; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } URLParamMap that = (URLParamMap) o; return Objects.equals(urlParam, that.urlParam); } @Override public int hashCode() { return Objects.hash(urlParam); } } /** * Get a Map like URLParam * * @return a {@link URLParamMap} adapt to URLParam */ public Map<String, String> getParameters() { return new URLParamMap(this); } /** * Get any method related parameter which match key * * @param key key * @return result ( if any, random choose one ) */ public String getAnyMethodParameter(String key) { Map<String, String> methodMap = METHOD_PARAMETERS.get(key); if (CollectionUtils.isNotEmptyMap(methodMap)) { String methods = getParameter(METHODS_KEY); if (StringUtils.isNotEmpty(methods)) { for (String method : methods.split(",")) { String value = methodMap.get(method); if (StringUtils.isNotEmpty(value)) { return value; } } } else { return methodMap.values().iterator().next(); } } return null; } /** * Add parameters to a new URLParam. * * @param key key * @param value value * @return A new URLParam */ public URLParam addParameter(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } return addParameters(Collections.singletonMap(key, value)); } /** * Add absent parameters to a new URLParam. * * @param key key * @param value value * @return A new URLParam */ public URLParam addParameterIfAbsent(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } if (hasParameter(key)) { return this; } return addParametersIfAbsent(Collections.singletonMap(key, value)); } /** * Add parameters to a new URLParam. * If key-pair is present, this will cover it. * * @param parameters parameters in key-value pairs * @return A new URLParam */ public URLParam addParameters(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } boolean hasAndEqual = true; Map<String, String> urlParamMap = getParameters(); for (Map.Entry<String, String> entry : parameters.entrySet()) { String value = urlParamMap.get(entry.getKey()); if (value == null) { if (entry.getValue() != null) { hasAndEqual = false; break; } } else { if (!value.equals(entry.getValue())) { hasAndEqual = false; break; } } } // return immediately if there's no change if (hasAndEqual) { return this; } return doAddParameters(parameters, false); } /** * Add absent parameters to a new URLParam. * * @param parameters parameters in key-value pairs * @return A new URL */ public URLParam addParametersIfAbsent(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } return doAddParameters(parameters, true); } private URLParam doAddParameters(Map<String, String> parameters, boolean skipIfPresent) { // lazy init, null if no modify BitSet newKey = null; int[] newValueArray = null; Map<Integer, Integer> newValueMap = null; Map<String, String> newExtraParams = null; Map<String, Map<String, String>> newMethodParams = null; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (skipIfPresent && hasParameter(entry.getKey())) { continue; } if (entry.getKey() == null || entry.getValue() == null) { continue; } int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, entry.getKey()); if (keyIndex < 0) { // entry key is not present in DynamicParamTable, add it to EXTRA_PARAMS if (newExtraParams == null) { newExtraParams = new HashMap<>(EXTRA_PARAMS); } newExtraParams.put(entry.getKey(), entry.getValue()); String[] methodSplit = entry.getKey().split("\\."); if (methodSplit.length == 2) { if (newMethodParams == null) { newMethodParams = new HashMap<>(METHOD_PARAMETERS); } Map<String, String> methodMap = newMethodParams.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); methodMap.put(methodSplit[0], entry.getValue()); } } else { if (KEY.get(keyIndex)) { // contains key, replace value if (parameters.size() > ADD_PARAMETER_ON_MOVE_THRESHOLD) { // recover VALUE back to Map, use map to replace key pair if (newValueMap == null) { newValueMap = recoverValue(); } newValueMap.put(keyIndex, DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } else { newValueArray = replaceOffset( VALUE, keyIndexToIndex(KEY, keyIndex), DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } } else { // key is absent, add it if (newKey == null) { newKey = (BitSet) KEY.clone(); } newKey.set(keyIndex); if (parameters.size() > ADD_PARAMETER_ON_MOVE_THRESHOLD) { // recover VALUE back to Map if (newValueMap == null) { newValueMap = recoverValue(); } newValueMap.put(keyIndex, DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } else { // add parameter by moving array, only support for adding once newValueArray = addByMove( VALUE, keyIndexToIndex(newKey, keyIndex), DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } } } } if (newKey == null) { newKey = KEY; } if (newValueArray == null && newValueMap == null) { newValueArray = VALUE; } if (newExtraParams == null) { newExtraParams = EXTRA_PARAMS; } if (newMethodParams == null) { newMethodParams = METHOD_PARAMETERS; } if (newValueMap == null) { return new URLParam(newKey, newValueArray, newExtraParams, newMethodParams, null); } else { return new URLParam(newKey, newValueMap, newExtraParams, newMethodParams, null); } } private Map<Integer, Integer> recoverValue() { Map<Integer, Integer> map = new HashMap<>((int) (KEY.size() / 0.75) + 1); for (int i = KEY.nextSetBit(0), offset = 0; i >= 0; i = KEY.nextSetBit(i + 1)) { map.put(i, VALUE[offset++]); } return map; } private int[] addByMove(int[] array, int index, Integer value) { if (index < 0 || index > array.length) { throw new IllegalArgumentException(); } // copy-on-write int[] result = new int[array.length + 1]; System.arraycopy(array, 0, result, 0, index); result[index] = value; System.arraycopy(array, index, result, index + 1, array.length - index); return result; } private int[] replaceOffset(int[] array, int index, Integer value) { if (index < 0 || index > array.length) { throw new IllegalArgumentException(); } // copy-on-write int[] result = new int[array.length]; System.arraycopy(array, 0, result, 0, array.length); result[index] = value; return result; } /** * remove specified parameters in URLParam * * @param keys keys to being removed * @return A new URLParam */ public URLParam removeParameters(String... keys) { if (keys == null || keys.length == 0) { return this; } // lazy init, null if no modify BitSet newKey = null; int[] newValueArray = null; Map<String, String> newExtraParams = null; Map<String, Map<String, String>> newMethodParams = null; for (String key : keys) { int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, key); if (keyIndex >= 0 && KEY.get(keyIndex)) { if (newKey == null) { newKey = (BitSet) KEY.clone(); } newKey.clear(keyIndex); // which offset is in VALUE array, set value as -1, compress in the end if (newValueArray == null) { newValueArray = new int[VALUE.length]; System.arraycopy(VALUE, 0, newValueArray, 0, VALUE.length); } // KEY is immutable newValueArray[keyIndexToIndex(KEY, keyIndex)] = -1; } if (EXTRA_PARAMS.containsKey(key)) { if (newExtraParams == null) { newExtraParams = new HashMap<>(EXTRA_PARAMS); } newExtraParams.remove(key); String[] methodSplit = key.split("\\."); if (methodSplit.length == 2) { if (newMethodParams == null) { newMethodParams = new HashMap<>(METHOD_PARAMETERS); } Map<String, String> methodMap = newMethodParams.get(methodSplit[1]); if (CollectionUtils.isNotEmptyMap(methodMap)) { methodMap.remove(methodSplit[0]); } } } // ignore if key is absent } if (newKey == null) { newKey = KEY; } if (newValueArray == null) { newValueArray = VALUE; } else { // remove -1 value newValueArray = compressArray(newValueArray); } if (newExtraParams == null) { newExtraParams = EXTRA_PARAMS; } if (newMethodParams == null) { newMethodParams = METHOD_PARAMETERS; } if (newKey.cardinality() + newExtraParams.size() == 0) { // empty, directly return cache return EMPTY_PARAM; } else { return new URLParam(newKey, newValueArray, newExtraParams, newMethodParams, null); } } private int[] compressArray(int[] array) { int total = 0; for (int i : array) { if (i > -1) { total++; } } if (total == 0) { return new int[0]; } int[] result = new int[total]; for (int i = 0, offset = 0; i < array.length; i++) { // skip if value if less than 0 if (array[i] > -1) { result[offset++] = array[i]; } } return result; } /** * remove all of the parameters in URLParam * * @return An empty URLParam */ public URLParam clearParameters() { return EMPTY_PARAM; } /** * check if specified key is present in URLParam * * @param key specified key * @return present or not */ public boolean hasParameter(String key) { int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, key); if (keyIndex < 0) { return EXTRA_PARAMS.containsKey(key); } return KEY.get(keyIndex); } /** * get value of specified key in URLParam * * @param key specified key * @return value, null if key is absent */ public String getParameter(String key) { int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, key); if (keyIndex < 0) { return EXTRA_PARAMS.get(key); } if (KEY.get(keyIndex)) { String value; int offset = keyIndexToOffset(keyIndex); value = DynamicParamTable.getValue(keyIndex, offset); return value; // if (StringUtils.isEmpty(value)) { // // Forward compatible, make sure key dynamic increment can work. // // In that case, some values which are proceed before increment will set in EXTRA_PARAMS. // return EXTRA_PARAMS.get(key); // } else { // return value; // } } return null; } private int keyIndexToIndex(BitSet key, int keyIndex) { return key.get(0, keyIndex).cardinality(); } private int keyIndexToOffset(int keyIndex) { int arrayOffset = keyIndexToIndex(KEY, keyIndex); return VALUE[arrayOffset]; } /** * get raw string like parameters * * @return raw string like parameters */ public String getRawParam() { if (StringUtils.isNotEmpty(rawParam)) { return rawParam; } else { // empty if parameters have been modified or init by Map return toString(); } } protected Map<String, Map<String, String>> getMethodParameters() { return METHOD_PARAMETERS; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } URLParam urlParam = (URLParam) o; if (Objects.equals(KEY, urlParam.KEY) && Arrays.equals(VALUE, urlParam.VALUE)) { if (CollectionUtils.isNotEmptyMap(EXTRA_PARAMS)) { if (CollectionUtils.isEmptyMap(urlParam.EXTRA_PARAMS) || EXTRA_PARAMS.size() != urlParam.EXTRA_PARAMS.size()) { return false; } for (Map.Entry<String, String> entry : EXTRA_PARAMS.entrySet()) { if (TIMESTAMP_KEY.equals(entry.getKey())) { continue; } if (!entry.getValue().equals(urlParam.EXTRA_PARAMS.get(entry.getKey()))) { return false; } } return true; } return CollectionUtils.isEmptyMap(urlParam.EXTRA_PARAMS); } return false; } private int hashCodeCache = -1; @Override public int hashCode() { if (hashCodeCache == -1) { for (Map.Entry<String, String> entry : EXTRA_PARAMS.entrySet()) { if (!TIMESTAMP_KEY.equals(entry.getKey())) { hashCodeCache = hashCodeCache * 31 + Objects.hashCode(entry); } } for (Integer value : VALUE) { hashCodeCache = hashCodeCache * 31 + value; } hashCodeCache = hashCodeCache * 31 + ((KEY == null) ? 0 : KEY.hashCode()); } return hashCodeCache; } @Override public String toString() { if (StringUtils.isNotEmpty(rawParam)) { return rawParam; } if ((KEY.cardinality() + EXTRA_PARAMS.size()) == 0) { return ""; } StringJoiner stringJoiner = new StringJoiner("&"); for (int i = KEY.nextSetBit(0); i >= 0; i = KEY.nextSetBit(i + 1)) { String key = DynamicParamTable.getKey(i); String value = DynamicParamTable.getValue(i, keyIndexToOffset(i)); value = value == null ? "" : value.trim(); stringJoiner.add(String.format("%s=%s", key, value)); } for (Map.Entry<String, String> entry : EXTRA_PARAMS.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); value = value == null ? "" : value.trim(); stringJoiner.add(String.format("%s=%s", key, value)); } return stringJoiner.toString(); } /** * Parse URLParam * Init URLParam by constructor is not allowed * rawParam field in result will be null while {@link URLParam#getRawParam()} will automatically create it * * @param params params map added into URLParam * @return a new URLParam */ public static URLParam parse(Map<String, String> params) { return parse(params, null); } /** * Parse URLParam * Init URLParam by constructor is not allowed * * @param rawParam original rawParam string * @param encoded if parameters are URL encoded * @param extraParameters extra parameters to add into URLParam * @return a new URLParam */ public static URLParam parse(String rawParam, boolean encoded, Map<String, String> extraParameters) { Map<String, String> parameters = URLStrParser.parseParams(rawParam, encoded); if (CollectionUtils.isNotEmptyMap(extraParameters)) { parameters.putAll(extraParameters); } return parse(parameters, rawParam); } /** * Parse URLParam * Init URLParam by constructor is not allowed * * @param rawParam original rawParam string * @return a new URLParam */ public static URLParam parse(String rawParam) { String[] parts = rawParam.split("&"); int capacity = (int) (parts.length / .75f) + 1; BitSet keyBit = new BitSet(capacity); Map<Integer, Integer> valueMap = new HashMap<>(capacity); Map<String, String> extraParam = new HashMap<>(capacity); Map<String, Map<String, String>> methodParameters = new HashMap<>(capacity); 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); addParameter(keyBit, valueMap, extraParam, methodParameters, key, value, false); // compatible with lower versions registering "default." keys if (key.startsWith(DEFAULT_KEY_PREFIX)) { addParameter( keyBit, valueMap, extraParam, methodParameters, key.substring(DEFAULT_KEY_PREFIX.length()), value, true); } } else { addParameter(keyBit, valueMap, extraParam, methodParameters, part, part, false); } } } return new URLParam(keyBit, valueMap, extraParam, methodParameters, rawParam); } /** * Parse URLParam * Init URLParam by constructor is not allowed * * @param params params map added into URLParam * @param rawParam original rawParam string, directly add to rawParam field, * will not affect real key-pairs store in URLParam. * Please make sure it can correspond with params or will * cause unexpected result when calling {@link URLParam#getRawParam()} * and {@link URLParam#toString()} ()}. If you not sure, you can call * {@link URLParam#parse(String)} to init. * @return a new URLParam */ public static URLParam parse(Map<String, String> params, String rawParam) { if (CollectionUtils.isNotEmptyMap(params)) { int capacity = (int) (params.size() / .75f) + 1; BitSet keyBit = new BitSet(capacity); Map<Integer, Integer> valueMap = new HashMap<>(capacity); Map<String, String> extraParam = new HashMap<>(capacity); Map<String, Map<String, String>> methodParameters = new HashMap<>(capacity); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); addParameter(keyBit, valueMap, extraParam, methodParameters, key, value, false); // compatible with lower versions registering "default." keys if (key.startsWith(DEFAULT_KEY_PREFIX)) { addParameter( keyBit, valueMap, extraParam, methodParameters, key.substring(DEFAULT_KEY_PREFIX.length()), value, true); } } return new URLParam(keyBit, valueMap, extraParam, methodParameters, rawParam); } else { return EMPTY_PARAM; } } private static void addParameter( BitSet keyBit, Map<Integer, Integer> valueMap, Map<String, String> extraParam, Map<String, Map<String, String>> methodParameters, String key, String value, boolean skipIfPresent) { int keyIndex = DynamicParamTable.getKeyIndex(true, key); if (skipIfPresent) { if (keyIndex < 0) { if (extraParam.containsKey(key)) { return; } } else { if (keyBit.get(keyIndex)) { return; } } } if (keyIndex < 0) { extraParam.put(key, value); String[] methodSplit = key.split("\\.", 2); if (methodSplit.length == 2) { Map<String, String> methodMap = methodParameters.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); methodMap.put(methodSplit[0], value); } } else { valueMap.put(keyIndex, DynamicParamTable.getValueIndex(key, value)); keyBit.set(keyIndex); } } }
6,948
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicValues.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.url.component.param; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DynamicValues implements ParamValue { private volatile String[] index2Value = new String[1]; private final Map<String, Integer> value2Index = new ConcurrentHashMap<>(); private int indexSeq = 0; public DynamicValues(String defaultVal) { if (defaultVal == null) { indexSeq += 1; } else { add(defaultVal); } } public int add(String value) { Integer index = value2Index.get(value); if (index != null) { return index; } else { synchronized (this) { // thread safe if (!value2Index.containsKey(value)) { if (indexSeq == Integer.MAX_VALUE) { throw new IllegalStateException("URL Param Cache is full."); } // copy on write, only support append now String[] newValues = new String[indexSeq + 1]; System.arraycopy(index2Value, 0, newValues, 0, indexSeq); newValues[indexSeq] = value; index2Value = newValues; value2Index.put(value, indexSeq); indexSeq += 1; } } } return value2Index.get(value); } @Override public String getN(int n) { if (n == -1) { return null; } return index2Value[n]; } @Override public int getIndex(String value) { if (value == null) { return -1; } Integer index = value2Index.get(value); if (index == null) { return add(value); } return index; } }
6,949
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.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.url.component.param; import java.util.HashSet; public class IgnoredParam { private static final HashSet<String> IGNORED = new HashSet<>(); static { IGNORED.add("timestamp"); } static boolean ignore(String key) { return IGNORED.contains(key); } }
6,950
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.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.url.component.param; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * In lower case */ public class FixedParamValue implements ParamValue { private final String[] values; private final Map<String, Integer> val2Index; public FixedParamValue(String... values) { if (values.length == 0) { throw new IllegalArgumentException("the array size of values should be larger than 0"); } this.values = values; Map<String, Integer> valueMap = new HashMap<>(values.length); for (int i = 0; i < values.length; i++) { if (values[i] != null) { valueMap.put(values[i].toLowerCase(Locale.ROOT), i); } } val2Index = Collections.unmodifiableMap(valueMap); } /** * DEFAULT value will be returned if n = 0 * @param n */ @Override public String getN(int n) { return values[n]; } @Override public int getIndex(String value) { Integer offset = val2Index.get(value.toLowerCase(Locale.ROOT)); if (offset == null) { throw new IllegalArgumentException("unrecognized value " + value + " , please check if value is illegal. " + "Permitted values: " + Arrays.asList(values)); } return offset; } }
6,951
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DefaultDynamicParamSource.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.url.component.param; import org.apache.dubbo.common.constants.CommonConstants; import java.util.List; public class DefaultDynamicParamSource implements DynamicParamSource { @Override public void init(List<String> keys, List<ParamValue> values) { keys.add(CommonConstants.VERSION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.SIDE_KEY); values.add(new FixedParamValue(CommonConstants.CONSUMER_SIDE, CommonConstants.PROVIDER_SIDE)); keys.add(CommonConstants.INTERFACE_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.PID_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.THREADPOOL_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.GROUP_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.VERSION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.METADATA_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.APPLICATION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.DUBBO_VERSION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.RELEASE_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.PATH_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.ANYHOST_KEY); values.add(new DynamicValues(null)); } }
6,952
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.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.url.component.param; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Global Param Cache Table * Not support method parameters */ public final class DynamicParamTable { /** * Keys array, value is string */ private static String[] ORIGIN_KEYS; private static ParamValue[] VALUES; private static final Map<String, Integer> KEY2INDEX = new HashMap<>(64); private DynamicParamTable() { throw new IllegalStateException(); } static { init(); } public static int getKeyIndex(boolean enabled, String key) { if (!enabled) { return -1; } Integer indexFromMap = KEY2INDEX.get(key); return indexFromMap == null ? -1 : indexFromMap; } public static int getValueIndex(String key, String value) { int idx = getKeyIndex(true, key); if (idx < 0) { throw new IllegalArgumentException("Cannot found key in url param:" + key); } ParamValue paramValue = VALUES[idx]; return paramValue.getIndex(value); } public static String getKey(int offset) { return ORIGIN_KEYS[offset]; } public static String getValue(int vi, int offset) { return VALUES[vi].getN(offset); } private static void init() { List<String> keys = new LinkedList<>(); List<ParamValue> values = new LinkedList<>(); Map<String, Integer> key2Index = new HashMap<>(64); keys.add(""); values.add(new DynamicValues(null)); FrameworkModel.defaultModel() .getExtensionLoader(DynamicParamSource.class) .getSupportedExtensionInstances() .forEach(source -> source.init(keys, values)); TreeMap<String, ParamValue> resultMap = new TreeMap<>(Comparator.comparingInt(System::identityHashCode)); for (int i = 0; i < keys.size(); i++) { resultMap.put(keys.get(i), values.get(i)); } ORIGIN_KEYS = resultMap.keySet().toArray(new String[0]); VALUES = resultMap.values().toArray(new ParamValue[0]); for (int i = 0; i < ORIGIN_KEYS.length; i++) { key2Index.put(ORIGIN_KEYS[i], i); } KEY2INDEX.putAll(key2Index); } }
6,953
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamSource.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.url.component.param; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.List; @SPI(scope = ExtensionScope.FRAMEWORK) public interface DynamicParamSource { void init(List<String> keys, List<ParamValue> values); }
6,954
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.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.url.component.param; public interface ParamValue { /** * get value at the specified index. * * @param n the nth value * @return the value stored at index = n */ String getN(int n); /** * max index is 2^31 - 1 * * @param value the stored value * @return the index of value */ int getIndex(String value); }
6,955
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/lang/Prioritized.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.lang; import java.util.Comparator; import static java.lang.Integer.compare; /** * {@code Prioritized} interface can be implemented by objects that * should be sorted, for example the tasks in executable queue. * * @since 2.7.5 */ public interface Prioritized extends Comparable<Prioritized> { /** * The {@link Comparator} of {@link Prioritized} */ Comparator<Object> COMPARATOR = (one, two) -> { boolean b1 = one instanceof Prioritized; boolean b2 = two instanceof Prioritized; if (b1 && !b2) { // one is Prioritized, two is not return -1; } else if (b2 && !b1) { // two is Prioritized, one is not return 1; } else if (b1 && b2) { // one and two both are Prioritized return ((Prioritized) one).compareTo((Prioritized) two); } else { // no different return 0; } }; /** * The maximum priority */ int MAX_PRIORITY = Integer.MIN_VALUE; /** * The minimum priority */ int MIN_PRIORITY = Integer.MAX_VALUE; /** * Normal Priority */ int NORMAL_PRIORITY = 0; /** * Get the priority * * @return the default is {@link #NORMAL_PRIORITY} */ default int getPriority() { return NORMAL_PRIORITY; } @Override default int compareTo(Prioritized that) { return compare(this.getPriority(), that.getPriority()); } }
6,956
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/lang/ShutdownHookCallbacks.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.lang; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static java.util.Collections.sort; import static org.apache.dubbo.common.function.ThrowableAction.execute; /** * The composed {@link ShutdownHookCallback} class to manipulate one and more {@link ShutdownHookCallback} instances * * @since 2.7.5 */ public class ShutdownHookCallbacks implements Disposable { private final List<ShutdownHookCallback> callbacks = new LinkedList<>(); private final ApplicationModel applicationModel; public ShutdownHookCallbacks(ApplicationModel applicationModel) { this.applicationModel = applicationModel; loadCallbacks(); } public ShutdownHookCallbacks addCallback(ShutdownHookCallback callback) { synchronized (this) { if (!callbacks.contains(callback)) { this.callbacks.add(callback); } } return this; } public Collection<ShutdownHookCallback> getCallbacks() { synchronized (this) { sort(this.callbacks); return this.callbacks; } } public void destroy() { synchronized (this) { callbacks.clear(); } } private void loadCallbacks() { ExtensionLoader<ShutdownHookCallback> loader = applicationModel.getExtensionLoader(ShutdownHookCallback.class); loader.getSupportedExtensionInstances().forEach(this::addCallback); } public void callback() { getCallbacks().forEach(callback -> execute(callback::callback)); } }
6,957
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/lang/ShutdownHookCallback.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.lang; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * A callback interface invoked when Dubbo application is stopped. * <p>Note: This class is not directly related to Java ShutdownHook.</p> * <p/> * <p>Call chains:</p> * <ol> * <li>Java Shutdown Hook -> ApplicationDeployer.destroy() -> execute ShutdownHookCallback</li> * <li>Stop dubbo application -> ApplicationDeployer.destroy() -> execute ShutdownHookCallback</li> * </ol> * * @since 2.7.5 * @see org.apache.dubbo.common.deploy.ApplicationDeployListener * @see org.apache.dubbo.rpc.model.ScopeModelDestroyListener */ @SPI(scope = ExtensionScope.APPLICATION) public interface ShutdownHookCallback extends Prioritized { /** * Callback execution * * @throws Throwable if met with some errors */ void callback() throws Throwable; }
6,958
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/lang/Nullable.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.lang; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Nullable {}
6,959
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/system/OperatingSystemBeanManager.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.system; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.MethodUtils; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Objects; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; /** * OperatingSystemBeanManager related. */ public class OperatingSystemBeanManager { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(OperatingSystemBeanManager.class); /** * com.ibm for J9 * com.sun for HotSpot */ private static final List<String> OPERATING_SYSTEM_BEAN_CLASS_NAMES = Arrays.asList("com.sun.management.OperatingSystemMXBean", "com.ibm.lang.management.OperatingSystemMXBean"); private static final OperatingSystemMXBean OPERATING_SYSTEM_BEAN; private static final Class<?> OPERATING_SYSTEM_BEAN_CLASS; private static final Method SYSTEM_CPU_USAGE_METHOD; private static final Method PROCESS_CPU_USAGE_METHOD; static { OPERATING_SYSTEM_BEAN = ManagementFactory.getOperatingSystemMXBean(); OPERATING_SYSTEM_BEAN_CLASS = loadOne(OPERATING_SYSTEM_BEAN_CLASS_NAMES); SYSTEM_CPU_USAGE_METHOD = deduceMethod("getSystemCpuLoad"); PROCESS_CPU_USAGE_METHOD = deduceMethod("getProcessCpuLoad"); } private OperatingSystemBeanManager() {} public static OperatingSystemMXBean getOperatingSystemBean() { return OPERATING_SYSTEM_BEAN; } public static double getSystemCpuUsage() { return MethodUtils.invokeAndReturnDouble(SYSTEM_CPU_USAGE_METHOD, OPERATING_SYSTEM_BEAN); } public static double getProcessCpuUsage() { return MethodUtils.invokeAndReturnDouble(PROCESS_CPU_USAGE_METHOD, OPERATING_SYSTEM_BEAN); } private static Class<?> loadOne(List<String> classNames) { for (String className : classNames) { try { return Class.forName(className); } catch (ClassNotFoundException e) { LOGGER.warn( COMMON_CLASS_NOT_FOUND, "", "", "[OperatingSystemBeanManager] Failed to load operating system bean class.", e); } } return null; } private static Method deduceMethod(String name) { if (Objects.isNull(OPERATING_SYSTEM_BEAN_CLASS)) { return null; } try { OPERATING_SYSTEM_BEAN_CLASS.cast(OPERATING_SYSTEM_BEAN); return OPERATING_SYSTEM_BEAN_CLASS.getDeclaredMethod(name); } catch (Exception e) { return null; } } }
6,960
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/json/JSON.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.json; import java.lang.reflect.Type; import java.util.List; import java.util.Map; public interface JSON { boolean isSupport(); <T> T toJavaObject(String json, Type type); <T> List<T> toJavaList(String json, Class<T> clazz); String toJson(Object obj); List<?> getList(Map<String, ?> obj, String key); List<Map<String, ?>> getListOfObjects(Map<String, ?> obj, String key); List<String> getListOfStrings(Map<String, ?> obj, String key); Map<String, ?> getObject(Map<String, ?> obj, String key); Double getNumberAsDouble(Map<String, ?> obj, String key); Integer getNumberAsInteger(Map<String, ?> obj, String key); Long getNumberAsLong(Map<String, ?> obj, String key); String getString(Map<String, ?> obj, String key); List<Map<String, ?>> checkObjectList(List<?> rawList); List<String> checkStringList(List<?> rawList); }
6,961
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/json/GsonUtils.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.json; import org.apache.dubbo.common.utils.ClassUtils; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_GSON; public class GsonUtils { // weak reference of com.google.gson.Gson, prevent throw exception when init private static volatile Object gsonCache = null; private static volatile Boolean supportGson; private static boolean isSupportGson() { if (supportGson == null) { synchronized (GsonUtils.class) { if (supportGson == null) { try { Class<?> aClass = ClassUtils.forName("com.google.gson.Gson"); supportGson = aClass != null; } catch (Throwable t) { supportGson = false; } } } } return supportGson; } public static Object fromJson(String json, Type originType) throws RuntimeException { if (!isSupportGson()) { throw new RuntimeException("Gson is not supported. Please import Gson in JVM env."); } Type type = TypeToken.get(originType).getType(); try { return getGson().fromJson(json, type); } catch (JsonSyntaxException ex) { throw new RuntimeException(String.format( "Generic serialization [%s] Json syntax exception thrown when parsing (message:%s type:%s) error:%s", GENERIC_SERIALIZATION_GSON, json, type.toString(), ex.getMessage())); } } private static Gson getGson() { if (gsonCache == null || !(gsonCache instanceof Gson)) { synchronized (GsonUtils.class) { if (gsonCache == null || !(gsonCache instanceof Gson)) { gsonCache = new Gson(); } } } return (Gson) gsonCache; } /** * @deprecated for uts only */ @Deprecated protected static void setSupportGson(Boolean supportGson) { GsonUtils.supportGson = supportGson; } }
6,962
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.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.json.impl; import java.lang.reflect.Type; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class GsonImpl extends AbstractJSONImpl { // weak reference of com.google.gson.Gson, prevent throw exception when init private volatile Object gsonCache = null; @Override public <T> T toJavaObject(String json, Type type) { return getGson().fromJson(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { return getGson() .fromJson(json, TypeToken.getParameterized(List.class, clazz).getType()); } @Override public String toJson(Object obj) { return getGson().toJson(obj); } private Gson getGson() { if (gsonCache == null || !(gsonCache instanceof Gson)) { synchronized (this) { if (gsonCache == null || !(gsonCache instanceof Gson)) { gsonCache = new Gson(); } } } return (Gson) gsonCache; } }
6,963
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.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.json.impl; import java.lang.reflect.Type; import java.util.List; import com.alibaba.fastjson.serializer.SerializerFeature; public class FastJsonImpl extends AbstractJSONImpl { @Override public <T> T toJavaObject(String json, Type type) { return com.alibaba.fastjson.JSON.parseObject(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { return com.alibaba.fastjson.JSON.parseArray(json, clazz); } @Override public String toJson(Object obj) { return com.alibaba.fastjson.JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect); } }
6,964
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.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.json.impl; import java.lang.reflect.Type; import java.util.List; import com.alibaba.fastjson2.JSONWriter; public class FastJson2Impl extends AbstractJSONImpl { @Override public <T> T toJavaObject(String json, Type type) { return com.alibaba.fastjson2.JSON.parseObject(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { return com.alibaba.fastjson2.JSON.parseArray(json, clazz); } @Override public String toJson(Object obj) { return com.alibaba.fastjson2.JSON.toJSONString(obj, JSONWriter.Feature.WriteEnumsUsingName); } }
6,965
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.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.json.impl; import java.lang.reflect.Type; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class JacksonImpl extends AbstractJSONImpl { private final ObjectMapper objectMapper = new ObjectMapper(); private volatile Object jacksonCache = null; @Override public <T> T toJavaObject(String json, Type type) { try { return getJackson().readValue(json, getJackson().getTypeFactory().constructType(type)); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { try { return getJackson() .readValue(json, getJackson().getTypeFactory().constructCollectionType(List.class, clazz)); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public String toJson(Object obj) { try { return getJackson().writeValueAsString(obj); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } private JsonMapper getJackson() { if (jacksonCache == null || !(jacksonCache instanceof JsonMapper)) { synchronized (this) { if (jacksonCache == null || !(jacksonCache instanceof JsonMapper)) { jacksonCache = JsonMapper.builder() .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .serializationInclusion(Include.NON_NULL) .addModule(new JavaTimeModule()) .build(); } } } return (JsonMapper) jacksonCache; } }
6,966
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJSONImpl.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.json.impl; import org.apache.dubbo.common.json.JSON; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public abstract class AbstractJSONImpl implements JSON { @Override public boolean isSupport() { try { Map<String, String> map = new HashMap<>(); map.put("json", "test"); if (!CollectionUtils.mapEquals(map, toJavaObject(toJson(map), Map.class))) { return false; } List<String> list = new LinkedList<>(); list.add("json"); return CollectionUtils.equals(list, toJavaList(toJson(list), String.class)); } catch (Throwable t) { return false; } } @Override public List<?> getList(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (!(value instanceof List)) { throw new ClassCastException(String.format("value '%s' for key '%s' in '%s' is not List", value, key, obj)); } return (List<?>) value; } /** * Gets a list from an object for the given key, and verifies all entries are objects. If the key * is not present, this returns null. If the value is not a List or an entry is not an object, * throws an exception. */ @Override public List<Map<String, ?>> getListOfObjects(Map<String, ?> obj, String key) { assert obj != null; List<?> list = getList(obj, key); if (list == null) { return null; } return checkObjectList(list); } /** * Gets a list from an object for the given key, and verifies all entries are strings. If the key * is not present, this returns null. If the value is not a List or an entry is not a string, * throws an exception. */ @Override public List<String> getListOfStrings(Map<String, ?> obj, String key) { assert obj != null; List<?> list = getList(obj, key); if (list == null) { return null; } return checkStringList(list); } /** * Gets an object from an object for the given key. If the key is not present, this returns null. * If the value is not a Map, throws an exception. */ @SuppressWarnings("unchecked") @Override public Map<String, ?> getObject(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (!(value instanceof Map)) { throw new ClassCastException( String.format("value '%s' for key '%s' in '%s' is not object", value, key, obj)); } return (Map<String, ?>) value; } /** * Gets a number from an object for the given key. If the key is not present, this returns null. * If the value does not represent a double, throws an exception. */ @Override public Double getNumberAsDouble(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (value instanceof Double) { return (Double) value; } if (value instanceof String) { try { return Double.parseDouble((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("value '%s' for key '%s' is not a double", value, key)); } } throw new IllegalArgumentException( String.format("value '%s' for key '%s' in '%s' is not a number", value, key, obj)); } /** * Gets a number from an object for the given key, casted to an integer. If the key is not * present, this returns null. If the value does not represent an integer, throws an exception. */ @Override public Integer getNumberAsInteger(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (value instanceof Double) { Double d = (Double) value; int i = d.intValue(); if (i != d) { throw new ClassCastException("Number expected to be integer: " + d); } return i; } if (value instanceof String) { try { return Integer.parseInt((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("value '%s' for key '%s' is not an integer", value, key)); } } throw new IllegalArgumentException(String.format("value '%s' for key '%s' is not an integer", value, key)); } /** * Gets a number from an object for the given key, casted to an long. If the key is not * present, this returns null. If the value does not represent a long integer, throws an * exception. */ @Override public Long getNumberAsLong(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (value instanceof Double) { Double d = (Double) value; long l = d.longValue(); if (l != d) { throw new ClassCastException("Number expected to be long: " + d); } return l; } if (value instanceof String) { try { return Long.parseLong((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("value '%s' for key '%s' is not a long integer", value, key)); } } throw new IllegalArgumentException(String.format("value '%s' for key '%s' is not a long integer", value, key)); } /** * Gets a string from an object for the given key. If the key is not present, this returns null. * If the value is not a String, throws an exception. */ @Override public String getString(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (!(value instanceof String)) { throw new ClassCastException( String.format("value '%s' for key '%s' in '%s' is not String", value, key, obj)); } return (String) value; } /** * Casts a list of unchecked JSON values to a list of checked objects in Java type. * If the given list contains a value that is not a Map, throws an exception. */ @SuppressWarnings("unchecked") @Override public List<Map<String, ?>> checkObjectList(List<?> rawList) { assert rawList != null; for (int i = 0; i < rawList.size(); i++) { if (!(rawList.get(i) instanceof Map)) { throw new ClassCastException( String.format("value %s for idx %d in %s is not object", rawList.get(i), i, rawList)); } } return (List<Map<String, ?>>) rawList; } /** * Casts a list of unchecked JSON values to a list of String. If the given list * contains a value that is not a String, throws an exception. */ @SuppressWarnings("unchecked") @Override public List<String> checkStringList(List<?> rawList) { assert rawList != null; for (int i = 0; i < rawList.size(); i++) { if (!(rawList.get(i) instanceof String)) { throw new ClassCastException( String.format("value '%s' for idx %d in '%s' is not string", rawList.get(i), i, rawList)); } } return (List<String>) rawList; } }
6,967
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/concurrent/Rejector.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.concurrent; import java.util.Queue; /** * RejectHandler, it works when you need to custom reject action. * * @see AbortPolicy * @see DiscardPolicy * @see DiscardOldestPolicy */ public interface Rejector<E> { /** * Method that may be invoked by a Queue when Queue has remained memory * return true. This may occur when no more memory are available because their bounds would be exceeded. * * <p>In the absence of other alternatives, the method may throw an unchecked * {@link RejectException}, which will be propagated to the caller. * * @param e the element requested to be added * @param queue the queue attempting to add this element * * @throws RejectException if there is no more memory */ void reject(E e, Queue<E> queue); }
6,968
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/concurrent/AbortPolicy.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.concurrent; import java.util.Queue; /** * A handler for rejected element that throws a {@code RejectException}. */ public class AbortPolicy<E> implements Rejector<E> { @Override public void reject(final E e, final Queue<E> queue) { throw new RejectException("no more memory can be used !"); } }
6,969
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/concurrent/RejectException.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.concurrent; import org.apache.dubbo.common.threadpool.MemorySafeLinkedBlockingQueue; /** * Exception thrown by an {@link MemorySafeLinkedBlockingQueue} when an element cannot be accepted. */ public class RejectException extends RuntimeException { private static final long serialVersionUID = -3240015871717170195L; /** * Constructs a {@code RejectException} with no detail message. The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause(Throwable) initCause}. */ public RejectException() {} /** * Constructs a {@code RejectException} with the specified detail message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause(Throwable) initCause}. * * @param message the detail message */ public RejectException(final String message) { super(message); } /** * Constructs a {@code RejectException} with the specified detail message and cause. * * @param message the detail message * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method) */ public RejectException(final String message, final Throwable cause) { super(message, cause); } /** * Constructs a {@code RejectException} with the specified cause. The detail message is set to {@code (cause == null ? null : * cause.toString())} (which typically contains the class and detail message of {@code cause}). * * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method) */ public RejectException(final Throwable cause) { super(cause); } }
6,970
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/concurrent/DiscardOldestPolicy.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.concurrent; import java.util.Queue; /** * A handler for rejected element that discards the oldest element. */ public class DiscardOldestPolicy<E> implements Rejector<E> { @Override public void reject(final E e, final Queue<E> queue) { queue.poll(); queue.offer(e); } }
6,971
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/concurrent/DiscardPolicy.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.concurrent; import java.util.Queue; /** * A handler for rejected element that silently discards the rejected element. */ public class DiscardPolicy<E> implements Rejector<E> { @Override public void reject(final E e, final Queue<E> queue) {} }
6,972
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/concurrent/CallableSafeInitializer.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.concurrent; import org.apache.dubbo.common.resource.Disposable; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; /** * <p> * A safe and lazy and removable initializer implementation that wraps a * {@code Callable} object. * </p> * @see org.apache.commons.lang3.concurrent.AtomicSafeInitializer */ public class CallableSafeInitializer<T> { /** A guard which ensures that initialize() is called only once. */ private final AtomicReference<CallableSafeInitializer<T>> factory = new AtomicReference<>(); /** Holds the reference to the managed object. */ private final AtomicReference<T> reference = new AtomicReference<>(); /** The Callable to be executed. */ private final Callable<T> callable; public CallableSafeInitializer(Callable<T> callable) { this.callable = callable; } /** * Get (and initialize, if not initialized yet) the required object * * @return lazily initialized object * exception */ // @Override public final T get() { T result; while ((result = reference.get()) == null) { if (factory.compareAndSet(null, this)) { reference.set(initialize()); } } return result; } /** * Creates and initializes the object managed by this * {@code AtomicInitializer}. This method is called by {@link #get()} when * the managed object is not available yet. An implementation can focus on * the creation of the object. No synchronization is needed, as this is * already handled by {@code get()}. This method is guaranteed to be called * only once. * * @return the managed data object */ protected T initialize() { try { return callable.call(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public T remove() { return this.remove(null); } public T remove(Consumer<? super T> action) { // release T value = reference.getAndSet(null); if (value != null) { if (action != null) { action.accept(value); } if (value instanceof Disposable) { ((Disposable) value).destroy(); } } factory.set(null); return value; } }
6,973
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/beans/ScopeBeanExtensionInjector.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.beans; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelAware; /** * Inject scope bean to SPI extension instance */ public class ScopeBeanExtensionInjector implements ExtensionInjector, ScopeModelAware { private ScopeBeanFactory beanFactory; @Override public void setScopeModel(final ScopeModel scopeModel) { this.beanFactory = scopeModel.getBeanFactory(); } @Override public <T> T getInstance(final Class<T> type, final String name) { return beanFactory == null ? null : beanFactory.getBean(name, type); } }
6,974
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/beans/ScopeBeanException.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.beans; public class ScopeBeanException extends RuntimeException { public ScopeBeanException(String message, Throwable cause) { super(message, cause); } public ScopeBeanException(String message) { super(message); } }
6,975
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beans
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beans/support/InstantiationStrategy.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.beans.support; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelAccessor; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; /** * Interface to create instance for specify type, using both in {@link ExtensionLoader} and {@link ScopeBeanFactory}. */ public class InstantiationStrategy { private final ScopeModelAccessor scopeModelAccessor; public InstantiationStrategy() { this(null); } public InstantiationStrategy(ScopeModelAccessor scopeModelAccessor) { this.scopeModelAccessor = scopeModelAccessor; } @SuppressWarnings("unchecked") public <T> T instantiate(Class<T> type) throws ReflectiveOperationException { // should not use default constructor directly, maybe also has another constructor matched scope model arguments // 1. try to get default constructor Constructor<T> defaultConstructor = null; try { defaultConstructor = type.getConstructor(); } catch (NoSuchMethodException e) { // ignore no default constructor } // 2. use matched constructor if found List<Constructor<?>> matchedConstructors = new ArrayList<>(); Constructor<?>[] declaredConstructors = type.getConstructors(); for (Constructor<?> constructor : declaredConstructors) { if (isMatched(constructor)) { matchedConstructors.add(constructor); } } // remove default constructor from matchedConstructors if (defaultConstructor != null) { matchedConstructors.remove(defaultConstructor); } // match order: // 1. the only matched constructor with parameters // 2. default constructor if absent Constructor<?> targetConstructor; if (matchedConstructors.size() > 1) { throw new IllegalArgumentException("Expect only one but found " + matchedConstructors.size() + " matched constructors for type: " + type.getName() + ", matched constructors: " + matchedConstructors); } else if (matchedConstructors.size() == 1) { targetConstructor = matchedConstructors.get(0); } else if (defaultConstructor != null) { targetConstructor = defaultConstructor; } else { throw new IllegalArgumentException("None matched constructor was found for type: " + type.getName()); } // create instance with arguments Class<?>[] parameterTypes = targetConstructor.getParameterTypes(); Object[] args = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { args[i] = getArgumentValueForType(parameterTypes[i]); } return (T) targetConstructor.newInstance(args); } private boolean isMatched(Constructor<?> constructor) { for (Class<?> parameterType : constructor.getParameterTypes()) { if (!isSupportedConstructorParameterType(parameterType)) { return false; } } return true; } private boolean isSupportedConstructorParameterType(Class<?> parameterType) { return ScopeModel.class.isAssignableFrom(parameterType); } private Object getArgumentValueForType(Class<?> parameterType) { // get scope mode value if (scopeModelAccessor != null) { if (parameterType == ScopeModel.class) { return scopeModelAccessor.getScopeModel(); } else if (parameterType == FrameworkModel.class) { return scopeModelAccessor.getFrameworkModel(); } else if (parameterType == ApplicationModel.class) { return scopeModelAccessor.getApplicationModel(); } else if (parameterType == ModuleModel.class) { return scopeModelAccessor.getModuleModel(); } } return null; } }
6,976
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beans
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.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.beans.factory; import org.apache.dubbo.common.beans.ScopeBeanException; import org.apache.dubbo.common.beans.support.InstantiationStrategy; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionAccessorAware; import org.apache.dubbo.common.extension.ExtensionPostProcessor; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModelAccessor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_DESTROY_INVOKER; /** * A bean factory for internal sharing. */ public class ScopeBeanFactory { protected static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ScopeBeanFactory.class); private final ScopeBeanFactory parent; private final ExtensionAccessor extensionAccessor; private final List<ExtensionPostProcessor> extensionPostProcessors; private final ConcurrentHashMap<Class<?>, AtomicInteger> beanNameIdCounterMap = new ConcurrentHashMap<>(); private final List<BeanInfo> registeredBeanInfos = new CopyOnWriteArrayList<>(); private InstantiationStrategy instantiationStrategy; private final AtomicBoolean destroyed = new AtomicBoolean(); private List<Class<?>> registeredClasses = new ArrayList<>(); public ScopeBeanFactory(ScopeBeanFactory parent, ExtensionAccessor extensionAccessor) { this.parent = parent; this.extensionAccessor = extensionAccessor; extensionPostProcessors = extensionAccessor.getExtensionDirector().getExtensionPostProcessors(); initInstantiationStrategy(); } private void initInstantiationStrategy() { for (ExtensionPostProcessor extensionPostProcessor : extensionPostProcessors) { if (extensionPostProcessor instanceof ScopeModelAccessor) { instantiationStrategy = new InstantiationStrategy((ScopeModelAccessor) extensionPostProcessor); break; } } if (instantiationStrategy == null) { instantiationStrategy = new InstantiationStrategy(); } } public <T> T registerBean(Class<T> bean) throws ScopeBeanException { return this.getOrRegisterBean(null, bean); } public <T> T registerBean(String name, Class<T> clazz) throws ScopeBeanException { return getOrRegisterBean(name, clazz); } private <T> T createAndRegisterBean(String name, Class<T> clazz) { checkDestroyed(); T instance = getBean(name, clazz); if (instance != null) { throw new ScopeBeanException( "already exists bean with same name and type, name=" + name + ", type=" + clazz.getName()); } try { instance = instantiationStrategy.instantiate(clazz); } catch (Throwable e) { throw new ScopeBeanException("create bean instance failed, type=" + clazz.getName(), e); } registerBean(name, instance); return instance; } public void registerBean(Object bean) { this.registerBean(null, bean); } public void registerBean(String name, Object bean) { checkDestroyed(); // avoid duplicated register same bean if (containsBean(name, bean)) { return; } Class<?> beanClass = bean.getClass(); if (name == null) { name = beanClass.getName() + "#" + getNextId(beanClass); } initializeBean(name, bean); registeredBeanInfos.add(new BeanInfo(name, bean)); } public <T> T getOrRegisterBean(Class<T> type) { return getOrRegisterBean(null, type); } public <T> T getOrRegisterBean(String name, Class<T> type) { T bean = getBean(name, type); if (bean == null) { // lock by type synchronized (type) { bean = getBean(name, type); if (bean == null) { bean = createAndRegisterBean(name, type); } } } registeredClasses.add(type); return bean; } public <T> T getOrRegisterBean(Class<T> type, Function<? super Class<T>, ? extends T> mappingFunction) { return getOrRegisterBean(null, type, mappingFunction); } public <T> T getOrRegisterBean( String name, Class<T> type, Function<? super Class<T>, ? extends T> mappingFunction) { T bean = getBean(name, type); if (bean == null) { // lock by type synchronized (type) { bean = getBean(name, type); if (bean == null) { bean = mappingFunction.apply(type); registerBean(name, bean); } } } return bean; } private void initializeBean(String name, Object bean) { checkDestroyed(); try { if (bean instanceof ExtensionAccessorAware) { ((ExtensionAccessorAware) bean).setExtensionAccessor(extensionAccessor); } for (ExtensionPostProcessor processor : extensionPostProcessors) { processor.postProcessAfterInitialization(bean, name); } } catch (Exception e) { throw new ScopeBeanException( "register bean failed! name=" + name + ", type=" + bean.getClass().getName(), e); } } private boolean containsBean(String name, Object bean) { for (BeanInfo beanInfo : registeredBeanInfos) { if (beanInfo.instance == bean && (name == null || StringUtils.isEquals(name, beanInfo.name))) { return true; } } return false; } private int getNextId(Class<?> beanClass) { return ConcurrentHashMapUtils.computeIfAbsent(beanNameIdCounterMap, beanClass, key -> new AtomicInteger()) .incrementAndGet(); } @SuppressWarnings("unchecked") public <T> List<T> getBeansOfType(Class<T> type) { List<T> currentBeans = (List<T>) registeredBeanInfos.stream() .filter(beanInfo -> type.isInstance(beanInfo.instance)) .map(beanInfo -> beanInfo.instance) .collect(Collectors.toList()); if (parent != null) { currentBeans.addAll(parent.getBeansOfType(type)); } return currentBeans; } public <T> T getBean(Class<T> type) { return this.getBean(null, type); } public <T> T getBean(String name, Class<T> type) { T bean = getBeanInternal(name, type); if (bean == null && parent != null) { return parent.getBean(name, type); } return bean; } @SuppressWarnings("unchecked") private <T> T getBeanInternal(String name, Class<T> type) { checkDestroyed(); // All classes are derived from java.lang.Object, cannot filter bean by it if (type == Object.class) { return null; } List<BeanInfo> candidates = null; BeanInfo firstCandidate = null; for (BeanInfo beanInfo : registeredBeanInfos) { // if required bean type is same class/superclass/interface of the registered bean if (type.isAssignableFrom(beanInfo.instance.getClass())) { if (StringUtils.isEquals(beanInfo.name, name)) { return (T) beanInfo.instance; } else { // optimize for only one matched bean if (firstCandidate == null) { firstCandidate = beanInfo; } else { if (candidates == null) { candidates = new ArrayList<>(); candidates.add(firstCandidate); } candidates.add(beanInfo); } } } } // if bean name not matched and only single candidate if (candidates != null) { if (candidates.size() == 1) { return (T) candidates.get(0).instance; } else if (candidates.size() > 1) { List<String> candidateBeanNames = candidates.stream().map(beanInfo -> beanInfo.name).collect(Collectors.toList()); throw new ScopeBeanException("expected single matching bean but found " + candidates.size() + " candidates for type [" + type.getName() + "]: " + candidateBeanNames); } } else if (firstCandidate != null) { return (T) firstCandidate.instance; } return null; } public void destroy() { if (destroyed.compareAndSet(false, true)) { for (BeanInfo beanInfo : registeredBeanInfos) { if (beanInfo.instance instanceof Disposable) { try { Disposable beanInstance = (Disposable) beanInfo.instance; beanInstance.destroy(); } catch (Throwable e) { LOGGER.error( CONFIG_FAILED_DESTROY_INVOKER, "", "", "An error occurred when destroy bean [name=" + beanInfo.name + ", bean=" + beanInfo.instance + "]: " + e, e); } } } registeredBeanInfos.clear(); } } public boolean isDestroyed() { return destroyed.get(); } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException("ScopeBeanFactory is destroyed"); } } static class BeanInfo { private final String name; private final Object instance; public BeanInfo(String name, Object instance) { this.name = name; this.instance = instance; } } public List<Class<?>> getRegisteredClasses() { return registeredClasses; } }
6,977
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/bytecode/NoSuchPropertyException.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.bytecode; /** * NoSuchPropertyException. */ public class NoSuchPropertyException extends RuntimeException { private static final long serialVersionUID = -2725364246023268766L; public NoSuchPropertyException() { super(); } public NoSuchPropertyException(String msg) { super(msg); } }
6,978
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/bytecode/Mixin.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.bytecode; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; /** * Mixin */ public abstract class Mixin { private static final String PACKAGE_NAME = Mixin.class.getPackage().getName(); private static final AtomicLong MIXIN_CLASS_COUNTER = new AtomicLong(0); protected Mixin() {} /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dc delegate class. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?> dc) { return mixin(ics, new Class[] {dc}); } /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dc delegate class. * @param cl class loader. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?> dc, ClassLoader cl) { return mixin(ics, new Class[] {dc}, cl); } /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dcs delegate class array. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?>[] dcs) { return mixin(ics, dcs, ClassUtils.getCallerClassLoader(Mixin.class)); } /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dcs delegate class array. * @param cl class loader. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?>[] dcs, ClassLoader cl) { assertInterfaceArray(ics); long id = MIXIN_CLASS_COUNTER.getAndIncrement(); String pkg = null; ClassGenerator ccp = null, ccm = null; try { ccp = ClassGenerator.newInstance(cl); // impl constructor StringBuilder code = new StringBuilder(); for (int i = 0; i < dcs.length; i++) { if (!Modifier.isPublic(dcs[i].getModifiers())) { String npkg = dcs[i].getPackage().getName(); if (pkg == null) { pkg = npkg; } else { if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces class from different packages"); } } } ccp.addField("private " + dcs[i].getName() + " d" + i + ";"); code.append('d') .append(i) .append(" = (") .append(dcs[i].getName()) .append(")$1[") .append(i) .append("];\n"); if (MixinAware.class.isAssignableFrom(dcs[i])) { code.append('d').append(i).append(".setMixinInstance(this);\n"); } } ccp.addConstructor(Modifier.PUBLIC, new Class<?>[] {Object[].class}, code.toString()); Class<?> neighbor = null; // impl methods. Set<String> worked = new HashSet<String>(); for (int i = 0; i < ics.length; i++) { if (!Modifier.isPublic(ics[i].getModifiers())) { String npkg = ics[i].getPackage().getName(); if (pkg == null) { pkg = npkg; neighbor = ics[i]; } else { if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public delegate class from different packages"); } } } ccp.addInterface(ics[i]); for (Method method : ics[i].getMethods()) { if ("java.lang.Object".equals(method.getDeclaringClass().getName())) { continue; } String desc = ReflectUtils.getDesc(method); if (worked.contains(desc)) { continue; } worked.add(desc); int ix = findMethod(dcs, desc); if (ix < 0) { throw new RuntimeException("Missing method [" + desc + "] implement."); } Class<?> rt = method.getReturnType(); String mn = method.getName(); if (Void.TYPE.equals(rt)) { ccp.addMethod( mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), "d" + ix + "." + mn + "($$);"); } else { ccp.addMethod( mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), "return ($r)d" + ix + "." + mn + "($$);"); } } } if (pkg == null) { pkg = PACKAGE_NAME; neighbor = Mixin.class; } // create MixinInstance class. String micn = pkg + ".mixin" + id; ccp.setClassName(micn); ccp.toClass(neighbor); // create Mixin class. String fcn = Mixin.class.getName() + id; ccm = ClassGenerator.newInstance(cl); ccm.setClassName(fcn); ccm.addDefaultConstructor(); ccm.setSuperClass(Mixin.class.getName()); ccm.addMethod("public Object newInstance(Object[] delegates){ return new " + micn + "($1); }"); Class<?> mixin = ccm.toClass(Mixin.class); return (Mixin) mixin.getDeclaredConstructor().newInstance(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator if (ccp != null) { ccp.release(); } if (ccm != null) { ccm.release(); } } } private static int findMethod(Class<?>[] dcs, String desc) { Class<?> cl; Method[] methods; for (int i = 0; i < dcs.length; i++) { cl = dcs[i]; methods = cl.getMethods(); for (Method method : methods) { if (desc.equals(ReflectUtils.getDesc(method))) { return i; } } } return -1; } private static void assertInterfaceArray(Class<?>[] ics) { for (int i = 0; i < ics.length; i++) { if (!ics[i].isInterface()) { throw new RuntimeException("Class " + ics[i].getName() + " is not a interface."); } } } /** * new Mixin instance. * * @param ds delegates instance. * @return instance. */ public abstract Object newInstance(Object[] ds); public static interface MixinAware { void setMixinInstance(Object instance); } }
6,979
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/bytecode/Wrapper.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.bytecode; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.stream.Collectors; import javassist.ClassPool; import javassist.CtMethod; /** * Wrapper. */ public abstract class Wrapper { private static final ConcurrentMap<Class<?>, Wrapper> WRAPPER_MAP = new ConcurrentHashMap<Class<?>, Wrapper>(); // class wrapper map private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; private static final Wrapper OBJECT_WRAPPER = new Wrapper() { @Override public String[] getMethodNames() { return OBJECT_METHODS; } @Override public String[] getDeclaredMethodNames() { return OBJECT_METHODS; } @Override public String[] getPropertyNames() { return EMPTY_STRING_ARRAY; } @Override public Class<?> getPropertyType(String pn) { return null; } @Override public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException { throw new NoSuchPropertyException("Property [" + pn + "] not found."); } @Override public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException { throw new NoSuchPropertyException("Property [" + pn + "] not found."); } @Override public boolean hasProperty(String name) { return false; } @Override public Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException { if ("getClass".equals(mn)) { return instance.getClass(); } if ("hashCode".equals(mn)) { return instance.hashCode(); } if ("toString".equals(mn)) { return instance.toString(); } if ("equals".equals(mn)) { if (args.length == 1) { return instance.equals(args[0]); } throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error."); } throw new NoSuchMethodException("Method [" + mn + "] not found."); } }; private static AtomicLong WRAPPER_CLASS_COUNTER = new AtomicLong(0); /** * get wrapper. * * @param c Class instance. * @return Wrapper instance(not null). */ public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic class. { c = c.getSuperclass(); } if (c == Object.class) { return OBJECT_WRAPPER; } return ConcurrentHashMapUtils.computeIfAbsent(WRAPPER_MAP, c, Wrapper::makeWrapper); } private static Wrapper makeWrapper(Class<?> c) { if (c.isPrimitive()) { throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); } String name = c.getName(); ClassLoader cl = ClassUtils.getClassLoader(c); StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); StringBuilder c3 = new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ "); c1.append(name) .append(" w; try{ w = ((") .append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); c2.append(name) .append(" w; try{ w = ((") .append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); c3.append(name) .append(" w; try{ w = ((") .append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); Map<String, Class<?>> pts = new HashMap<>(); // <property name, property types> Map<String, Method> ms = new LinkedHashMap<>(); // <method desc, Method instance> List<String> mns = new ArrayList<>(); // method names. List<String> dmns = new ArrayList<>(); // declaring method names. // get all public field. for (Field f : c.getFields()) { String fn = f.getName(); Class<?> ft = f.getType(); if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) { continue; } c1.append(" if( $2.equals(\"") .append(fn) .append("\") ){ ((") .append(f.getDeclaringClass().getName()) .append(")w).") .append(fn) .append('=') .append(arg(ft, "$3")) .append("; return; }"); c2.append(" if( $2.equals(\"") .append(fn) .append("\") ){ return ($w)((") .append(f.getDeclaringClass().getName()) .append(")w).") .append(fn) .append("; }"); pts.put(fn, ft); } final ClassPool classPool = ClassGenerator.getClassPool(cl); List<String> allMethod = new ArrayList<>(); try { final CtMethod[] ctMethods = classPool.get(c.getName()).getMethods(); for (CtMethod method : ctMethods) { allMethod.add(ReflectUtils.getDesc(method)); } } catch (Exception e) { throw new RuntimeException(e); } Method[] methods = Arrays.stream(c.getMethods()) .filter(method -> allMethod.contains(ReflectUtils.getDesc(method))) .collect(Collectors.toList()) .toArray(new Method[] {}); // get all public method. boolean hasMethod = ClassUtils.hasMethods(methods); if (hasMethod) { Map<String, Integer> sameNameMethodCount = new HashMap<>((int) (methods.length / 0.75f) + 1); for (Method m : methods) { sameNameMethodCount.compute(m.getName(), (key, oldValue) -> oldValue == null ? 1 : oldValue + 1); } c3.append(" try{"); for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } String mn = m.getName(); c3.append(" if( \"").append(mn).append("\".equals( $2 ) "); int len = m.getParameterTypes().length; c3.append(" && ").append(" $3.length == ").append(len); boolean overload = sameNameMethodCount.get(m.getName()) > 1; if (overload) { if (len > 0) { for (int l = 0; l < len; l++) { c3.append(" && ") .append(" $3[") .append(l) .append("].getName().equals(\"") .append(m.getParameterTypes()[l].getName()) .append("\")"); } } } c3.append(" ) { "); if (m.getReturnType() == Void.TYPE) { c3.append(" w.") .append(mn) .append('(') .append(args(m.getParameterTypes(), "$4")) .append(");") .append(" return null;"); } else { c3.append(" return ($w)w.") .append(mn) .append('(') .append(args(m.getParameterTypes(), "$4")) .append(");"); } c3.append(" }"); mns.add(mn); if (m.getDeclaringClass() == c) { dmns.add(mn); } ms.put(ReflectUtils.getDesc(m), m); } c3.append(" } catch(Throwable e) { "); c3.append(" throw new java.lang.reflect.InvocationTargetException(e); "); c3.append(" }"); } c3.append(" throw new ") .append(NoSuchMethodException.class.getName()) .append("(\"Not found method \\\"\"+$2+\"\\\" in class ") .append(c.getName()) .append(".\"); }"); // deal with get/set method. Matcher matcher; for (Map.Entry<String, Method> entry : ms.entrySet()) { String md = entry.getKey(); Method method = entry.getValue(); if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"") .append(pn) .append("\") ){ return ($w)w.") .append(method.getName()) .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"") .append(pn) .append("\") ){ return ($w)w.") .append(method.getName()) .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { Class<?> pt = method.getParameterTypes()[0]; String pn = propertyName(matcher.group(1)); c1.append(" if( $2.equals(\"") .append(pn) .append("\") ){ w.") .append(method.getName()) .append('(') .append(arg(pt, "$3")) .append("); return; }"); pts.put(pn, pt); } } c1.append(" throw new ") .append(NoSuchPropertyException.class.getName()) .append("(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class ") .append(c.getName()) .append(".\"); }"); c2.append(" throw new ") .append(NoSuchPropertyException.class.getName()) .append("(\"Not found property \\\"\"+$2+\"\\\" field or getter method in class ") .append(c.getName()) .append(".\"); }"); // make class long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); ClassGenerator cc = ClassGenerator.newInstance(cl); cc.setClassName(c.getName() + "DubboWrap" + id); cc.setSuperClass(Wrapper.class); cc.addDefaultConstructor(); cc.addField("public static String[] pns;"); // property name array. cc.addField("public static " + Map.class.getName() + " pts;"); // property type map. cc.addField("public static String[] mns;"); // all method name array. cc.addField("public static String[] dmns;"); // declared method name array. for (int i = 0, len = ms.size(); i < len; i++) { cc.addField("public static Class[] mts" + i + ";"); } cc.addMethod("public String[] getPropertyNames(){ return pns; }"); cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }"); cc.addMethod("public Class getPropertyType(String n){ return (Class)pts.get($1); }"); cc.addMethod("public String[] getMethodNames(){ return mns; }"); cc.addMethod("public String[] getDeclaredMethodNames(){ return dmns; }"); cc.addMethod(c1.toString()); cc.addMethod(c2.toString()); cc.addMethod(c3.toString()); try { Class<?> wc = cc.toClass(c); // setup static field. wc.getField("pts").set(null, pts); wc.getField("pns").set(null, pts.keySet().toArray(new String[0])); wc.getField("mns").set(null, mns.toArray(new String[0])); wc.getField("dmns").set(null, dmns.toArray(new String[0])); int ix = 0; for (Method m : ms.values()) { wc.getField("mts" + ix++).set(null, m.getParameterTypes()); } return (Wrapper) wc.getDeclaredConstructor().newInstance(); } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } finally { cc.release(); pts.clear(); ms.clear(); mns.clear(); dmns.clear(); } } private static String arg(Class<?> cl, String name) { if (cl.isPrimitive()) { if (cl == Boolean.TYPE) { return "((Boolean)" + name + ").booleanValue()"; } if (cl == Byte.TYPE) { return "((Byte)" + name + ").byteValue()"; } if (cl == Character.TYPE) { return "((Character)" + name + ").charValue()"; } if (cl == Double.TYPE) { return "((Number)" + name + ").doubleValue()"; } if (cl == Float.TYPE) { return "((Number)" + name + ").floatValue()"; } if (cl == Integer.TYPE) { return "((Number)" + name + ").intValue()"; } if (cl == Long.TYPE) { return "((Number)" + name + ").longValue()"; } if (cl == Short.TYPE) { return "((Number)" + name + ").shortValue()"; } throw new RuntimeException("Unknown primitive type: " + cl.getName()); } return "(" + ReflectUtils.getName(cl) + ")" + name; } private static String args(Class<?>[] cs, String name) { int len = cs.length; if (len == 0) { return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) { sb.append(','); } sb.append(arg(cs[i], name + "[" + i + "]")); } return sb.toString(); } private static String propertyName(String pn) { return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) : pn; } /** * get property name array. * * @return property name array. */ public abstract String[] getPropertyNames(); /** * get property type. * * @param pn property name. * @return Property type or nul. */ public abstract Class<?> getPropertyType(String pn); /** * has property. * * @param name property name. * @return has or has not. */ public abstract boolean hasProperty(String name); /** * get property value. * * @param instance instance. * @param pn property name. * @return value. */ public abstract Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException, IllegalArgumentException; /** * set property value. * * @param instance instance. * @param pn property name. * @param pv property value. */ public abstract void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException, IllegalArgumentException; /** * get property value. * * @param instance instance. * @param pns property name array. * @return value array. */ public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException { Object[] ret = new Object[pns.length]; for (int i = 0; i < ret.length; i++) { ret[i] = getPropertyValue(instance, pns[i]); } return ret; } /** * set property value. * * @param instance instance. * @param pns property name array. * @param pvs property value array. */ public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws NoSuchPropertyException, IllegalArgumentException { if (pns.length != pvs.length) { throw new IllegalArgumentException("pns.length != pvs.length"); } for (int i = 0; i < pns.length; i++) { setPropertyValue(instance, pns[i], pvs[i]); } } /** * get method name array. * * @return method name array. */ public abstract String[] getMethodNames(); /** * get method name array. * * @return method name array. */ public abstract String[] getDeclaredMethodNames(); /** * has method. * * @param name method name. * @return has or has not. */ public boolean hasMethod(String name) { for (String mn : getMethodNames()) { if (mn.equals(name)) { return true; } } return false; } /** * invoke method. * * @param instance instance. * @param mn method name. * @param types * @param args argument array. * @return return value. */ public abstract Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException, InvocationTargetException; }
6,980
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/bytecode/DubboLoaderClassPath.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.bytecode; import java.io.InputStream; import java.net.URL; import javassist.LoaderClassPath; import javassist.NotFoundException; /** * Ensure javassist will load Dubbo's class from Dubbo's classLoader */ public class DubboLoaderClassPath extends LoaderClassPath { public DubboLoaderClassPath() { super(DubboLoaderClassPath.class.getClassLoader()); } @Override public InputStream openClassfile(String classname) throws NotFoundException { if (!classname.startsWith("org.apache.dubbo") && !classname.startsWith("grpc.health") && !classname.startsWith("com.google")) { return null; } return super.openClassfile(classname); } @Override public URL find(String classname) { if (!classname.startsWith("org.apache.dubbo")) { return null; } return super.find(classname); } }
6,981
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/bytecode/Proxy.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.bytecode; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.CommonConstants.MAX_PROXY_COUNT; /** * Proxy. */ public class Proxy { public static final InvocationHandler THROW_UNSUPPORTED_INVOKER = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) { throw new UnsupportedOperationException("Method [" + ReflectUtils.getName(method) + "] unimplemented."); } }; private static final AtomicLong PROXY_CLASS_COUNTER = new AtomicLong(0); private static final Map<ClassLoader, Map<String, Proxy>> PROXY_CACHE_MAP = new WeakHashMap<>(); private final Class<?> classToCreate; protected Proxy(Class<?> classToCreate) { this.classToCreate = classToCreate; } /** * Get proxy. * * @param ics interface class array. * @return Proxy instance. */ public static Proxy getProxy(Class<?>... ics) { if (ics.length > MAX_PROXY_COUNT) { throw new IllegalArgumentException("interface limit exceeded"); } // ClassLoader from App Interface should support load some class from Dubbo ClassLoader cl = ics[0].getClassLoader(); ProtectionDomain domain = ics[0].getProtectionDomain(); // use interface class name list as key. String key = buildInterfacesKey(cl, ics); // get cache by class loader. final Map<String, Proxy> cache; synchronized (PROXY_CACHE_MAP) { cache = PROXY_CACHE_MAP.computeIfAbsent(cl, k -> new ConcurrentHashMap<>()); } Proxy proxy = cache.get(key); if (proxy == null) { synchronized (ics[0]) { proxy = cache.get(key); if (proxy == null) { // create Proxy class. proxy = new Proxy(buildProxyClass(cl, ics, domain)); cache.put(key, proxy); } } } return proxy; } private static String buildInterfacesKey(ClassLoader cl, Class<?>[] ics) { StringBuilder sb = new StringBuilder(); for (Class<?> ic : ics) { String itf = ic.getName(); if (!ic.isInterface()) { throw new RuntimeException(itf + " is not a interface."); } Class<?> tmp = null; try { tmp = Class.forName(itf, false, cl); } catch (ClassNotFoundException ignore) { } if (tmp != ic) { throw new IllegalArgumentException(ic + " is not visible from class loader"); } sb.append(itf).append(';'); } return sb.toString(); } private static Class<?> buildProxyClass(ClassLoader cl, Class<?>[] ics, ProtectionDomain domain) { ClassGenerator ccp = null; try { ccp = ClassGenerator.newInstance(cl); Set<String> worked = new HashSet<>(); List<Method> methods = new ArrayList<>(); String pkg = ics[0].getPackage().getName(); Class<?> neighbor = ics[0]; for (Class<?> ic : ics) { String npkg = ic.getPackage().getName(); if (!Modifier.isPublic(ic.getModifiers())) { if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces from different packages"); } } ccp.addInterface(ic); for (Method method : ic.getMethods()) { String desc = ReflectUtils.getDesc(method); if (worked.contains(desc) || Modifier.isStatic(method.getModifiers())) { continue; } worked.add(desc); int ix = methods.size(); Class<?> rt = method.getReturnType(); Class<?>[] pts = method.getParameterTypes(); StringBuilder code = new StringBuilder("Object[] args = new Object[") .append(pts.length) .append("];"); for (int j = 0; j < pts.length; j++) { code.append(" args[") .append(j) .append("] = ($w)$") .append(j + 1) .append(';'); } code.append(" Object ret = handler.invoke(this, methods[") .append(ix) .append("], args);"); if (!Void.TYPE.equals(rt)) { code.append(" return ").append(asArgument(rt, "ret")).append(';'); } methods.add(method); ccp.addMethod( method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString()); } } // create ProxyInstance class. String pcn = neighbor.getName() + "DubboProxy" + PROXY_CLASS_COUNTER.getAndIncrement(); ccp.setClassName(pcn); ccp.addField("public static java.lang.reflect.Method[] methods;"); ccp.addField("private " + InvocationHandler.class.getName() + " handler;"); ccp.addConstructor( Modifier.PUBLIC, new Class<?>[] {InvocationHandler.class}, new Class<?>[0], "handler=$1;"); ccp.addDefaultConstructor(); Class<?> clazz = ccp.toClass(neighbor, cl, domain); clazz.getField("methods").set(null, methods.toArray(new Method[0])); return clazz; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator if (ccp != null) { ccp.release(); } } } private static String asArgument(Class<?> cl, String name) { if (cl.isPrimitive()) { if (Boolean.TYPE == cl) { return name + "==null?false:((Boolean)" + name + ").booleanValue()"; } if (Byte.TYPE == cl) { return name + "==null?(byte)0:((Byte)" + name + ").byteValue()"; } if (Character.TYPE == cl) { return name + "==null?(char)0:((Character)" + name + ").charValue()"; } if (Double.TYPE == cl) { return name + "==null?(double)0:((Double)" + name + ").doubleValue()"; } if (Float.TYPE == cl) { return name + "==null?(float)0:((Float)" + name + ").floatValue()"; } if (Integer.TYPE == cl) { return name + "==null?(int)0:((Integer)" + name + ").intValue()"; } if (Long.TYPE == cl) { return name + "==null?(long)0:((Long)" + name + ").longValue()"; } if (Short.TYPE == cl) { return name + "==null?(short)0:((Short)" + name + ").shortValue()"; } throw new RuntimeException(name + " is unknown primitive type."); } return "(" + ReflectUtils.getName(cl) + ")" + name; } /** * get instance with default handler. * * @return instance. */ public Object newInstance() { return newInstance(THROW_UNSUPPORTED_INVOKER); } /** * get instance with special handler. * * @return instance. */ public Object newInstance(InvocationHandler handler) { Constructor<?> constructor; try { constructor = classToCreate.getDeclaredConstructor(InvocationHandler.class); return constructor.newInstance(handler); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } public Class<?> getClassToCreate() { return classToCreate; } }
6,982
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/bytecode/ClassGenerator.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.bytecode; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; /** * ClassGenerator */ public final class ClassGenerator { private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); private static final String SIMPLE_NAME_TAG = "<init>"; private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<>(); // ClassLoader - ClassPool private ClassPool mPool; private CtClass mCtc; private String mClassName; private String mSuperClass; private Set<String> mInterfaces; private List<String> mFields; private List<String> mConstructors; private List<String> mMethods; private ClassLoader mClassLoader; private Map<String, Method> mCopyMethods; // <method desc,method instance> private Map<String, Constructor<?>> mCopyConstructors; // <constructor desc,constructor instance> private boolean mDefaultConstructor = false; private ClassGenerator() {} private ClassGenerator(ClassLoader classLoader, ClassPool pool) { mClassLoader = classLoader; mPool = pool; } public static ClassGenerator newInstance() { return new ClassGenerator( Thread.currentThread().getContextClassLoader(), getClassPool(Thread.currentThread().getContextClassLoader())); } public static ClassGenerator newInstance(ClassLoader loader) { return new ClassGenerator(loader, getClassPool(loader)); } public static boolean isDynamicClass(Class<?> cl) { return ClassGenerator.DC.class.isAssignableFrom(cl); } public static ClassPool getClassPool(ClassLoader loader) { if (loader == null) { return ClassPool.getDefault(); } ClassPool pool = POOL_MAP.get(loader); if (pool == null) { synchronized (POOL_MAP) { pool = POOL_MAP.get(loader); if (pool == null) { pool = new ClassPool(true); pool.insertClassPath(new LoaderClassPath(loader)); pool.insertClassPath(new DubboLoaderClassPath()); POOL_MAP.put(loader, pool); } } } return pool; } private static String modifier(int mod) { StringBuilder modifier = new StringBuilder(); if (Modifier.isPublic(mod)) { modifier.append("public"); } else if (Modifier.isProtected(mod)) { modifier.append("protected"); } else if (Modifier.isPrivate(mod)) { modifier.append("private"); } if (Modifier.isStatic(mod)) { modifier.append(" static"); } if (Modifier.isVolatile(mod)) { modifier.append(" volatile"); } return modifier.toString(); } public String getClassName() { return mClassName; } public ClassGenerator setClassName(String name) { mClassName = name; return this; } public ClassGenerator addInterface(String cn) { if (mInterfaces == null) { mInterfaces = new HashSet<>(); } mInterfaces.add(cn); return this; } public ClassGenerator addInterface(Class<?> cl) { return addInterface(cl.getName()); } public ClassGenerator setSuperClass(String cn) { mSuperClass = cn; return this; } public ClassGenerator setSuperClass(Class<?> cl) { mSuperClass = cl.getName(); return this; } public ClassGenerator addField(String code) { if (mFields == null) { mFields = new ArrayList<>(); } mFields.add(code); return this; } public ClassGenerator addField(String name, int mod, Class<?> type) { return addField(name, mod, type, null); } public ClassGenerator addField(String name, int mod, Class<?> type, String def) { StringBuilder sb = new StringBuilder(); sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' '); sb.append(name); if (StringUtils.isNotEmpty(def)) { sb.append('='); sb.append(def); } sb.append(';'); return addField(sb.toString()); } public ClassGenerator addMethod(String code) { if (mMethods == null) { mMethods = new ArrayList<>(); } mMethods.add(code); return this; } public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, String body) { return addMethod(name, mod, rt, pts, null, body); } public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, Class<?>[] ets, String body) { StringBuilder sb = new StringBuilder(); sb.append(modifier(mod)) .append(' ') .append(ReflectUtils.getName(rt)) .append(' ') .append(name); sb.append('('); if (ArrayUtils.isNotEmpty(pts)) { for (int i = 0; i < pts.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(pts[i])); sb.append(" arg").append(i); } } sb.append(')'); if (ArrayUtils.isNotEmpty(ets)) { sb.append(" throws "); for (int i = 0; i < ets.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(ets[i])); } } sb.append('{').append(body).append('}'); return addMethod(sb.toString()); } public ClassGenerator addMethod(Method m) { addMethod(m.getName(), m); return this; } public ClassGenerator addMethod(String name, Method m) { String desc = name + ReflectUtils.getDescWithoutMethodName(m); addMethod(':' + desc); if (mCopyMethods == null) { mCopyMethods = new ConcurrentHashMap<>(8); } mCopyMethods.put(desc, m); return this; } public ClassGenerator addConstructor(String code) { if (mConstructors == null) { mConstructors = new LinkedList<>(); } mConstructors.add(code); return this; } public ClassGenerator addConstructor(int mod, Class<?>[] pts, String body) { return addConstructor(mod, pts, null, body); } public ClassGenerator addConstructor(int mod, Class<?>[] pts, Class<?>[] ets, String body) { StringBuilder sb = new StringBuilder(); sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG); sb.append('('); for (int i = 0; i < pts.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(pts[i])); sb.append(" arg").append(i); } sb.append(')'); if (ArrayUtils.isNotEmpty(ets)) { sb.append(" throws "); for (int i = 0; i < ets.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(ets[i])); } } sb.append('{').append(body).append('}'); return addConstructor(sb.toString()); } public ClassGenerator addConstructor(Constructor<?> c) { String desc = ReflectUtils.getDesc(c); addConstructor(":" + desc); if (mCopyConstructors == null) { mCopyConstructors = new ConcurrentHashMap<>(4); } mCopyConstructors.put(desc, c); return this; } public ClassGenerator addDefaultConstructor() { mDefaultConstructor = true; return this; } public ClassPool getClassPool() { return mPool; } /** * @param neighbor A class belonging to the same package that this * class belongs to. It is used to load the class. */ public Class<?> toClass(Class<?> neighbor) { return toClass(neighbor, mClassLoader, getClass().getProtectionDomain()); } public Class<?> toClass(Class<?> neighborClass, ClassLoader loader, ProtectionDomain pd) { if (mCtc != null) { mCtc.detach(); } long id = CLASS_NAME_COUNTER.getAndIncrement(); try { CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); if (mClassName == null) { mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; } mCtc = mPool.makeClass(mClassName); if (mSuperClass != null) { mCtc.setSuperclass(ctcs); } mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. if (mInterfaces != null) { for (String cl : mInterfaces) { mCtc.addInterface(mPool.get(cl)); } } if (mFields != null) { for (String code : mFields) { mCtc.addField(CtField.make(code, mCtc)); } } if (mMethods != null) { for (String code : mMethods) { if (code.charAt(0) == ':') { mCtc.addMethod(CtNewMethod.copy( getCtMethod(mCopyMethods.get(code.substring(1))), code.substring(1, code.indexOf('(')), mCtc, null)); } else { mCtc.addMethod(CtNewMethod.make(code, mCtc)); } } } if (mDefaultConstructor) { mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); } if (mConstructors != null) { for (String code : mConstructors) { if (code.charAt(0) == ':') { mCtc.addConstructor(CtNewConstructor.copy( getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); } else { String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. mCtc.addConstructor( CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc)); } } } try { return mPool.toClass(mCtc, neighborClass, loader, pd); } catch (Throwable t) { if (!(t instanceof CannotCompileException)) { return mPool.toClass(mCtc, loader, pd); } throw t; } } catch (RuntimeException e) { throw e; } catch (NotFoundException | CannotCompileException e) { throw new RuntimeException(e.getMessage(), e); } } public void release() { if (mCtc != null) { mCtc.detach(); } if (mInterfaces != null) { mInterfaces.clear(); } if (mFields != null) { mFields.clear(); } if (mMethods != null) { mMethods.clear(); } if (mConstructors != null) { mConstructors.clear(); } if (mCopyMethods != null) { mCopyMethods.clear(); } if (mCopyConstructors != null) { mCopyConstructors.clear(); } } private CtClass getCtClass(Class<?> c) throws NotFoundException { return mPool.get(c.getName()); } private CtMethod getCtMethod(Method m) throws NotFoundException { return getCtClass(m.getDeclaringClass()).getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); } private CtConstructor getCtConstructor(Constructor<?> c) throws NotFoundException { return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); } public static interface DC {} // dynamic class tag interface. }
6,983
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/bytecode/NoSuchMethodException.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.bytecode; /** * NoSuchMethodException. */ public class NoSuchMethodException extends RuntimeException { private static final long serialVersionUID = -2725364246023268766L; public NoSuchMethodException() { super(); } public NoSuchMethodException(String msg) { super(msg); } }
6,984
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/profiler/ProfilerSwitch.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.profiler; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * TODO */ public class ProfilerSwitch { private static final AtomicBoolean enableDetailProfiler = new AtomicBoolean(false); private static final AtomicBoolean enableSimpleProfiler = new AtomicBoolean(true); private static final AtomicReference<Double> warnPercent = new AtomicReference<>(0.75); public static void enableSimpleProfiler() { enableSimpleProfiler.set(true); } public static void disableSimpleProfiler() { enableSimpleProfiler.set(false); } public static void enableDetailProfiler() { enableDetailProfiler.set(true); } public static void disableDetailProfiler() { enableDetailProfiler.set(false); } public static boolean isEnableDetailProfiler() { return enableDetailProfiler.get() && enableSimpleProfiler.get(); } public static boolean isEnableSimpleProfiler() { return enableSimpleProfiler.get(); } public static double getWarnPercent() { return warnPercent.get(); } public static void setWarnPercent(double percent) { warnPercent.set(percent); } }
6,985
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/profiler/Profiler.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.profiler; import org.apache.dubbo.common.threadlocal.InternalThreadLocal; import java.util.LinkedList; import java.util.List; public class Profiler { public static final String PROFILER_KEY = "DUBBO_INVOKE_PROFILER"; public static final int MAX_ENTRY_SIZE = 1000; private static final InternalThreadLocal<ProfilerEntry> bizProfiler = new InternalThreadLocal<>(); public static ProfilerEntry start(String message) { return new ProfilerEntry(message); } public static ProfilerEntry enter(ProfilerEntry entry, String message) { ProfilerEntry subEntry = new ProfilerEntry(message, entry, entry.getFirst()); if (subEntry.getRequestCount().incrementAndGet() < MAX_ENTRY_SIZE) { entry.getSub().add(subEntry); } // ignore if sub entry size is exceed return subEntry; } public static ProfilerEntry release(ProfilerEntry entry) { entry.setEndTime(System.nanoTime()); ProfilerEntry parent = entry.getParent(); if (parent != null) { return parent; } else { return entry; } } public static ProfilerEntry setToBizProfiler(ProfilerEntry entry) { try { return bizProfiler.get(); } finally { bizProfiler.set(entry); } } public static ProfilerEntry getBizProfiler() { return bizProfiler.get(); } public static void removeBizProfiler() { bizProfiler.remove(); } public static String buildDetail(ProfilerEntry entry) { long totalUsageTime = entry.getEndTime() - entry.getStartTime(); return "Start time: " + entry.getStartTime() + "\n" + String.join("\n", buildDetail(entry, entry.getStartTime(), totalUsageTime, 0)); } public static List<String> buildDetail(ProfilerEntry entry, long startTime, long totalUsageTime, int depth) { StringBuilder stringBuilder = new StringBuilder(); long usage = entry.getEndTime() - entry.getStartTime(); int percent = (int) (((usage) * 100) / totalUsageTime); long offset = entry.getStartTime() - startTime; List<String> lines = new LinkedList<>(); stringBuilder .append("+-[ Offset: ") .append(offset / 1000_000) .append('.') .append(String.format("%06d", offset % 1000_000)) .append("ms; Usage: ") .append(usage / 1000_000) .append('.') .append(String.format("%06d", usage % 1000_000)) .append("ms, ") .append(percent) .append("% ] ") .append(entry.getMessage()); lines.add(stringBuilder.toString()); List<ProfilerEntry> entrySub = entry.getSub(); for (int i = 0, entrySubSize = entrySub.size(); i < entrySubSize; i++) { ProfilerEntry sub = entrySub.get(i); List<String> subLines = buildDetail(sub, startTime, totalUsageTime, depth + 1); if (i < entrySubSize - 1) { lines.add(" " + subLines.get(0)); for (int j = 1, subLinesSize = subLines.size(); j < subLinesSize; j++) { String subLine = subLines.get(j); lines.add(" |" + subLine); } } else { lines.add(" " + subLines.get(0)); for (int j = 1, subLinesSize = subLines.size(); j < subLinesSize; j++) { String subLine = subLines.get(j); lines.add(" " + subLine); } } } return lines; } }
6,986
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/profiler/ProfilerEntry.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.profiler; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class ProfilerEntry { private final List<ProfilerEntry> sub = new ArrayList<>(4); private final String message; private final ProfilerEntry parent; private final ProfilerEntry first; private final long startTime; private final AtomicInteger requestCount; private long endTime; public ProfilerEntry(String message) { this.message = message; this.parent = null; this.first = this; this.startTime = System.nanoTime(); this.requestCount = new AtomicInteger(1); } public ProfilerEntry(String message, ProfilerEntry parentEntry, ProfilerEntry firstEntry) { this.message = message; this.parent = parentEntry; this.first = firstEntry; this.startTime = System.nanoTime(); this.requestCount = parentEntry.getRequestCount(); } public List<ProfilerEntry> getSub() { return sub; } public String getMessage() { return message; } public ProfilerEntry getParent() { return parent; } public ProfilerEntry getFirst() { return first; } public long getStartTime() { return startTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public long getEndTime() { return endTime; } public AtomicInteger getRequestCount() { return requestCount; } }
6,987
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/resource/Disposable.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.resource; /** * An interface for destroying resources */ public interface Disposable { void destroy(); }
6,988
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/resource/GlobalResourceInitializer.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.resource; import org.apache.dubbo.common.concurrent.CallableSafeInitializer; import java.util.concurrent.Callable; import java.util.function.Consumer; /** * A initializer to release resource automatically on dubbo shutdown */ public class GlobalResourceInitializer<T> extends CallableSafeInitializer<T> { /** * The Dispose action to be executed on shutdown. */ private Consumer<T> disposeAction; private Disposable disposable; public GlobalResourceInitializer(Callable<T> initializer) { super(initializer); } public GlobalResourceInitializer(Callable<T> initializer, Consumer<T> disposeAction) { super(initializer); this.disposeAction = disposeAction; } public GlobalResourceInitializer(Callable<T> callable, Disposable disposable) { super(callable); this.disposable = disposable; } @Override protected T initialize() { T value = super.initialize(); // register disposable to release automatically if (this.disposable != null) { GlobalResourcesRepository.getInstance().registerDisposable(this.disposable); } else { GlobalResourcesRepository.getInstance().registerDisposable(() -> this.remove(disposeAction)); } return value; } }
6,989
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/resource/GlobalResourcesRepository.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.resource; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Global resource repository between all framework models. * It will be destroyed only after all framework model is destroyed. */ public class GlobalResourcesRepository { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GlobalResourcesRepository.class); private static volatile GlobalResourcesRepository instance; private volatile ExecutorService executorService; private final List<Disposable> oneoffDisposables = new CopyOnWriteArrayList<>(); private static final List<Disposable> globalReusedDisposables = new CopyOnWriteArrayList<>(); private GlobalResourcesRepository() {} public static GlobalResourcesRepository getInstance() { if (instance == null) { synchronized (GlobalResourcesRepository.class) { if (instance == null) { instance = new GlobalResourcesRepository(); } } } return instance; } /** * Register a global reused disposable. The disposable will be executed when all dubbo FrameworkModels are destroyed. * Note: the global disposable should be registered in static code, it's reusable and will not be removed when dubbo shutdown. * * @param disposable */ public static void registerGlobalDisposable(Disposable disposable) { if (!globalReusedDisposables.contains(disposable)) { synchronized (GlobalResourcesRepository.class) { if (!globalReusedDisposables.contains(disposable)) { globalReusedDisposables.add(disposable); } } } } public void removeGlobalDisposable(Disposable disposable) { if (globalReusedDisposables.contains(disposable)) { synchronized (GlobalResourcesRepository.class) { if (globalReusedDisposables.contains(disposable)) { this.globalReusedDisposables.remove(disposable); } } } } public static ExecutorService getGlobalExecutorService() { return getInstance().getExecutorService(); } public ExecutorService getExecutorService() { if (executorService == null || executorService.isShutdown()) { synchronized (this) { if (executorService == null || executorService.isShutdown()) { if (logger.isInfoEnabled()) { logger.info("Creating global shared handler ..."); } executorService = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-global-shared-handler", true)); } } } return executorService; } public synchronized void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroying global resources ..."); } if (executorService != null) { executorService.shutdownNow(); try { if (!executorService.awaitTermination( ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Wait global executor service terminated timeout."); } } catch (InterruptedException e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } executorService = null; } // call one-off disposables for (Disposable disposable : new ArrayList<>(oneoffDisposables)) { try { disposable.destroy(); } catch (Exception e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } } // clear one-off disposable oneoffDisposables.clear(); // call global disposable, don't clear globalReusedDisposables for reuse purpose for (Disposable disposable : new ArrayList<>(globalReusedDisposables)) { try { disposable.destroy(); } catch (Exception e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } } if (logger.isInfoEnabled()) { logger.info("Dubbo is completely destroyed"); } } /** * Register a one-off disposable, the disposable is removed automatically on first shutdown. * * @param disposable */ public void registerDisposable(Disposable disposable) { if (!oneoffDisposables.contains(disposable)) { synchronized (this) { if (!oneoffDisposables.contains(disposable)) { oneoffDisposables.add(disposable); } } } } public void removeDisposable(Disposable disposable) { if (oneoffDisposables.contains(disposable)) { synchronized (this) { if (oneoffDisposables.contains(disposable)) { oneoffDisposables.remove(disposable); } } } } // for test public static List<Disposable> getGlobalReusedDisposables() { return globalReusedDisposables; } // for test public List<Disposable> getOneoffDisposables() { return oneoffDisposables; } }
6,990
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/compiler/Compiler.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.compiler; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * Compiler. (SPI, Singleton, ThreadSafe) */ @SPI(value = "javassist", scope = ExtensionScope.FRAMEWORK) public interface Compiler { /** * Compile java source code. * * @param code Java source code * @param classLoader classloader * @return Compiled class * @deprecated use {@link Compiler#compile(Class, String, ClassLoader)} to support JDK 16 */ @Deprecated default Class<?> compile(String code, ClassLoader classLoader) { return compile(null, code, classLoader); } /** * Compile java source code. * * @param neighbor A class belonging to the same package that this * class belongs to. It is used to load the class. (For JDK 16 and above) * @param code Java source code * @param classLoader classloader * @return Compiled class */ default Class<?> compile(Class<?> neighbor, String code, ClassLoader classLoader) { return compile(code, classLoader); } }
6,991
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.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.compiler.support; import org.apache.dubbo.common.compiler.Compiler; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Abstract compiler. (SPI, Prototype, ThreadSafe) */ public abstract class AbstractCompiler implements Compiler { private static final Pattern PACKAGE_PATTERN = Pattern.compile("package\\s+([$_a-zA-Z][$_a-zA-Z0-9\\.]*);"); private static final Pattern CLASS_PATTERN = Pattern.compile("class\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)\\s+"); private static final Map<String, Lock> CLASS_IN_CREATION_MAP = new ConcurrentHashMap<>(); @Override public Class<?> compile(Class<?> neighbor, String code, ClassLoader classLoader) { code = code.trim(); Matcher matcher = PACKAGE_PATTERN.matcher(code); String pkg; if (matcher.find()) { pkg = matcher.group(1); } else { pkg = ""; } matcher = CLASS_PATTERN.matcher(code); String cls; if (matcher.find()) { cls = matcher.group(1); } else { throw new IllegalArgumentException("No such class name in " + code); } String className = pkg != null && pkg.length() > 0 ? pkg + "." + cls : cls; Lock lock = CLASS_IN_CREATION_MAP.get(className); if (lock == null) { CLASS_IN_CREATION_MAP.putIfAbsent(className, new ReentrantLock()); lock = CLASS_IN_CREATION_MAP.get(className); } try { lock.lock(); return Class.forName(className, true, classLoader); } catch (ClassNotFoundException e) { if (!code.endsWith("}")) { throw new IllegalStateException("The java code not endsWith \"}\", code: \n" + code + "\n"); } try { return doCompile(neighbor, classLoader, className, code); } catch (RuntimeException t) { throw t; } catch (Throwable t) { throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: " + className + ", code: \n" + code + "\n, stack: " + ClassUtils.toString(t)); } } finally { lock.unlock(); } } protected Class<?> doCompile(ClassLoader classLoader, String name, String source) throws Throwable { return null; } protected Class<?> doCompile(Class<?> neighbor, ClassLoader classLoader, String name, String source) throws Throwable { return doCompile(classLoader, name, source); } }
6,992
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/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.compiler.support; import org.apache.dubbo.common.utils.StringUtils; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * ClassUtils. (Tool, Static, ThreadSafe) */ public class ClassUtils { public static final String CLASS_EXTENSION = ".class"; public static final String JAVA_EXTENSION = ".java"; private static final int JIT_LIMIT = 5 * 1024; private ClassUtils() {} public static Object newInstance(String name) { try { return forName(name).getDeclaredConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalStateException(e.getMessage(), e); } } public static Class<?> forName(String[] packages, String className) { try { return classForName(className); } catch (ClassNotFoundException e) { if (packages != null && packages.length > 0) { for (String pkg : packages) { try { return classForName(pkg + "." + className); } catch (ClassNotFoundException ignore) { } } } throw new IllegalStateException(e.getMessage(), e); } } public static Class<?> forName(String className) { try { return classForName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } } public static Class<?> classForName(String className) throws ClassNotFoundException { switch (className) { case "boolean": return boolean.class; case "byte": return byte.class; case "char": return char.class; case "short": return short.class; case "int": return int.class; case "long": return long.class; case "float": return float.class; case "double": return double.class; case "boolean[]": return boolean[].class; case "byte[]": return byte[].class; case "char[]": return char[].class; case "short[]": return short[].class; case "int[]": return int[].class; case "long[]": return long[].class; case "float[]": return float[].class; case "double[]": return double[].class; default: } try { return arrayForName(className); } catch (ClassNotFoundException e) { // try to load from java.lang package if (className.indexOf('.') == -1) { try { return arrayForName("java.lang." + className); } catch (ClassNotFoundException ignore) { // ignore, let the original exception be thrown } } throw e; } } private static Class<?> arrayForName(String className) throws ClassNotFoundException { return Class.forName( className.endsWith("[]") ? "[L" + className.substring(0, className.length() - 2) + ";" : className, true, Thread.currentThread().getContextClassLoader()); } public static Class<?> getBoxedClass(Class<?> type) { if (type == boolean.class) { return Boolean.class; } else if (type == char.class) { return Character.class; } else if (type == byte.class) { return Byte.class; } else if (type == short.class) { return Short.class; } else if (type == int.class) { return Integer.class; } else if (type == long.class) { return Long.class; } else if (type == float.class) { return Float.class; } else if (type == double.class) { return Double.class; } else { return type; } } public static Boolean boxed(boolean v) { return Boolean.valueOf(v); } public static Character boxed(char v) { return Character.valueOf(v); } public static Byte boxed(byte v) { return Byte.valueOf(v); } public static Short boxed(short v) { return Short.valueOf(v); } public static Integer boxed(int v) { return Integer.valueOf(v); } public static Long boxed(long v) { return Long.valueOf(v); } public static Float boxed(float v) { return Float.valueOf(v); } public static Double boxed(double v) { return Double.valueOf(v); } public static Object boxed(Object v) { return v; } public static boolean unboxed(Boolean v) { return v == null ? false : v.booleanValue(); } public static char unboxed(Character v) { return v == null ? '\0' : v.charValue(); } public static byte unboxed(Byte v) { return v == null ? 0 : v.byteValue(); } public static short unboxed(Short v) { return v == null ? 0 : v.shortValue(); } public static int unboxed(Integer v) { return v == null ? 0 : v.intValue(); } public static long unboxed(Long v) { return v == null ? 0 : v.longValue(); } public static float unboxed(Float v) { return v == null ? 0 : v.floatValue(); } public static double unboxed(Double v) { return v == null ? 0 : v.doubleValue(); } public static Object unboxed(Object v) { return v; } public static boolean isNotEmpty(Object object) { return getSize(object) > 0; } public static int getSize(Object object) { if (object == null) { return 0; } if (object instanceof Collection<?>) { return ((Collection<?>) object).size(); } else if (object instanceof Map<?, ?>) { return ((Map<?, ?>) object).size(); } else if (object.getClass().isArray()) { return Array.getLength(object); } else { return -1; } } public static URI toURI(String name) { try { return new URI(name); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public static boolean isBeforeJava5(String javaVersion) { return (StringUtils.isEmpty(javaVersion) || "1.0".equals(javaVersion) || "1.1".equals(javaVersion) || "1.2".equals(javaVersion) || "1.3".equals(javaVersion) || "1.4".equals(javaVersion)); } public static boolean isBeforeJava6(String javaVersion) { return isBeforeJava5(javaVersion) || "1.5".equals(javaVersion); } public static String toString(Throwable e) { StringWriter w = new StringWriter(); PrintWriter p = new PrintWriter(w); p.print(e.getClass().getName() + ": "); if (e.getMessage() != null) { p.print(e.getMessage() + "\n"); } p.println(); try { e.printStackTrace(p); return w.toString(); } finally { p.close(); } } public static void checkBytecode(String name, byte[] bytecode) { if (bytecode.length > JIT_LIMIT) { System.err.println( "The template bytecode too long, may be affect the JIT compiler. template class: " + name); } } public static String getSizeMethod(Class<?> cls) { try { return cls.getMethod("size", new Class<?>[0]).getName() + "()"; } catch (NoSuchMethodException e) { try { return cls.getMethod("length", new Class<?>[0]).getName() + "()"; } catch (NoSuchMethodException e2) { try { return cls.getMethod("getSize", new Class<?>[0]).getName() + "()"; } catch (NoSuchMethodException e3) { try { return cls.getMethod("getLength", new Class<?>[0]).getName() + "()"; } catch (NoSuchMethodException e4) { return null; } } } } } public static String getMethodName(Method method, Class<?>[] parameterClasses, String rightCode) { StringBuilder buf = new StringBuilder(rightCode); if (method.getParameterTypes().length > parameterClasses.length) { Class<?>[] types = method.getParameterTypes(); for (int i = parameterClasses.length; i < types.length; i++) { if (buf.length() > 0) { buf.append(','); } Class<?> type = types[i]; String def; if (type == boolean.class) { def = "false"; } else if (type == char.class) { def = "\'\\0\'"; } else if (type == byte.class || type == short.class || type == int.class || type == long.class || type == float.class || type == double.class) { def = "0"; } else { def = "null"; } buf.append(def); } } return method.getName() + "(" + buf + ")"; } public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes) throws NoSuchMethodException { if (currentClass == null) { throw new NoSuchMethodException("class == null"); } try { return currentClass.getMethod(name, parameterTypes); } catch (NoSuchMethodException e) { for (Method method : currentClass.getMethods()) { if (method.getName().equals(name) && parameterTypes.length == method.getParameterTypes().length && Modifier.isPublic(method.getModifiers())) { if (parameterTypes.length > 0) { Class<?>[] types = method.getParameterTypes(); boolean match = true; for (int i = 0; i < parameterTypes.length; i++) { if (!types[i].isAssignableFrom(parameterTypes[i])) { match = false; break; } } if (!match) { continue; } } return method; } } throw e; } } public static String getInitCode(Class<?> type) { if (byte.class.equals(type) || short.class.equals(type) || int.class.equals(type) || long.class.equals(type) || float.class.equals(type) || double.class.equals(type)) { return "0"; } else if (char.class.equals(type)) { return "'\\0'"; } else if (boolean.class.equals(type)) { return "false"; } else { return "null"; } } public static <K, V> Map<K, V> toMap(Map.Entry<K, V>[] entries) { Map<K, V> map = new HashMap<K, V>(); if (entries != null && entries.length > 0) { for (Map.Entry<K, V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } } return map; } /** * get simple class name from qualified class name */ public static String getSimpleClassName(String qualifiedName) { if (null == qualifiedName) { return null; } int i = qualifiedName.lastIndexOf('.'); return i < 0 ? qualifiedName : qualifiedName.substring(i + 1); } }
6,993
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.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.compiler.support; import javax.tools.DiagnosticCollector; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * JdkCompiler. (SPI, Singleton, ThreadSafe) */ public class JdkCompiler extends AbstractCompiler { private final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); private final DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); private final ClassLoaderImpl classLoader; private final JavaFileManagerImpl javaFileManager; private final List<String> options; private static final String DEFAULT_JAVA_VERSION = "1.8"; private static List<String> buildDefaultOptions(String javaVersion) { return Arrays.asList("-source", javaVersion, "-target", javaVersion); } private static List<String> buildDefaultOptions() { return buildDefaultOptions(DEFAULT_JAVA_VERSION); } public JdkCompiler(List<String> options) { this.options = new ArrayList<>(options); StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null); final ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader instanceof URLClassLoader && (!"sun.misc.Launcher$AppClassLoader".equals(loader.getClass().getName()))) { try { URLClassLoader urlClassLoader = (URLClassLoader) loader; List<File> files = new ArrayList<>(); for (URL url : urlClassLoader.getURLs()) { files.add(new File(url.getFile())); } manager.setLocation(StandardLocation.CLASS_PATH, files); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } } classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() { @Override public ClassLoaderImpl run() { return new ClassLoaderImpl(loader); } }); javaFileManager = new JavaFileManagerImpl(manager, classLoader); } public JdkCompiler() { this(buildDefaultOptions()); } public JdkCompiler(String javaVersion) { this(buildDefaultOptions(javaVersion)); } @Override public Class<?> doCompile(ClassLoader ignored, String name, String sourceCode) throws Throwable { int i = name.lastIndexOf('.'); String packageName = i < 0 ? "" : name.substring(0, i); String className = i < 0 ? name : name.substring(i + 1); JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode); javaFileManager.putFileForInput( StandardLocation.SOURCE_PATH, packageName, className + ClassUtils.JAVA_EXTENSION, javaFileObject); Boolean result = compiler.getTask( null, javaFileManager, diagnosticCollector, options, null, Collections.singletonList(javaFileObject)) .call(); if (result == null || !result) { throw new IllegalStateException( "Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector.getDiagnostics()); } return classLoader.loadClass(name); } private static final class JavaFileObjectImpl extends SimpleJavaFileObject { private final CharSequence source; private ByteArrayOutputStream bytecode; public JavaFileObjectImpl(final String baseName, final CharSequence source) { super(ClassUtils.toURI(baseName + ClassUtils.JAVA_EXTENSION), Kind.SOURCE); this.source = source; } JavaFileObjectImpl(final String name, final Kind kind) { super(ClassUtils.toURI(name), kind); source = null; } public JavaFileObjectImpl(URI uri, Kind kind) { super(uri, kind); source = null; } @Override public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws UnsupportedOperationException { if (source == null) { throw new UnsupportedOperationException("source == null"); } return source; } @Override public InputStream openInputStream() { return new ByteArrayInputStream(getByteCode()); } @Override public OutputStream openOutputStream() { return bytecode = new ByteArrayOutputStream(); } public byte[] getByteCode() { return bytecode.toByteArray(); } } private static final class JavaFileManagerImpl extends ForwardingJavaFileManager<JavaFileManager> { private final ClassLoaderImpl classLoader; private final Map<URI, JavaFileObject> fileObjects = new HashMap<>(); public JavaFileManagerImpl(JavaFileManager fileManager, ClassLoaderImpl classLoader) { super(fileManager); this.classLoader = classLoader; } @Override public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { FileObject o = fileObjects.get(uri(location, packageName, relativeName)); if (o != null) { return o; } return super.getFileForInput(location, packageName, relativeName); } public void putFileForInput( StandardLocation location, String packageName, String relativeName, JavaFileObject file) { fileObjects.put(uri(location, packageName, relativeName), file); } private URI uri(Location location, String packageName, String relativeName) { return ClassUtils.toURI(location.getName() + '/' + packageName + '/' + relativeName); } @Override public JavaFileObject getJavaFileForOutput( Location location, String qualifiedName, Kind kind, FileObject outputFile) throws IOException { JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind); classLoader.add(qualifiedName, file); return file; } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { return classLoader; } @Override public String inferBinaryName(Location loc, JavaFileObject file) { if (file instanceof JavaFileObjectImpl) { return file.getName(); } return super.inferBinaryName(loc, file); } @Override public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException { Iterable<JavaFileObject> result = super.list(location, packageName, kinds, recurse); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); ArrayList<JavaFileObject> files = new ArrayList<>(); if (location == StandardLocation.CLASS_PATH && kinds.contains(JavaFileObject.Kind.CLASS)) { for (JavaFileObject file : fileObjects.values()) { if (file.getKind() == Kind.CLASS && file.getName().startsWith(packageName)) { files.add(file); } } files.addAll(classLoader.files()); } else if (location == StandardLocation.SOURCE_PATH && kinds.contains(JavaFileObject.Kind.SOURCE)) { for (JavaFileObject file : fileObjects.values()) { if (file.getKind() == Kind.SOURCE && file.getName().startsWith(packageName)) { files.add(file); } } } for (JavaFileObject file : result) { files.add(file); } return files; } } private static final class ClassLoaderImpl extends ClassLoader { private final Map<String, JavaFileObject> classes = new HashMap<>(); ClassLoaderImpl(final ClassLoader parentClassLoader) { super(parentClassLoader); } Collection<JavaFileObject> files() { return Collections.unmodifiableCollection(classes.values()); } @Override protected Class<?> findClass(final String qualifiedClassName) throws ClassNotFoundException { JavaFileObject file = classes.get(qualifiedClassName); if (file != null) { byte[] bytes = ((JavaFileObjectImpl) file).getByteCode(); return defineClass(qualifiedClassName, bytes, 0, bytes.length); } try { return org.apache.dubbo.common.utils.ClassUtils.forNameWithCallerClassLoader( qualifiedClassName, getClass()); } catch (ClassNotFoundException nf) { return super.findClass(qualifiedClassName); } } void add(final String qualifiedClassName, final JavaFileObject javaFile) { classes.put(qualifiedClassName, javaFile); } @Override protected synchronized Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { return super.loadClass(name, resolve); } @Override public InputStream getResourceAsStream(final String name) { if (name.endsWith(ClassUtils.CLASS_EXTENSION)) { String qualifiedClassName = name.substring(0, name.length() - ClassUtils.CLASS_EXTENSION.length()) .replace('/', '.'); JavaFileObjectImpl file = (JavaFileObjectImpl) classes.get(qualifiedClassName); if (file != null) { return new ByteArrayInputStream(file.getByteCode()); } } return super.getResourceAsStream(name); } } }
6,994
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.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.compiler.support; import org.apache.dubbo.common.compiler.Compiler; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; /** * AdaptiveCompiler. (SPI, Singleton, ThreadSafe) */ @Adaptive public class AdaptiveCompiler implements Compiler, ScopeModelAware { private FrameworkModel frameworkModel; @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } private static volatile String DEFAULT_COMPILER; public static void setDefaultCompiler(String compiler) { DEFAULT_COMPILER = compiler; } @Override public Class<?> compile(Class<?> neighbor, String code, ClassLoader classLoader) { Compiler compiler; ExtensionLoader<Compiler> loader = frameworkModel.getExtensionLoader(Compiler.class); String name = DEFAULT_COMPILER; // copy reference if (name != null && name.length() > 0) { compiler = loader.getExtension(name); } else { compiler = loader.getDefaultExtension(); } return compiler.compile(neighbor, code, classLoader); } }
6,995
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.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.compiler.support; import org.apache.dubbo.common.bytecode.DubboLoaderClassPath; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; /** * CtClassBuilder is builder for CtClass * <p> * contains all the information, including: * <p> * class name, imported packages, super class name, implemented interfaces, constructors, fields, methods. */ public class CtClassBuilder { private String className; private String superClassName = "java.lang.Object"; private final List<String> imports = new ArrayList<>(); private final Map<String, String> fullNames = new HashMap<>(); private final List<String> ifaces = new ArrayList<>(); private final List<String> constructors = new ArrayList<>(); private final List<String> fields = new ArrayList<>(); private final List<String> methods = new ArrayList<>(); public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getSuperClassName() { return superClassName; } public void setSuperClassName(String superClassName) { this.superClassName = getQualifiedClassName(superClassName); } public List<String> getImports() { return imports; } public void addImports(String pkg) { int pi = pkg.lastIndexOf('.'); if (pi > 0) { String pkgName = pkg.substring(0, pi); this.imports.add(pkgName); if (!pkg.endsWith(".*")) { fullNames.put(pkg.substring(pi + 1), pkg); } } } public List<String> getInterfaces() { return ifaces; } public void addInterface(String iface) { this.ifaces.add(getQualifiedClassName(iface)); } public List<String> getConstructors() { return constructors; } public void addConstructor(String constructor) { this.constructors.add(constructor); } public List<String> getFields() { return fields; } public void addField(String field) { this.fields.add(field); } public List<String> getMethods() { return methods; } public void addMethod(String method) { this.methods.add(method); } /** * get full qualified class name * * @param className super class name, maybe qualified or not */ protected String getQualifiedClassName(String className) { if (className.contains(".")) { return className; } if (fullNames.containsKey(className)) { return fullNames.get(className); } return ClassUtils.forName(imports.toArray(new String[0]), className).getName(); } /** * build CtClass object */ public CtClass build(ClassLoader classLoader) throws NotFoundException, CannotCompileException { ClassPool pool = new ClassPool(true); pool.insertClassPath(new LoaderClassPath(classLoader)); pool.insertClassPath(new DubboLoaderClassPath()); // create class CtClass ctClass = pool.makeClass(className, pool.get(superClassName)); // add imported packages imports.forEach(pool::importPackage); // add implemented interfaces for (String iface : ifaces) { ctClass.addInterface(pool.get(iface)); } // add constructors for (String constructor : constructors) { ctClass.addConstructor(CtNewConstructor.make(constructor, ctClass)); } // add fields for (String field : fields) { ctClass.addField(CtField.make(field, ctClass)); } // add methods for (String method : methods) { ctClass.addMethod(CtNewMethod.make(method, ctClass)); } return ctClass; } }
6,996
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.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.compiler.support; import org.apache.dubbo.common.bytecode.DubboLoaderClassPath; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.LoaderClassPath; /** * JavassistCompiler. (SPI, Singleton, ThreadSafe) */ public class JavassistCompiler extends AbstractCompiler { private static final Pattern IMPORT_PATTERN = Pattern.compile("import\\s+([\\w\\.\\*]+);\n"); private static final Pattern EXTENDS_PATTERN = Pattern.compile("\\s+extends\\s+([\\w\\.]+)[^\\{]*\\{\n"); private static final Pattern IMPLEMENTS_PATTERN = Pattern.compile("\\s+implements\\s+([\\w\\.]+)\\s*\\{\n"); private static final Pattern METHODS_PATTERN = Pattern.compile("\n(private|public|protected)\\s+"); private static final Pattern FIELD_PATTERN = Pattern.compile("[^\n]+=[^\n]+;"); @Override public Class<?> doCompile(Class<?> neighbor, ClassLoader classLoader, String name, String source) throws Throwable { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(name); // process imported classes Matcher matcher = IMPORT_PATTERN.matcher(source); while (matcher.find()) { builder.addImports(matcher.group(1).trim()); } // process extended super class matcher = EXTENDS_PATTERN.matcher(source); if (matcher.find()) { builder.setSuperClassName(matcher.group(1).trim()); } // process implemented interfaces matcher = IMPLEMENTS_PATTERN.matcher(source); if (matcher.find()) { String[] ifaces = matcher.group(1).trim().split("\\,"); Arrays.stream(ifaces).forEach(i -> builder.addInterface(i.trim())); } // process constructors, fields, methods String body = source.substring(source.indexOf('{') + 1, source.length() - 1); String[] methods = METHODS_PATTERN.split(body); String className = ClassUtils.getSimpleClassName(name); Arrays.stream(methods).map(String::trim).filter(m -> !m.isEmpty()).forEach(method -> { if (method.startsWith(className)) { builder.addConstructor("public " + method); } else if (FIELD_PATTERN.matcher(method).matches()) { builder.addField("private " + method); } else { builder.addMethod("public " + method); } }); // compile CtClass cls = builder.build(classLoader); ClassPool cp = cls.getClassPool(); if (classLoader == null) { classLoader = cp.getClassLoader(); } cp.insertClassPath(new LoaderClassPath(classLoader)); cp.insertClassPath(new DubboLoaderClassPath()); try { return cp.toClass(cls, neighbor, classLoader, JavassistCompiler.class.getProtectionDomain()); } catch (Throwable t) { if (!(t instanceof CannotCompileException)) { return cp.toClass(cls, classLoader, JavassistCompiler.class.getProtectionDomain()); } throw t; } } }
6,997
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/reference/ReferenceCountedResource.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.reference; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; /** * inspired by Netty */ public abstract class ReferenceCountedResource implements AutoCloseable { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedResource.class); private static final AtomicLongFieldUpdater<ReferenceCountedResource> COUNTER_UPDATER = AtomicLongFieldUpdater.newUpdater(ReferenceCountedResource.class, "counter"); private volatile long counter = 1; /** * Increments the reference count by 1. */ public final ReferenceCountedResource retain() { long oldCount = COUNTER_UPDATER.getAndIncrement(this); if (oldCount <= 0) { COUNTER_UPDATER.getAndDecrement(this); throw new AssertionError("This instance has been destroyed"); } return this; } /** * Decreases the reference count by 1 and calls {@link this#destroy} if the reference count reaches 0. */ public final boolean release() { long remainingCount = COUNTER_UPDATER.decrementAndGet(this); if (remainingCount == 0) { destroy(); return true; } else if (remainingCount <= -1) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "This instance has been destroyed"); return false; } else { return false; } } /** * Useful when used together with try-with-resources pattern */ @Override public final void close() { release(); } /** * This method will be invoked when counter reaches 0, override this method to destroy materials related to the specific resource. */ protected abstract void destroy(); }
6,998
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/convert/StringToFloatConverter.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.convert; import static java.lang.Float.valueOf; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; /** * The class to convert {@link String} to {@link Float} * * @since 2.7.6 */ public class StringToFloatConverter implements StringConverter<Float> { @Override public Float convert(String source) { return isNotEmpty(source) ? valueOf(source) : null; } @Override public int getPriority() { return NORMAL_PRIORITY + 4; } }
6,999