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/convert/StringToStringConverter.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;
/**
* A class to covert {@link String} to {@link String} value, just no-op
*
* @since 2.7.6
*/
public class StringToStringConverter implements StringConverter<String> {
@Override
public String convert(String source) {
return source;
}
}
| 7,000 |
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/StringToByteConverter.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 org.apache.dubbo.common.utils.StringUtils;
/**
* The class to convert {@link String} to {@link Byte}
*
* @since 3.0.4
*/
public class StringToByteConverter implements StringConverter<Byte> {
@Override
public Byte convert(String source) {
return StringUtils.isNotEmpty(source) ? Byte.valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 9;
}
}
| 7,001 |
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/StringConverter.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;
/**
* A class to covert {@link String} to the target-typed value
*
* @see Converter
* @since 2.7.6
*/
@FunctionalInterface
public interface StringConverter<T> extends Converter<String, T> {}
| 7,002 |
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/StringToDurationConverter.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 org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.StringUtils;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
public class StringToDurationConverter implements StringConverter<Duration> {
@Override
public Duration convert(String source) {
return isNotEmpty(source) ? DurationStyle.detectAndParse(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 10;
}
/**
* @author Phillip Webb
* @author Valentine Wu
* @link {org.springframework.boot.convert.DurationStyle}
*/
enum DurationStyle {
/**
* Simple formatting, for example '1s'.
*/
SIMPLE("^([+-]?\\d+)([a-zA-Z]{0,2})$") {
@Override
public Duration parse(String value, ChronoUnit unit) {
try {
Matcher matcher = matcher(value);
Assert.assertTrue(matcher.matches(), "Does not match simple duration pattern");
String suffix = matcher.group(2);
return (StringUtils.isNotBlank(suffix)
? TimeUnit.fromSuffix(suffix)
: TimeUnit.fromChronoUnit(unit))
.parse(matcher.group(1));
} catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid simple duration", ex);
}
}
},
/**
* ISO-8601 formatting.
*/
ISO8601("^[+-]?[pP].*$") {
@Override
public Duration parse(String value, ChronoUnit unit) {
try {
return Duration.parse(value);
} catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex);
}
}
};
private final Pattern pattern;
DurationStyle(String pattern) {
this.pattern = Pattern.compile(pattern);
}
protected final boolean matches(String value) {
return this.pattern.matcher(value).matches();
}
protected final Matcher matcher(String value) {
return this.pattern.matcher(value);
}
/**
* Parse the given value to a duration.
*
* @param value the value to parse
* @return a duration
*/
public Duration parse(String value) {
return parse(value, null);
}
/**
* Parse the given value to a duration.
*
* @param value the value to parse
* @param unit the duration unit to use if the value doesn't specify one ({@code null}
* will default to ms)
* @return a duration
*/
public abstract Duration parse(String value, ChronoUnit unit);
/**
* Detect the style then parse the value to return a duration.
*
* @param value the value to parse
* @return the parsed duration
* @throws IllegalArgumentException if the value is not a known style or cannot be
* parsed
*/
public static Duration detectAndParse(String value) {
return detectAndParse(value, null);
}
/**
* Detect the style then parse the value to return a duration.
*
* @param value the value to parse
* @param unit the duration unit to use if the value doesn't specify one ({@code null}
* will default to ms)
* @return the parsed duration
* @throws IllegalArgumentException if the value is not a known style or cannot be
* parsed
*/
public static Duration detectAndParse(String value, ChronoUnit unit) {
return detect(value).parse(value, unit);
}
/**
* Detect the style from the given source value.
*
* @param value the source value
* @return the duration style
* @throws IllegalArgumentException if the value is not a known style
*/
public static DurationStyle detect(String value) {
Assert.notNull(value, "Value must not be null");
for (DurationStyle candidate : values()) {
if (candidate.matches(value)) {
return candidate;
}
}
throw new IllegalArgumentException("'" + value + "' is not a valid duration");
}
/**
* Time Unit that support.
*/
enum TimeUnit {
/**
* Nanoseconds.
*/
NANOS(ChronoUnit.NANOS, "ns", Duration::toNanos),
/**
* Microseconds.
*/
MICROS(ChronoUnit.MICROS, "us", (duration) -> duration.toNanos() / 1000L),
/**
* Milliseconds.
*/
MILLIS(ChronoUnit.MILLIS, "ms", Duration::toMillis),
/**
* Seconds.
*/
SECONDS(ChronoUnit.SECONDS, "s", Duration::getSeconds),
/**
* Minutes.
*/
MINUTES(ChronoUnit.MINUTES, "m", Duration::toMinutes),
/**
* Hours.
*/
HOURS(ChronoUnit.HOURS, "h", Duration::toHours),
/**
* Days.
*/
DAYS(ChronoUnit.DAYS, "d", Duration::toDays);
private final ChronoUnit chronoUnit;
private final String suffix;
private final Function<Duration, Long> longValue;
TimeUnit(ChronoUnit chronoUnit, String suffix, Function<Duration, Long> toUnit) {
this.chronoUnit = chronoUnit;
this.suffix = suffix;
this.longValue = toUnit;
}
public Duration parse(String value) {
return Duration.of(Long.parseLong(value), this.chronoUnit);
}
public long longValue(Duration value) {
return this.longValue.apply(value);
}
public static TimeUnit fromChronoUnit(ChronoUnit chronoUnit) {
if (chronoUnit == null) {
return TimeUnit.MILLIS;
}
for (TimeUnit candidate : values()) {
if (candidate.chronoUnit == chronoUnit) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit " + chronoUnit);
}
public static TimeUnit fromSuffix(String suffix) {
for (TimeUnit candidate : values()) {
if (candidate.suffix.equalsIgnoreCase(suffix)) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit '" + suffix + "'");
}
}
}
}
| 7,003 |
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/StringToShortConverter.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.Short.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Short}
*
* @since 2.7.6
*/
public class StringToShortConverter implements StringConverter<Short> {
@Override
public Short convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 2;
}
}
| 7,004 |
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/StringToBooleanConverter.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.Boolean.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Boolean}
*
* @since 2.7.6
*/
public class StringToBooleanConverter implements StringConverter<Boolean> {
@Override
public Boolean convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 5;
}
}
| 7,005 |
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/StringToCharacterConverter.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 org.apache.dubbo.common.utils.StringUtils.length;
/**
* The class to convert {@link String} to {@link Character}
*
* @since 2.7.6
*/
public class StringToCharacterConverter implements StringConverter<Character> {
@Override
public Character convert(String source) {
int length = length(source);
if (length == 0) {
return null;
}
if (length > 1) {
throw new IllegalArgumentException("The source String is more than one character!");
}
return source.charAt(0);
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 8;
}
}
| 7,006 |
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/StringToOptionalConverter.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 java.util.Optional;
import static java.util.Optional.ofNullable;
/**
* The class to convert {@link String} to {@link Optional}
*
* @since 2.7.6
*/
public class StringToOptionalConverter implements StringConverter<Optional> {
@Override
public Optional convert(String source) {
return ofNullable(source);
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
}
| 7,007 |
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/StringToLongConverter.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.Long.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Long}
*
* @since 2.7.6
*/
public class StringToLongConverter implements StringConverter<Long> {
@Override
public Long convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 1;
}
}
| 7,008 |
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/StringToCharArrayConverter.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 org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to <code>char[]</code>
*
* @since 2.7.6
*/
public class StringToCharArrayConverter implements StringConverter<char[]> {
@Override
public char[] convert(String source) {
return isNotEmpty(source) ? source.toCharArray() : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 7;
}
}
| 7,009 |
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/Converter.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 org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
import static org.apache.dubbo.common.utils.TypeUtils.findActualTypeArgument;
/**
* A class to convert the source-typed value to the target-typed value
*
* @param <S> The source type
* @param <T> The target type
* @since 2.7.6
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
@FunctionalInterface
public interface Converter<S, T> extends Prioritized {
/**
* Accept the source type and target type or not
*
* @param sourceType the source type
* @param targetType the target type
* @return if accepted, return <code>true</code>, or <code>false</code>
*/
default boolean accept(Class<?> sourceType, Class<?> targetType) {
return isAssignableFrom(sourceType, getSourceType()) && isAssignableFrom(targetType, getTargetType());
}
/**
* Convert the source-typed value to the target-typed value
*
* @param source the source-typed value
* @return the target-typed value
*/
T convert(S source);
/**
* Get the source type
*
* @return non-null
*/
default Class<S> getSourceType() {
return findActualTypeArgument(getClass(), Converter.class, 0);
}
/**
* Get the target type
*
* @return non-null
*/
default Class<T> getTargetType() {
return findActualTypeArgument(getClass(), Converter.class, 1);
}
}
| 7,010 |
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/StringToIntegerConverter.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.Integer.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Integer}
*
* @since 2.7.6
*/
public class StringToIntegerConverter implements StringConverter<Integer> {
@Override
public Integer convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY;
}
}
| 7,011 |
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/ConverterUtil.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 org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class ConverterUtil {
private final FrameworkModel frameworkModel;
private final ConcurrentMap<Class<?>, ConcurrentMap<Class<?>, List<Converter>>> converterCache =
new ConcurrentHashMap<>();
public ConverterUtil(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
/**
* Get the Converter instance from {@link ExtensionLoader} with the specified source and target type
*
* @param sourceType the source type
* @param targetType the target type
* @return
* @see ExtensionLoader#getSupportedExtensionInstances()
*/
public Converter<?, ?> getConverter(Class<?> sourceType, Class<?> targetType) {
ConcurrentMap<Class<?>, List<Converter>> toTargetMap =
ConcurrentHashMapUtils.computeIfAbsent(converterCache, sourceType, (k) -> new ConcurrentHashMap<>());
List<Converter> converters = ConcurrentHashMapUtils.computeIfAbsent(
toTargetMap,
targetType,
(k) -> frameworkModel.getExtensionLoader(Converter.class).getSupportedExtensionInstances().stream()
.filter(converter -> converter.accept(sourceType, targetType))
.collect(Collectors.toList()));
return converters.size() > 0 ? converters.get(0) : null;
}
/**
* Convert the value of source to target-type value if possible
*
* @param source the value of source
* @param targetType the target type
* @param <T> the target type
* @return <code>null</code> if can't be converted
* @since 2.7.8
*/
public <T> T convertIfPossible(Object source, Class<T> targetType) {
Converter converter = getConverter(source.getClass(), targetType);
if (converter != null) {
return (T) converter.convert(source);
}
return null;
}
}
| 7,012 |
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/StringToDoubleConverter.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.Double.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Double}
*
* @since 2.7.6
*/
public class StringToDoubleConverter implements StringConverter<Double> {
@Override
public Double convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 3;
}
}
| 7,013 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
/**
* The class to convert {@link String} to {@link TransferQueue}-based value
*
* @since 2.7.6
*/
public class StringToTransferQueueConverter extends StringToIterableConverter<TransferQueue> {
public StringToTransferQueueConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected TransferQueue createMultiValue(int size, Class<?> multiValueType) {
return new LinkedTransferQueue();
}
}
| 7,014 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The class to convert {@link String} to {@link SortedSet}-based value
*
* @since 2.7.6
*/
public class StringToSortedSetConverter extends StringToIterableConverter<SortedSet> {
public StringToSortedSetConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected SortedSet createMultiValue(int size, Class<?> multiValueType) {
return new TreeSet();
}
}
| 7,015 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
/**
* The class to convert {@link String} to {@link BlockingDeque}-based value
*
* @since 2.7.6
*/
public class StringToBlockingQueueConverter extends StringToIterableConverter<BlockingQueue> {
public StringToBlockingQueueConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected BlockingQueue createMultiValue(int size, Class<?> multiValueType) {
return new ArrayBlockingQueue(size);
}
}
| 7,016 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.Collection;
/**
* The class to convert {@link String} to {@link Collection}-based value
*
* @since 2.7.6
*/
public class StringToCollectionConverter extends StringToIterableConverter<Collection> {
public StringToCollectionConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Collection createMultiValue(int size, Class<?> multiValueType) {
return new ArrayList(size);
}
}
| 7,017 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.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.multiple;
import org.apache.dubbo.common.convert.ConverterUtil;
import org.apache.dubbo.common.convert.StringConverter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collection;
import java.util.Optional;
import static org.apache.dubbo.common.utils.ClassUtils.getAllInterfaces;
import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
import static org.apache.dubbo.common.utils.TypeUtils.findActualTypeArgument;
/**
* The class to convert {@link String} to {@link Iterable}-based value
*
* @since 2.7.6
*/
public abstract class StringToIterableConverter<T extends Iterable> implements StringToMultiValueConverter {
private ConverterUtil converterUtil;
public StringToIterableConverter(FrameworkModel frameworkModel) {
converterUtil = frameworkModel.getBeanFactory().getBean(ConverterUtil.class);
}
public boolean accept(Class<String> type, Class<?> multiValueType) {
return isAssignableFrom(getSupportedType(), multiValueType);
}
@Override
public final Object convert(String[] segments, int size, Class<?> multiValueType, Class<?> elementType) {
Optional<StringConverter> stringConverter = getStringConverter(elementType);
return stringConverter
.map(converter -> {
T convertedObject = createMultiValue(size, multiValueType);
if (convertedObject instanceof Collection) {
Collection collection = (Collection) convertedObject;
for (int i = 0; i < size; i++) {
String segment = segments[i];
Object element = converter.convert(segment);
collection.add(element);
}
return collection;
}
return convertedObject;
})
.orElse(null);
}
protected abstract T createMultiValue(int size, Class<?> multiValueType);
protected Optional<StringConverter> getStringConverter(Class<?> elementType) {
StringConverter converter = (StringConverter) converterUtil.getConverter(String.class, elementType);
return Optional.ofNullable(converter);
}
protected final Class<T> getSupportedType() {
return findActualTypeArgument(getClass(), StringToIterableConverter.class, 0);
}
@Override
public final int getPriority() {
int level = getAllInterfaces(getSupportedType(), type -> isAssignableFrom(Iterable.class, type))
.size();
return MIN_PRIORITY - level;
}
}
| 7,018 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.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.multiple;
import org.apache.dubbo.common.utils.ArrayUtils;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.split;
/**
* The class to convert {@link String} to multiple value object
*
* @see MultiValueConverter
* @since 2.7.6
*/
public interface StringToMultiValueConverter extends MultiValueConverter<String> {
@Override
default Object convert(String source, Class<?> multiValueType, Class<?> elementType) {
if (isEmpty(source)) {
return null;
}
// split by the comma
String[] segments = split(source, ',');
if (ArrayUtils.isEmpty(segments)) { // If empty array, create an array with only one element
segments = new String[] {source};
}
int size = segments.length;
return convert(segments, size, multiValueType, elementType);
}
/**
* Convert the segments to multiple value object
*
* @param segments the String array of content
* @param size the size of multiple value object
* @param targetType the target type
* @param elementType the element type
* @return multiple value object
*/
Object convert(String[] segments, int size, Class<?> targetType, Class<?> elementType);
}
| 7,019 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.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.multiple;
import org.apache.dubbo.common.convert.Converter;
import org.apache.dubbo.common.convert.ConverterUtil;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Array;
import static java.lang.reflect.Array.newInstance;
/**
* The class to convert {@link String} to array-type object
*
* @since 2.7.6
*/
public class StringToArrayConverter implements StringToMultiValueConverter {
private ConverterUtil converterUtil;
public StringToArrayConverter(FrameworkModel frameworkModel) {
converterUtil = frameworkModel.getBeanFactory().getBean(ConverterUtil.class);
}
public boolean accept(Class<String> type, Class<?> multiValueType) {
if (multiValueType != null && multiValueType.isArray()) {
return true;
}
return false;
}
@Override
public Object convert(String[] segments, int size, Class<?> targetType, Class<?> elementType) {
Class<?> componentType = targetType.getComponentType();
Converter converter = converterUtil.getConverter(String.class, componentType);
Object array = newInstance(componentType, size);
for (int i = 0; i < size; i++) {
Array.set(array, i, converter.convert(segments[i]));
}
return array;
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
}
| 7,020 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The class to convert {@link String} to {@link SortedSet}-based value
*
* @since 2.7.6
*/
public class StringToNavigableSetConverter extends StringToIterableConverter<NavigableSet> {
public StringToNavigableSetConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected NavigableSet createMultiValue(int size, Class<?> multiValueType) {
return new TreeSet();
}
}
| 7,021 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
/**
* The class to convert {@link String} to {@link Deque}-based value
*
* @since 2.7.6
*/
public class StringToQueueConverter extends StringToIterableConverter<Queue> {
public StringToQueueConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Queue createMultiValue(int size, Class<?> multiValueType) {
return new ArrayDeque(size);
}
}
| 7,022 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* The class to convert {@link String} to {@link Deque}-based value
*
* @since 2.7.6
*/
public class StringToDequeConverter extends StringToIterableConverter<Deque> {
public StringToDequeConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Deque createMultiValue(int size, Class<?> multiValueType) {
return new ArrayDeque(size);
}
}
| 7,023 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToSetConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashSet;
import java.util.Set;
/**
* The class to convert {@link String} to {@link Set}-based value
*
* @since 2.7.6
*/
public class StringToSetConverter extends StringToIterableConverter<Set> {
public StringToSetConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Set createMultiValue(int size, Class<?> multiValueType) {
return new HashSet(size);
}
}
| 7,024 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
/**
* The class to convert {@link String} to {@link BlockingDeque}-based value
*
* @since 2.7.6
*/
public class StringToBlockingDequeConverter extends StringToIterableConverter<BlockingDeque> {
public StringToBlockingDequeConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected BlockingDeque createMultiValue(int size, Class<?> multiValueType) {
return new LinkedBlockingDeque(size);
}
}
| 7,025 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToListConverter.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.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
/**
* The class to convert {@link String} to {@link List}-based value
*
* @since 2.7.6
*/
public class StringToListConverter extends StringToIterableConverter<List> {
public StringToListConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected List createMultiValue(int size, Class<?> multiValueType) {
return new ArrayList(size);
}
}
| 7,026 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/MultiValueConverter.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.multiple;
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.lang.Prioritized;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collection;
import static org.apache.dubbo.common.utils.TypeUtils.findActualTypeArgument;
/**
* An interface to convert the source-typed value to multiple value, e.g , Java array, {@link Collection} or
* sub-interfaces
*
* @param <S> The source type
* @since 2.7.6
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface MultiValueConverter<S> extends Prioritized {
/**
* Accept the source type and target type or not
*
* @param sourceType the source type
* @param multiValueType the multi-value type
* @return if accepted, return <code>true</code>, or <code>false</code>
*/
boolean accept(Class<S> sourceType, Class<?> multiValueType);
/**
* Convert the source to be the multiple value
*
* @param source the source-typed value
* @param multiValueType the multi-value type
* @param elementType the element type
* @return
*/
Object convert(S source, Class<?> multiValueType, Class<?> elementType);
/**
* Get the source type
*
* @return non-null
*/
default Class<S> getSourceType() {
return findActualTypeArgument(getClass(), MultiValueConverter.class, 0);
}
/**
* Find the {@link MultiValueConverter} instance from {@link ExtensionLoader} with the specified source and target type
*
* @param sourceType the source type
* @param targetType the target type
* @return <code>null</code> if not found
* @see ExtensionLoader#getSupportedExtensionInstances()
* @since 2.7.8
* @deprecated will be removed in 3.3.0
*/
@Deprecated
static MultiValueConverter<?> find(Class<?> sourceType, Class<?> targetType) {
return FrameworkModel.defaultModel()
.getExtensionLoader(MultiValueConverter.class)
.getSupportedExtensionInstances()
.stream()
.filter(converter -> converter.accept(sourceType, targetType))
.findFirst()
.orElse(null);
}
/**
* @deprecated will be removed in 3.3.0
*/
@Deprecated
static <T> T convertIfPossible(Object source, Class<?> multiValueType, Class<?> elementType) {
Class<?> sourceType = source.getClass();
MultiValueConverter converter = find(sourceType, multiValueType);
if (converter != null) {
return (T) converter.convert(source, multiValueType, elementType);
}
return null;
}
}
| 7,027 |
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/store/DataStore.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.store;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.util.Map;
@SPI(value = "simple", scope = ExtensionScope.APPLICATION)
public interface DataStore {
/**
* return a snapshot value of componentName
*/
Map<String, Object> get(String componentName);
Object get(String componentName, String key);
void put(String componentName, String key, Object value);
void remove(String componentName, String key);
}
| 7,028 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/store | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.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.store.support;
import org.apache.dubbo.common.store.DataStore;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class SimpleDataStore implements DataStore {
// <component name or id, <data-name, data-value>>
private final ConcurrentMap<String, ConcurrentMap<String, Object>> data = new ConcurrentHashMap<>();
@Override
public Map<String, Object> get(String componentName) {
ConcurrentMap<String, Object> value = data.get(componentName);
if (value == null) {
return new HashMap<>();
}
return new HashMap<>(value);
}
@Override
public Object get(String componentName, String key) {
if (!data.containsKey(componentName)) {
return null;
}
return data.get(componentName).get(key);
}
@Override
public void put(String componentName, String key, Object value) {
Map<String, Object> componentData =
ConcurrentHashMapUtils.computeIfAbsent(data, componentName, k -> new ConcurrentHashMap<>());
componentData.put(key, value);
}
@Override
public void remove(String componentName, String key) {
if (!data.containsKey(componentName)) {
return;
}
data.get(componentName).remove(key);
}
}
| 7,029 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.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.rpc.support;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class GroupServiceKeyCache {
private final String serviceGroup;
// ConcurrentMap<serviceName, ConcurrentMap<serviceVersion, ConcurrentMap<port, String>>>
private final ConcurrentMap<String, ConcurrentMap<String, ConcurrentMap<Integer, String>>> serviceKeyMap;
public GroupServiceKeyCache(String serviceGroup) {
this.serviceGroup = serviceGroup;
this.serviceKeyMap = new ConcurrentHashMap<>(512);
}
public String getServiceKey(String serviceName, String serviceVersion, int port) {
ConcurrentMap<String, ConcurrentMap<Integer, String>> versionMap = serviceKeyMap.get(serviceName);
if (versionMap == null) {
serviceKeyMap.putIfAbsent(serviceName, new ConcurrentHashMap<>());
versionMap = serviceKeyMap.get(serviceName);
}
serviceVersion = serviceVersion == null ? "" : serviceVersion;
ConcurrentMap<Integer, String> portMap = versionMap.get(serviceVersion);
if (portMap == null) {
versionMap.putIfAbsent(serviceVersion, new ConcurrentHashMap<>());
portMap = versionMap.get(serviceVersion);
}
String serviceKey = portMap.get(port);
if (serviceKey == null) {
serviceKey = createServiceKey(serviceName, serviceVersion, port);
portMap.put(port, serviceKey);
}
return serviceKey;
}
private String createServiceKey(String serviceName, String serviceVersion, int port) {
StringBuilder buf = new StringBuilder();
if (StringUtils.isNotEmpty(serviceGroup)) {
buf.append(serviceGroup).append('/');
}
buf.append(serviceName);
if (StringUtils.isNotEmpty(serviceVersion) && !"0.0.0".equals(serviceVersion) && !"*".equals(serviceVersion)) {
buf.append(':').append(serviceVersion);
}
buf.append(':').append(port);
return buf.toString();
}
}
| 7,030 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.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.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_RAW_RETURN;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_GSON;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_PROTOBUF;
public class ProtocolUtils {
private static final ConcurrentMap<String, GroupServiceKeyCache> groupServiceKeyCacheMap =
new ConcurrentHashMap<>();
private ProtocolUtils() {}
public static String serviceKey(URL url) {
return serviceKey(url.getPort(), url.getPath(), url.getVersion(), url.getGroup());
}
public static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) {
serviceGroup = serviceGroup == null ? "" : serviceGroup;
GroupServiceKeyCache groupServiceKeyCache = groupServiceKeyCacheMap.get(serviceGroup);
if (groupServiceKeyCache == null) {
groupServiceKeyCacheMap.putIfAbsent(serviceGroup, new GroupServiceKeyCache(serviceGroup));
groupServiceKeyCache = groupServiceKeyCacheMap.get(serviceGroup);
}
return groupServiceKeyCache.getServiceKey(serviceName, serviceVersion, port);
}
public static boolean isGeneric(String generic) {
return StringUtils.isNotEmpty(generic)
&& (GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */
|| GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(
generic) /* Streaming generalization call supporting jdk serialization */
|| GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic)
|| GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic)
|| GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic)
|| GENERIC_RAW_RETURN.equalsIgnoreCase(generic));
}
public static boolean isValidGenericValue(String generic) {
return isGeneric(generic) || Boolean.FALSE.toString().equalsIgnoreCase(generic);
}
public static boolean isDefaultGenericSerialization(String generic) {
return isGeneric(generic) && GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic);
}
public static boolean isJavaGenericSerialization(String generic) {
return isGeneric(generic) && GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic);
}
public static boolean isGsonGenericSerialization(String generic) {
return isGeneric(generic) && GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic);
}
public static boolean isBeanGenericSerialization(String generic) {
return isGeneric(generic) && GENERIC_SERIALIZATION_BEAN.equals(generic);
}
public static boolean isProtobufGenericSerialization(String generic) {
return isGeneric(generic) && GENERIC_SERIALIZATION_PROTOBUF.equals(generic);
}
public static boolean isGenericReturnRawResult(String generic) {
return GENERIC_RAW_RETURN.equals(generic);
}
}
| 7,031 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationInitListener.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.rpc.model;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.APPLICATION)
public interface ApplicationInitListener {
/**
* init the application
*/
void init();
}
| 7,032 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelUtil.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.rpc.model;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
public class ScopeModelUtil {
public static <T> ScopeModel getOrDefault(ScopeModel scopeModel, Class<T> type) {
if (scopeModel != null) {
return scopeModel;
}
return getDefaultScopeModel(type);
}
private static <T> ScopeModel getDefaultScopeModel(Class<T> type) {
SPI spi = type.getAnnotation(SPI.class);
if (spi == null) {
throw new IllegalArgumentException("SPI annotation not found for class: " + type.getName());
}
switch (spi.scope()) {
case FRAMEWORK:
return FrameworkModel.defaultModel();
case APPLICATION:
return ApplicationModel.defaultModel();
case MODULE:
return ApplicationModel.defaultModel().getDefaultModule();
default:
throw new IllegalStateException("Unable to get default scope model for type: " + type.getName());
}
}
public static ModuleModel getModuleModel(ScopeModel scopeModel) {
if (scopeModel == null) {
return ApplicationModel.defaultModel().getDefaultModule();
}
if (scopeModel instanceof ModuleModel) {
return (ModuleModel) scopeModel;
} else {
throw new IllegalArgumentException("Unable to get ModuleModel from " + scopeModel);
}
}
public static ApplicationModel getApplicationModel(ScopeModel scopeModel) {
return getOrDefaultApplicationModel(scopeModel);
}
public static ApplicationModel getOrDefaultApplicationModel(ScopeModel scopeModel) {
if (scopeModel == null) {
return ApplicationModel.defaultModel();
}
return getOrNullApplicationModel(scopeModel);
}
public static ApplicationModel getOrNullApplicationModel(ScopeModel scopeModel) {
if (scopeModel == null) {
return null;
}
if (scopeModel instanceof ApplicationModel) {
return (ApplicationModel) scopeModel;
} else if (scopeModel instanceof ModuleModel) {
ModuleModel moduleModel = (ModuleModel) scopeModel;
return moduleModel.getApplicationModel();
} else {
throw new IllegalArgumentException("Unable to get ApplicationModel from " + scopeModel);
}
}
public static FrameworkModel getFrameworkModel(ScopeModel scopeModel) {
if (scopeModel == null) {
return FrameworkModel.defaultModel();
}
if (scopeModel instanceof ApplicationModel) {
return ((ApplicationModel) scopeModel).getFrameworkModel();
} else if (scopeModel instanceof ModuleModel) {
ModuleModel moduleModel = (ModuleModel) scopeModel;
return moduleModel.getApplicationModel().getFrameworkModel();
} else if (scopeModel instanceof FrameworkModel) {
return (FrameworkModel) scopeModel;
} else {
throw new IllegalArgumentException("Unable to get FrameworkModel from " + scopeModel);
}
}
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type, ScopeModel scopeModel) {
if (scopeModel != null) {
return scopeModel.getExtensionLoader(type);
} else {
SPI spi = type.getAnnotation(SPI.class);
if (spi == null) {
throw new IllegalArgumentException("SPI annotation not found for class: " + type.getName());
}
switch (spi.scope()) {
case FRAMEWORK:
return FrameworkModel.defaultModel().getExtensionLoader(type);
case APPLICATION:
return ApplicationModel.defaultModel().getExtensionLoader(type);
case MODULE:
return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(type);
default:
throw new IllegalArgumentException("Unable to get ExtensionLoader for type: " + type.getName());
}
}
}
}
| 7,033 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.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.rpc.model;
import org.apache.dubbo.common.BaseServiceMetadata;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Notice, this class currently has no usage inside Dubbo.
*
* data related to service level such as name, version, classloader of business service,
* security info, etc. Also, with a AttributeMap for extension.
*/
public class ServiceMetadata extends BaseServiceMetadata {
private String defaultGroup;
private Class<?> serviceType;
private Object target;
/**
* will be transferred to remote side
*/
private final Map<String, Object> attachments = new ConcurrentHashMap<>();
/**
* used locally
*/
private final Map<String, Object> attributeMap = new ConcurrentHashMap<>();
public ServiceMetadata(String serviceInterfaceName, String group, String version, Class<?> serviceType) {
this.serviceInterfaceName = serviceInterfaceName;
this.defaultGroup = group;
this.group = group;
this.version = version;
this.serviceKey = buildServiceKey(serviceInterfaceName, group, version);
this.serviceType = serviceType;
}
public ServiceMetadata() {}
@Override
public String getServiceKey() {
return serviceKey;
}
public Map<String, Object> getAttachments() {
return attachments;
}
public Map<String, Object> getAttributeMap() {
return attributeMap;
}
public Object getAttribute(String key) {
return attributeMap.get(key);
}
public void addAttribute(String key, Object value) {
this.attributeMap.put(key, value);
}
public void addAttachment(String key, Object value) {
this.attachments.put(key, value);
}
public Class<?> getServiceType() {
return serviceType;
}
public String getDefaultGroup() {
return defaultGroup;
}
public void setDefaultGroup(String defaultGroup) {
this.defaultGroup = defaultGroup;
}
public void setServiceType(Class<?> serviceType) {
this.serviceType = serviceType;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
}
| 7,034 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.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.rpc.model;
public interface UnPack {
/**
* @param data byte array
* @return object instance
* @throws Exception exception
*/
Object unpack(byte[] data) throws Exception;
}
| 7,035 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.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.rpc.model;
/**
* An accessor for scope model, it can be use in interface default methods to get scope model.
*/
public interface ScopeModelAccessor {
ScopeModel getScopeModel();
default FrameworkModel getFrameworkModel() {
return ScopeModelUtil.getFrameworkModel(getScopeModel());
}
default ApplicationModel getApplicationModel() {
return ScopeModelUtil.getApplicationModel(getScopeModel());
}
default ModuleModel getModuleModel() {
return ScopeModelUtil.getModuleModel(getScopeModel());
}
}
| 7,036 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/AsyncMethodInfo.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.rpc.model;
import java.lang.reflect.Method;
public class AsyncMethodInfo {
// callback instance when async-call is invoked
private Object oninvokeInstance;
// callback method when async-call is invoked
private Method oninvokeMethod;
// callback instance when async-call is returned
private Object onreturnInstance;
// callback method when async-call is returned
private Method onreturnMethod;
// callback instance when async-call has exception thrown
private Object onthrowInstance;
// callback method when async-call has exception thrown
private Method onthrowMethod;
public Object getOninvokeInstance() {
return oninvokeInstance;
}
public void setOninvokeInstance(Object oninvokeInstance) {
this.oninvokeInstance = oninvokeInstance;
}
public Method getOninvokeMethod() {
return oninvokeMethod;
}
public void setOninvokeMethod(Method oninvokeMethod) {
this.oninvokeMethod = oninvokeMethod;
}
public Object getOnreturnInstance() {
return onreturnInstance;
}
public void setOnreturnInstance(Object onreturnInstance) {
this.onreturnInstance = onreturnInstance;
}
public Method getOnreturnMethod() {
return onreturnMethod;
}
public void setOnreturnMethod(Method onreturnMethod) {
this.onreturnMethod = onreturnMethod;
}
public Object getOnthrowInstance() {
return onthrowInstance;
}
public void setOnthrowInstance(Object onthrowInstance) {
this.onthrowInstance = onthrowInstance;
}
public Method getOnthrowMethod() {
return onthrowMethod;
}
public void setOnthrowMethod(Method onthrowMethod) {
this.onthrowMethod = onthrowMethod;
}
}
| 7,037 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.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.rpc.model;
/**
* A packable method is used to customize serialization for methods. It can provide a common wrapper
* for RESP / Protobuf.
*/
public interface PackableMethod {
default Object parseRequest(byte[] data) throws Exception {
return getRequestUnpack().unpack(data);
}
default Object parseResponse(byte[] data) throws Exception {
return parseResponse(data, false);
}
default Object parseResponse(byte[] data, boolean isReturnTriException) throws Exception {
UnPack unPack = getResponseUnpack();
if (unPack instanceof WrapperUnPack) {
return ((WrapperUnPack) unPack).unpack(data, isReturnTriException);
}
return unPack.unpack(data);
}
default byte[] packRequest(Object request) throws Exception {
return getRequestPack().pack(request);
}
default byte[] packResponse(Object response) throws Exception {
return getResponsePack().pack(response);
}
default boolean needWrapper() {
return false;
}
Pack getRequestPack();
Pack getResponsePack();
UnPack getResponseUnpack();
UnPack getRequestUnpack();
}
| 7,038 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.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.rpc.model;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import java.util.List;
import java.util.Set;
/**
* ServiceModel and ServiceMetadata are to some extent duplicated with each other. We should merge them in the future.
*/
public interface ServiceDescriptor {
FullServiceDefinition getFullServiceDefinition(String serviceKey);
String getInterfaceName();
Class<?> getServiceInterfaceClass();
Set<MethodDescriptor> getAllMethods();
/**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param params
* @return
*/
MethodDescriptor getMethod(String methodName, String params);
/**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param paramTypes
* @return methodDescriptor
*/
MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes);
List<MethodDescriptor> getMethods(String methodName);
}
| 7,039 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.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.rpc.model;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.GlobalResourcesRepository;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/**
* Model of dubbo framework, it can be shared with multiple applications.
*/
public class FrameworkModel extends ScopeModel {
// ========================= Static Fields Start ===================================
protected static final Logger LOGGER = LoggerFactory.getLogger(FrameworkModel.class);
public static final String NAME = "FrameworkModel";
private static final AtomicLong index = new AtomicLong(1);
private static final Object globalLock = new Object();
private static volatile FrameworkModel defaultInstance;
private static final List<FrameworkModel> allInstances = new CopyOnWriteArrayList<>();
// ========================= Static Fields End ===================================
// internal app index is 0, default app index is 1
private final AtomicLong appIndex = new AtomicLong(0);
private volatile ApplicationModel defaultAppModel;
private final List<ApplicationModel> applicationModels = new CopyOnWriteArrayList<>();
private final List<ApplicationModel> pubApplicationModels = new CopyOnWriteArrayList<>();
private final FrameworkServiceRepository serviceRepository;
private final ApplicationModel internalApplicationModel;
private final ReentrantLock destroyLock = new ReentrantLock();
/**
* Use {@link FrameworkModel#newModel()} to create a new model
*/
public FrameworkModel() {
super(null, ExtensionScope.FRAMEWORK, false);
synchronized (globalLock) {
synchronized (instLock) {
this.setInternalId(String.valueOf(index.getAndIncrement()));
// register FrameworkModel instance early
allInstances.add(this);
if (LOGGER.isInfoEnabled()) {
LOGGER.info(getDesc() + " is created");
}
initialize();
TypeDefinitionBuilder.initBuilders(this);
serviceRepository = new FrameworkServiceRepository(this);
ExtensionLoader<ScopeModelInitializer> initializerExtensionLoader =
this.getExtensionLoader(ScopeModelInitializer.class);
Set<ScopeModelInitializer> initializers = initializerExtensionLoader.getSupportedExtensionInstances();
for (ScopeModelInitializer initializer : initializers) {
initializer.initializeFrameworkModel(this);
}
internalApplicationModel = new ApplicationModel(this, true);
internalApplicationModel
.getApplicationConfigManager()
.setApplication(new ApplicationConfig(
internalApplicationModel, CommonConstants.DUBBO_INTERNAL_APPLICATION));
internalApplicationModel.setModelName(CommonConstants.DUBBO_INTERNAL_APPLICATION);
}
}
}
@Override
protected void onDestroy() {
synchronized (instLock) {
if (defaultInstance == this) {
// NOTE: During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or
// ApplicationModel.defaultModel()
// will return a broken model, maybe cause unpredictable problem.
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Destroying default framework model: " + getDesc());
}
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info(getDesc() + " is destroying ...");
}
// destroy all application model
for (ApplicationModel applicationModel : new ArrayList<>(applicationModels)) {
applicationModel.destroy();
}
// check whether all application models are destroyed
checkApplicationDestroy();
// notify destroy and clean framework resources
// see org.apache.dubbo.config.deploy.FrameworkModelCleaner
notifyDestroy();
if (LOGGER.isInfoEnabled()) {
LOGGER.info(getDesc() + " is destroyed");
}
// remove from allInstances and reset default FrameworkModel
synchronized (globalLock) {
allInstances.remove(this);
resetDefaultFrameworkModel();
}
// if all FrameworkModels are destroyed, clean global static resources, shutdown dubbo completely
destroyGlobalResources();
}
}
private void checkApplicationDestroy() {
synchronized (instLock) {
if (applicationModels.size() > 0) {
List<String> remainApplications =
applicationModels.stream().map(ScopeModel::getDesc).collect(Collectors.toList());
throw new IllegalStateException(
"Not all application models are completely destroyed, remaining " + remainApplications.size()
+ " application models may be created during destruction: " + remainApplications);
}
}
}
private void destroyGlobalResources() {
synchronized (globalLock) {
if (allInstances.isEmpty()) {
GlobalResourcesRepository.getInstance().destroy();
}
}
}
/**
* During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or ApplicationModel.defaultModel()
* will return a broken model, maybe cause unpredictable problem.
* Recommendation: Avoid using the default model as much as possible.
* @return the global default FrameworkModel
*/
public static FrameworkModel defaultModel() {
FrameworkModel instance = defaultInstance;
if (instance == null) {
synchronized (globalLock) {
resetDefaultFrameworkModel();
if (defaultInstance == null) {
defaultInstance = new FrameworkModel();
}
instance = defaultInstance;
}
}
Assert.notNull(instance, "Default FrameworkModel is null");
return instance;
}
/**
* Get all framework model instances
* @return
*/
public static List<FrameworkModel> getAllInstances() {
synchronized (globalLock) {
return Collections.unmodifiableList(new ArrayList<>(allInstances));
}
}
/**
* Destroy all framework model instances, shutdown dubbo engine completely.
*/
public static void destroyAll() {
synchronized (globalLock) {
for (FrameworkModel frameworkModel : new ArrayList<>(allInstances)) {
frameworkModel.destroy();
}
}
}
public ApplicationModel newApplication() {
synchronized (instLock) {
return new ApplicationModel(this);
}
}
/**
* Get or create default application model
* @return
*/
public ApplicationModel defaultApplication() {
ApplicationModel appModel = this.defaultAppModel;
if (appModel == null) {
// check destroyed before acquire inst lock, avoid blocking during destroying
checkDestroyed();
resetDefaultAppModel();
if ((appModel = this.defaultAppModel) == null) {
synchronized (instLock) {
if (this.defaultAppModel == null) {
this.defaultAppModel = newApplication();
}
appModel = this.defaultAppModel;
}
}
}
Assert.notNull(appModel, "Default ApplicationModel is null");
return appModel;
}
ApplicationModel getDefaultAppModel() {
return defaultAppModel;
}
void addApplication(ApplicationModel applicationModel) {
// can not add new application if it's destroying
checkDestroyed();
synchronized (instLock) {
if (!this.applicationModels.contains(applicationModel)) {
applicationModel.setInternalId(buildInternalId(getInternalId(), appIndex.getAndIncrement()));
this.applicationModels.add(applicationModel);
if (!applicationModel.isInternal()) {
this.pubApplicationModels.add(applicationModel);
}
}
}
}
void removeApplication(ApplicationModel model) {
synchronized (instLock) {
this.applicationModels.remove(model);
if (!model.isInternal()) {
this.pubApplicationModels.remove(model);
}
resetDefaultAppModel();
}
}
/**
* Protocols are special resources that need to be destroyed as soon as possible.
*
* Since connections inside protocol are not classified by applications, trying to destroy protocols in advance might only work for singleton application scenario.
*/
void tryDestroyProtocols() {
synchronized (instLock) {
if (pubApplicationModels.size() == 0) {
notifyProtocolDestroy();
}
}
}
void tryDestroy() {
synchronized (instLock) {
if (pubApplicationModels.size() == 0) {
destroy();
}
}
}
private void checkDestroyed() {
if (isDestroyed()) {
throw new IllegalStateException("FrameworkModel is destroyed");
}
}
private void resetDefaultAppModel() {
synchronized (instLock) {
if (this.defaultAppModel != null && !this.defaultAppModel.isDestroyed()) {
return;
}
ApplicationModel oldDefaultAppModel = this.defaultAppModel;
if (pubApplicationModels.size() > 0) {
this.defaultAppModel = pubApplicationModels.get(0);
} else {
this.defaultAppModel = null;
}
if (defaultInstance == this && oldDefaultAppModel != this.defaultAppModel) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Reset global default application from " + safeGetModelDesc(oldDefaultAppModel) + " to "
+ safeGetModelDesc(this.defaultAppModel));
}
}
}
}
private static void resetDefaultFrameworkModel() {
synchronized (globalLock) {
if (defaultInstance != null && !defaultInstance.isDestroyed()) {
return;
}
FrameworkModel oldDefaultFrameworkModel = defaultInstance;
if (allInstances.size() > 0) {
defaultInstance = allInstances.get(0);
} else {
defaultInstance = null;
}
if (oldDefaultFrameworkModel != defaultInstance) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Reset global default framework from " + safeGetModelDesc(oldDefaultFrameworkModel)
+ " to " + safeGetModelDesc(defaultInstance));
}
}
}
}
private static String safeGetModelDesc(ScopeModel scopeModel) {
return scopeModel != null ? scopeModel.getDesc() : null;
}
/**
* Get all application models except for the internal application model.
*/
public List<ApplicationModel> getApplicationModels() {
synchronized (globalLock) {
return Collections.unmodifiableList(pubApplicationModels);
}
}
/**
* Get all application models including the internal application model.
*/
public List<ApplicationModel> getAllApplicationModels() {
synchronized (globalLock) {
return Collections.unmodifiableList(applicationModels);
}
}
public ApplicationModel getInternalApplicationModel() {
return internalApplicationModel;
}
public FrameworkServiceRepository getServiceRepository() {
return serviceRepository;
}
@Override
protected Lock acquireDestroyLock() {
return destroyLock;
}
@Override
public Environment modelEnvironment() {
throw new UnsupportedOperationException("Environment is inaccessible for FrameworkModel");
}
@Override
protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) {
return super.checkIfClassLoaderCanRemoved(classLoader)
&& applicationModels.stream()
.noneMatch(applicationModel -> applicationModel.containsClassLoader(classLoader));
}
}
| 7,040 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/DubboStub.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.rpc.model;
/**
* Marker interface implemented by all stub. Used to detect
* whether objects are Dubbo-generated stub.
*/
public interface DubboStub {}
| 7,041 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubServiceDescriptor.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.rpc.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class StubServiceDescriptor implements ServiceDescriptor {
private final String interfaceName;
private final Class<?> serviceInterfaceClass;
// to accelerate search
private final Map<String, List<MethodDescriptor>> methods = new HashMap<>();
private final Map<String, Map<String, MethodDescriptor>> descToMethods = new HashMap<>();
private final ConcurrentNavigableMap<String, FullServiceDefinition> serviceDefinitions =
new ConcurrentSkipListMap<>();
public StubServiceDescriptor(String interfaceName, Class<?> interfaceClass) {
this.interfaceName = interfaceName;
this.serviceInterfaceClass = interfaceClass;
}
public void addMethod(MethodDescriptor methodDescriptor) {
methods.put(methodDescriptor.getMethodName(), Collections.singletonList(methodDescriptor));
Map<String, MethodDescriptor> descMap =
descToMethods.computeIfAbsent(methodDescriptor.getMethodName(), k -> new HashMap<>());
descMap.put(methodDescriptor.getParamDesc(), methodDescriptor);
}
public FullServiceDefinition getFullServiceDefinition(String serviceKey) {
return serviceDefinitions.computeIfAbsent(
serviceKey,
(k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap()));
}
public String getInterfaceName() {
return interfaceName;
}
public Class<?> getServiceInterfaceClass() {
return serviceInterfaceClass;
}
public Set<MethodDescriptor> getAllMethods() {
Set<MethodDescriptor> methodModels = new HashSet<>();
methods.forEach((k, v) -> methodModels.addAll(v));
return methodModels;
}
/**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param params
* @return
*/
public MethodDescriptor getMethod(String methodName, String params) {
Map<String, MethodDescriptor> methods = descToMethods.get(methodName);
if (CollectionUtils.isNotEmptyMap(methods)) {
return methods.get(params);
}
return null;
}
/**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param paramTypes
* @return
*/
public MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes) {
List<MethodDescriptor> methodModels = methods.get(methodName);
if (CollectionUtils.isNotEmpty(methodModels)) {
for (MethodDescriptor descriptor : methodModels) {
if (Arrays.equals(paramTypes, descriptor.getParameterClasses())) {
return descriptor;
}
}
}
return null;
}
public List<MethodDescriptor> getMethods(String methodName) {
return methods.get(methodName);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StubServiceDescriptor that = (StubServiceDescriptor) o;
return Objects.equals(interfaceName, that.interfaceName)
&& Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass)
&& Objects.equals(methods, that.methods)
&& Objects.equals(descToMethods, that.descToMethods);
}
@Override
public int hashCode() {
return Objects.hash(interfaceName, serviceInterfaceClass, methods, descToMethods);
}
}
| 7,042 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.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.rpc.model;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.extension.ExtensionAccessor;
import org.apache.dubbo.common.extension.ExtensionDirector;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNABLE_DESTROY_MODEL;
public abstract class ScopeModel implements ExtensionAccessor {
protected static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ScopeModel.class);
/**
* The internal id is used to represent the hierarchy of the model tree, such as:
* <ol>
* <li>1</li>
* FrameworkModel (index=1)
* <li>1.2</li>
* FrameworkModel (index=1) -> ApplicationModel (index=2)
* <li>1.2.0</li>
* FrameworkModel (index=1) -> ApplicationModel (index=2) -> ModuleModel (index=0, internal module)
* <li>1.2.1</li>
* FrameworkModel (index=1) -> ApplicationModel (index=2) -> ModuleModel (index=1, first user module)
* </ol>
*/
private String internalId;
/**
* Public Model Name, can be set from user
*/
private String modelName;
private String desc;
private final Set<ClassLoader> classLoaders = new ConcurrentHashSet<>();
private final ScopeModel parent;
private final ExtensionScope scope;
private volatile ExtensionDirector extensionDirector;
private volatile ScopeBeanFactory beanFactory;
private final List<ScopeModelDestroyListener> destroyListeners = new CopyOnWriteArrayList<>();
private final List<ScopeClassLoaderListener> classLoaderListeners = new CopyOnWriteArrayList<>();
private final Map<String, Object> attributes = new ConcurrentHashMap<>();
private final AtomicBoolean destroyed = new AtomicBoolean(false);
private final boolean internalScope;
protected final Object instLock = new Object();
protected ScopeModel(ScopeModel parent, ExtensionScope scope, boolean isInternal) {
this.parent = parent;
this.scope = scope;
this.internalScope = isInternal;
}
/**
* NOTE:
* <ol>
* <li>The initialize method only be called in subclass.</li>
* <li>
* In subclass, the extensionDirector and beanFactory are available in initialize but not available in constructor.
* </li>
* </ol>
*/
protected void initialize() {
synchronized (instLock) {
this.extensionDirector =
new ExtensionDirector(parent != null ? parent.getExtensionDirector() : null, scope, this);
this.extensionDirector.addExtensionPostProcessor(new ScopeModelAwareExtensionProcessor(this));
this.beanFactory = new ScopeBeanFactory(parent != null ? parent.getBeanFactory() : null, extensionDirector);
// Add Framework's ClassLoader by default
ClassLoader dubboClassLoader = ScopeModel.class.getClassLoader();
if (dubboClassLoader != null) {
this.addClassLoader(dubboClassLoader);
}
}
}
protected abstract Lock acquireDestroyLock();
public void destroy() {
Lock lock = acquireDestroyLock();
try {
lock.lock();
if (destroyed.compareAndSet(false, true)) {
try {
onDestroy();
HashSet<ClassLoader> copyOfClassLoaders = new HashSet<>(classLoaders);
for (ClassLoader classLoader : copyOfClassLoaders) {
removeClassLoader(classLoader);
}
if (beanFactory != null) {
beanFactory.destroy();
}
if (extensionDirector != null) {
extensionDirector.destroy();
}
} catch (Throwable t) {
LOGGER.error(CONFIG_UNABLE_DESTROY_MODEL, "", "", "Error happened when destroying ScopeModel.", t);
}
}
} finally {
lock.unlock();
}
}
public boolean isDestroyed() {
return destroyed.get();
}
protected void notifyDestroy() {
for (ScopeModelDestroyListener destroyListener : destroyListeners) {
destroyListener.onDestroy(this);
}
}
protected void notifyProtocolDestroy() {
for (ScopeModelDestroyListener destroyListener : destroyListeners) {
if (destroyListener.isProtocol()) {
destroyListener.onDestroy(this);
}
}
}
protected void notifyClassLoaderAdd(ClassLoader classLoader) {
for (ScopeClassLoaderListener classLoaderListener : classLoaderListeners) {
classLoaderListener.onAddClassLoader(this, classLoader);
}
}
protected void notifyClassLoaderDestroy(ClassLoader classLoader) {
for (ScopeClassLoaderListener classLoaderListener : classLoaderListeners) {
classLoaderListener.onRemoveClassLoader(this, classLoader);
}
}
protected abstract void onDestroy();
public final void addDestroyListener(ScopeModelDestroyListener listener) {
destroyListeners.add(listener);
}
public final void addClassLoaderListener(ScopeClassLoaderListener listener) {
classLoaderListeners.add(listener);
}
public Map<String, Object> getAttributes() {
return attributes;
}
public <T> T getAttribute(String key, Class<T> type) {
return (T) attributes.get(key);
}
public Object getAttribute(String key) {
return attributes.get(key);
}
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
@Override
public ExtensionDirector getExtensionDirector() {
return extensionDirector;
}
public ScopeBeanFactory getBeanFactory() {
return beanFactory;
}
public ScopeModel getParent() {
return parent;
}
public ExtensionScope getScope() {
return scope;
}
public void addClassLoader(ClassLoader classLoader) {
synchronized (instLock) {
this.classLoaders.add(classLoader);
if (parent != null) {
parent.addClassLoader(classLoader);
}
extensionDirector.removeAllCachedLoader();
notifyClassLoaderAdd(classLoader);
}
}
public void removeClassLoader(ClassLoader classLoader) {
synchronized (instLock) {
if (checkIfClassLoaderCanRemoved(classLoader)) {
this.classLoaders.remove(classLoader);
if (parent != null) {
parent.removeClassLoader(classLoader);
}
extensionDirector.removeAllCachedLoader();
notifyClassLoaderDestroy(classLoader);
}
}
}
protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) {
return classLoader != null && !classLoader.equals(ScopeModel.class.getClassLoader());
}
public Set<ClassLoader> getClassLoaders() {
return Collections.unmodifiableSet(classLoaders);
}
/**
* Get current model's environment.
* </br>
* Note: This method should not start with `get` or it would be invoked due to Spring boot refresh.
* @see <a href="https://github.com/apache/dubbo/issues/12542">Configuration refresh issue</a>
*/
public abstract Environment modelEnvironment();
/**
* Get current model's environment.
*
* @see <a href="https://github.com/apache/dubbo/issues/12542">Configuration refresh issue</a>
* @deprecated use modelEnvironment() instead
*/
@Deprecated
public final Environment getModelEnvironment() {
try {
return modelEnvironment();
} catch (Exception ex) {
return null;
}
}
public String getInternalId() {
return this.internalId;
}
void setInternalId(String internalId) {
this.internalId = internalId;
}
protected String buildInternalId(String parentInternalId, long childIndex) {
// FrameworkModel 1
// ApplicationModel 1.1
// ModuleModel 1.1.1
if (StringUtils.hasText(parentInternalId)) {
return parentInternalId + "." + childIndex;
} else {
return "" + childIndex;
}
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
this.desc = buildDesc();
}
public boolean isInternal() {
return internalScope;
}
/**
* @return to describe string of this scope model
*/
public String getDesc() {
if (this.desc == null) {
this.desc = buildDesc();
}
return this.desc;
}
private String buildDesc() {
// Dubbo Framework[1]
// Dubbo Application[1.1](appName)
// Dubbo Module[1.1.1](appName/moduleName)
String type = this.getClass().getSimpleName().replace("Model", "");
String desc = "Dubbo " + type + "[" + this.getInternalId() + "]";
// append model name path
String modelNamePath = this.getModelNamePath();
if (StringUtils.hasText(modelNamePath)) {
desc += "(" + modelNamePath + ")";
}
return desc;
}
private String getModelNamePath() {
if (this instanceof ApplicationModel) {
return safeGetAppName((ApplicationModel) this);
} else if (this instanceof ModuleModel) {
String modelName = this.getModelName();
if (StringUtils.hasText(modelName)) {
// appName/moduleName
return safeGetAppName(((ModuleModel) this).getApplicationModel()) + "/" + modelName;
}
}
return null;
}
private static String safeGetAppName(ApplicationModel applicationModel) {
String modelName = applicationModel.getModelName();
if (StringUtils.isBlank(modelName)) {
modelName = "unknown"; // unknown application
}
return modelName;
}
@Override
public String toString() {
return getDesc();
}
}
| 7,043 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessor.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.rpc.model;
import org.apache.dubbo.common.extension.ExtensionPostProcessor;
public class ScopeModelAwareExtensionProcessor implements ExtensionPostProcessor, ScopeModelAccessor {
private ScopeModel scopeModel;
private FrameworkModel frameworkModel;
private ApplicationModel applicationModel;
private ModuleModel moduleModel;
public ScopeModelAwareExtensionProcessor(ScopeModel scopeModel) {
this.scopeModel = scopeModel;
initialize();
}
private void initialize() {
// NOTE: Do not create a new model or use the default application/module model here!
// Only the visible and only matching scope model can be injected, that is, module -> application -> framework.
// The converse is a one-to-many relationship and cannot be injected.
// One framework may have multiple applications, and one application may have multiple modules.
// So, the spi extension/bean of application scope can be injected its application model and framework model,
// but the spi extension/bean of framework scope cannot be injected an application or module model.
if (scopeModel instanceof FrameworkModel) {
frameworkModel = (FrameworkModel) scopeModel;
} else if (scopeModel instanceof ApplicationModel) {
applicationModel = (ApplicationModel) scopeModel;
frameworkModel = applicationModel.getFrameworkModel();
} else if (scopeModel instanceof ModuleModel) {
moduleModel = (ModuleModel) scopeModel;
applicationModel = moduleModel.getApplicationModel();
frameworkModel = applicationModel.getFrameworkModel();
}
}
@Override
public Object postProcessAfterInitialization(Object instance, String name) throws Exception {
if (instance instanceof ScopeModelAware) {
ScopeModelAware modelAware = (ScopeModelAware) instance;
modelAware.setScopeModel(scopeModel);
if (this.moduleModel != null) {
modelAware.setModuleModel(this.moduleModel);
}
if (this.applicationModel != null) {
modelAware.setApplicationModel(this.applicationModel);
}
if (this.frameworkModel != null) {
modelAware.setFrameworkModel(this.frameworkModel);
}
}
return instance;
}
@Override
public ScopeModel getScopeModel() {
return scopeModel;
}
@Override
public FrameworkModel getFrameworkModel() {
return frameworkModel;
}
@Override
public ApplicationModel getApplicationModel() {
return applicationModel;
}
@Override
public ModuleModel getModuleModel() {
return moduleModel;
}
}
| 7,044 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.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.rpc.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ModuleEnvironment;
import org.apache.dubbo.common.context.ModuleExt;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.config.context.ModuleConfigManager;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.locks.Lock;
/**
* Model of a service module
*/
public class ModuleModel extends ScopeModel {
private static final Logger logger = LoggerFactory.getLogger(ModuleModel.class);
public static final String NAME = "ModuleModel";
private final ApplicationModel applicationModel;
private volatile ModuleServiceRepository serviceRepository;
private volatile ModuleEnvironment moduleEnvironment;
private volatile ModuleConfigManager moduleConfigManager;
private volatile ModuleDeployer deployer;
private boolean lifeCycleManagedExternally = false;
protected ModuleModel(ApplicationModel applicationModel) {
this(applicationModel, false);
}
protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) {
super(applicationModel, ExtensionScope.MODULE, isInternal);
synchronized (instLock) {
Assert.notNull(applicationModel, "ApplicationModel can not be null");
this.applicationModel = applicationModel;
applicationModel.addModule(this, isInternal);
if (LOGGER.isInfoEnabled()) {
LOGGER.info(getDesc() + " is created");
}
initialize();
this.serviceRepository = new ModuleServiceRepository(this);
initModuleExt();
ExtensionLoader<ScopeModelInitializer> initializerExtensionLoader =
this.getExtensionLoader(ScopeModelInitializer.class);
Set<ScopeModelInitializer> initializers = initializerExtensionLoader.getSupportedExtensionInstances();
for (ScopeModelInitializer initializer : initializers) {
initializer.initializeModuleModel(this);
}
Assert.notNull(getServiceRepository(), "ModuleServiceRepository can not be null");
Assert.notNull(getConfigManager(), "ModuleConfigManager can not be null");
Assert.assertTrue(getConfigManager().isInitialized(), "ModuleConfigManager can not be initialized");
// notify application check state
ApplicationDeployer applicationDeployer = applicationModel.getDeployer();
if (applicationDeployer != null) {
applicationDeployer.notifyModuleChanged(this, DeployState.PENDING);
}
}
}
// already synchronized in constructor
private void initModuleExt() {
Set<ModuleExt> exts = this.getExtensionLoader(ModuleExt.class).getSupportedExtensionInstances();
for (ModuleExt ext : exts) {
ext.initialize();
}
}
@Override
protected void onDestroy() {
synchronized (instLock) {
// 1. remove from applicationModel
applicationModel.removeModule(this);
// 2. set stopping
if (deployer != null) {
deployer.preDestroy();
}
// 3. release services
if (deployer != null) {
deployer.postDestroy();
}
// destroy other resources
notifyDestroy();
if (serviceRepository != null) {
serviceRepository.destroy();
serviceRepository = null;
}
if (moduleEnvironment != null) {
moduleEnvironment.destroy();
moduleEnvironment = null;
}
if (moduleConfigManager != null) {
moduleConfigManager.destroy();
moduleConfigManager = null;
}
// destroy application if none pub module
applicationModel.tryDestroy();
}
}
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public ModuleServiceRepository getServiceRepository() {
return serviceRepository;
}
@Override
public void addClassLoader(ClassLoader classLoader) {
super.addClassLoader(classLoader);
if (moduleEnvironment != null) {
moduleEnvironment.refreshClassLoaders();
}
}
@Override
public ModuleEnvironment modelEnvironment() {
if (moduleEnvironment == null) {
moduleEnvironment =
(ModuleEnvironment) this.getExtensionLoader(ModuleExt.class).getExtension(ModuleEnvironment.NAME);
}
return moduleEnvironment;
}
public ModuleConfigManager getConfigManager() {
if (moduleConfigManager == null) {
moduleConfigManager = (ModuleConfigManager)
this.getExtensionLoader(ModuleExt.class).getExtension(ModuleConfigManager.NAME);
}
return moduleConfigManager;
}
public ModuleDeployer getDeployer() {
return deployer;
}
public void setDeployer(ModuleDeployer deployer) {
this.deployer = deployer;
}
@Override
protected Lock acquireDestroyLock() {
return getApplicationModel().getFrameworkModel().acquireDestroyLock();
}
/**
* for ut only
*/
@Deprecated
public void setModuleEnvironment(ModuleEnvironment moduleEnvironment) {
this.moduleEnvironment = moduleEnvironment;
}
public ConsumerModel registerInternalConsumer(Class<?> internalService, URL url) {
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setVersion(url.getVersion());
serviceMetadata.setGroup(url.getGroup());
serviceMetadata.setDefaultGroup(url.getGroup());
serviceMetadata.setServiceInterfaceName(internalService.getName());
serviceMetadata.setServiceType(internalService);
String serviceKey = URL.buildKey(internalService.getName(), url.getGroup(), url.getVersion());
serviceMetadata.setServiceKey(serviceKey);
ConsumerModel consumerModel = new ConsumerModel(
serviceMetadata.getServiceKey(),
"jdk",
serviceRepository.lookupService(serviceMetadata.getServiceInterfaceName()),
this,
serviceMetadata,
new HashMap<>(0),
ClassUtils.getClassLoader(internalService));
logger.info("Dynamically registering consumer model " + serviceKey + " into model " + this.getDesc());
serviceRepository.registerConsumer(consumerModel);
return consumerModel;
}
public boolean isLifeCycleManagedExternally() {
return lifeCycleManagedExternally;
}
public void setLifeCycleManagedExternally(boolean lifeCycleManagedExternally) {
this.lifeCycleManagedExternally = lifeCycleManagedExternally;
}
}
| 7,045 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.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.rpc.model;
import org.apache.dubbo.common.utils.Assert;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
/**
* This model is bound to your reference's configuration, for example, group, version or method level configuration.
*/
public class ConsumerModel extends ServiceModel {
private final Set<String> apps = new TreeSet<>();
private final Map<String, AsyncMethodInfo> methodConfigs;
private Map<Method, ConsumerMethodModel> methodModels = new HashMap<>();
/**
* This constructor creates an instance of ConsumerModel and passed objects should not be null.
* If service name, service instance, proxy object,methods should not be null. If these are null
* then this constructor will throw {@link IllegalArgumentException}
*
* @param serviceKey Name of the service.
* @param proxyObject Proxy object.
*/
public ConsumerModel(
String serviceKey,
Object proxyObject,
ServiceDescriptor serviceDescriptor,
Map<String, AsyncMethodInfo> methodConfigs,
ClassLoader interfaceClassLoader) {
super(proxyObject, serviceKey, serviceDescriptor, null, interfaceClassLoader);
Assert.notEmptyString(serviceKey, "Service name can't be null or blank");
this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs;
}
public ConsumerModel(
String serviceKey,
Object proxyObject,
ServiceDescriptor serviceDescriptor,
ServiceMetadata metadata,
Map<String, AsyncMethodInfo> methodConfigs,
ClassLoader interfaceClassLoader) {
super(proxyObject, serviceKey, serviceDescriptor, null, metadata, interfaceClassLoader);
Assert.notEmptyString(serviceKey, "Service name can't be null or blank");
this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs;
}
public ConsumerModel(
String serviceKey,
Object proxyObject,
ServiceDescriptor serviceDescriptor,
ModuleModel moduleModel,
ServiceMetadata metadata,
Map<String, AsyncMethodInfo> methodConfigs,
ClassLoader interfaceClassLoader) {
super(proxyObject, serviceKey, serviceDescriptor, moduleModel, metadata, interfaceClassLoader);
Assert.notEmptyString(serviceKey, "Service name can't be null or blank");
this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs;
}
public AsyncMethodInfo getMethodConfig(String methodName) {
return methodConfigs.get(methodName);
}
public Set<String> getApps() {
return apps;
}
public AsyncMethodInfo getAsyncInfo(String methodName) {
return methodConfigs.get(methodName);
}
public void initMethodModels() {
Class<?>[] interfaceList;
if (getProxyObject() == null) {
Class<?> serviceInterfaceClass = getServiceInterfaceClass();
if (serviceInterfaceClass != null) {
interfaceList = new Class[] {serviceInterfaceClass};
} else {
interfaceList = new Class[0];
}
} else {
interfaceList = getProxyObject().getClass().getInterfaces();
}
for (Class<?> interfaceClass : interfaceList) {
for (Method method : interfaceClass.getMethods()) {
methodModels.put(method, new ConsumerMethodModel(method));
}
}
}
/**
* Return method model for the given method on consumer side
*
* @param method method object
* @return method model
*/
public ConsumerMethodModel getMethodModel(Method method) {
return methodModels.get(method);
}
/**
* Return method model for the given method on consumer side
*
* @param method method object
* @return method model
*/
public ConsumerMethodModel getMethodModel(String method) {
Optional<Map.Entry<Method, ConsumerMethodModel>> consumerMethodModelEntry = methodModels.entrySet().stream()
.filter(entry -> entry.getKey().getName().equals(method))
.findFirst();
return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null);
}
/**
* @param method methodName
* @param argsType method arguments type
* @return
*/
public ConsumerMethodModel getMethodModel(String method, String[] argsType) {
Optional<ConsumerMethodModel> consumerMethodModel = methodModels.entrySet().stream()
.filter(entry -> entry.getKey().getName().equals(method))
.map(Map.Entry::getValue)
.filter(methodModel -> Arrays.equals(argsType, methodModel.getParameterTypes()))
.findFirst();
return consumerMethodModel.orElse(null);
}
/**
* Return all method models for the current service
*
* @return method model list
*/
public List<ConsumerMethodModel> getAllMethodModels() {
return new ArrayList<>(methodModels.values());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ConsumerModel that = (ConsumerModel) o;
return Objects.equals(apps, that.apps)
&& Objects.equals(methodConfigs, that.methodConfigs)
&& Objects.equals(methodModels, that.methodModels);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), apps, methodConfigs, methodModels);
}
}
| 7,046 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.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.rpc.model;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
public interface MethodDescriptor {
String getMethodName();
String getParamDesc();
/**
* duplicate filed as paramDesc, but with different format.
*/
String[] getCompatibleParamSignatures();
Class<?>[] getParameterClasses();
Class<?> getReturnClass();
Type[] getReturnTypes();
RpcType getRpcType();
boolean isGeneric();
/**
* Only available for ReflectionMethod
*
* @return method
*/
Method getMethod();
void addAttribute(String key, Object value);
Object getAttribute(String key);
enum RpcType {
UNARY,
CLIENT_STREAM,
SERVER_STREAM,
BI_STREAM
}
}
| 7,047 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeClassLoaderListener.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.rpc.model;
public interface ScopeClassLoaderListener<T extends ScopeModel> {
void onAddClassLoader(T scopeModel, ClassLoader classLoader);
void onRemoveClassLoader(T scopeModel, ClassLoader classLoader);
}
| 7,048 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.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.rpc.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface PackableMethodFactory {
PackableMethod create(MethodDescriptor methodDescriptor, URL url, String contentType);
}
| 7,049 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.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.rpc.model;
public interface WrapperUnPack extends UnPack {
default Object unpack(byte[] data) throws Exception {
return unpack(data, false);
}
Object unpack(byte[] data, boolean isReturnTriException) throws Exception;
}
| 7,050 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.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.rpc.model;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Stream;
public class StubMethodDescriptor implements MethodDescriptor, PackableMethod {
private static final Logger logger = LoggerFactory.getLogger(StubMethodDescriptor.class);
private final ServiceDescriptor serviceDescriptor;
private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>();
private final String methodName;
private final String[] compatibleParamSignatures;
private final Class<?>[] parameterClasses;
private final Class<?> returnClass;
private final Type[] returnTypes;
private final String paramDesc;
private final RpcType rpcType;
private final Pack requestPack;
private final Pack responsePack;
private final UnPack requestUnpack;
private final UnPack responseUnpack;
public StubMethodDescriptor(
String methodName,
Class<?> requestClass,
Class<?> responseClass,
StubServiceDescriptor serviceDescriptor,
RpcType rpcType,
Pack requestPack,
Pack responsePack,
UnPack requestUnpack,
UnPack responseUnpack) {
this.methodName = methodName;
this.serviceDescriptor = serviceDescriptor;
this.rpcType = rpcType;
this.requestPack = requestPack;
this.responsePack = responsePack;
this.responseUnpack = responseUnpack;
this.requestUnpack = requestUnpack;
this.parameterClasses = new Class<?>[] {requestClass};
this.returnClass = responseClass;
this.paramDesc = ReflectUtils.getDesc(parameterClasses);
this.compatibleParamSignatures =
Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new);
this.returnTypes = new Type[] {responseClass, responseClass};
serviceDescriptor.addMethod(this);
}
@Override
public String getMethodName() {
return methodName;
}
@Override
public String getParamDesc() {
return paramDesc;
}
@Override
public String[] getCompatibleParamSignatures() {
return compatibleParamSignatures;
}
@Override
public Class<?>[] getParameterClasses() {
return parameterClasses;
}
@Override
public Class<?> getReturnClass() {
return returnClass;
}
@Override
public Type[] getReturnTypes() {
return returnTypes;
}
@Override
public RpcType getRpcType() {
return rpcType;
}
@Override
public boolean isGeneric() {
return false;
}
@Override
public Method getMethod() {
return null;
}
@Override
public void addAttribute(String key, Object value) {
this.attributeMap.put(key, value);
}
@Override
public Object getAttribute(String key) {
return this.attributeMap.get(key);
}
@Override
public Pack getRequestPack() {
return requestPack;
}
@Override
public Pack getResponsePack() {
return responsePack;
}
@Override
public UnPack getResponseUnpack() {
return responseUnpack;
}
@Override
public UnPack getRequestUnpack() {
return requestUnpack;
}
}
| 7,051 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderMethodModel.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.rpc.model;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Replaced with {@link MethodDescriptor}
*/
@Deprecated
public class ProviderMethodModel {
private final Method method;
private final String methodName;
private final Class<?>[] parameterClasses;
private final String[] methodArgTypes;
private final Type[] genericParameterTypes;
private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>();
public ProviderMethodModel(Method method) {
this.method = method;
this.methodName = method.getName();
this.parameterClasses = method.getParameterTypes();
this.methodArgTypes = getArgTypes(method);
this.genericParameterTypes = method.getGenericParameterTypes();
}
public Method getMethod() {
return method;
}
public String getMethodName() {
return methodName;
}
public String[] getMethodArgTypes() {
return methodArgTypes;
}
public ConcurrentMap<String, Object> getAttributeMap() {
return attributeMap;
}
private static String[] getArgTypes(Method method) {
String[] methodArgTypes = new String[0];
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length > 0) {
methodArgTypes = new String[parameterTypes.length];
int index = 0;
for (Class<?> paramType : parameterTypes) {
methodArgTypes[index++] = paramType.getName();
}
}
return methodArgTypes;
}
public Class<?>[] getParameterClasses() {
return parameterClasses;
}
public Type[] getGenericParameterTypes() {
return genericParameterTypes;
}
}
| 7,052 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.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.rpc.model;
import org.apache.dubbo.common.URL;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* ProviderModel is about published services
*/
public class ProviderModel extends ServiceModel {
private final List<RegisterStatedURL> urls;
private final Map<String, List<ProviderMethodModel>> methods = new HashMap<>();
/**
* The url of the reference service
*/
private List<URL> serviceUrls = new ArrayList<>();
private volatile long lastInvokeTime = 0;
public ProviderModel(
String serviceKey,
Object serviceInstance,
ServiceDescriptor serviceDescriptor,
ClassLoader interfaceClassLoader) {
super(serviceInstance, serviceKey, serviceDescriptor, null, interfaceClassLoader);
if (null == serviceInstance) {
throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL.");
}
this.urls = new CopyOnWriteArrayList<>();
}
public ProviderModel(
String serviceKey,
Object serviceInstance,
ServiceDescriptor serviceDescriptor,
ServiceMetadata serviceMetadata,
ClassLoader interfaceClassLoader) {
super(serviceInstance, serviceKey, serviceDescriptor, null, serviceMetadata, interfaceClassLoader);
if (null == serviceInstance) {
throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL.");
}
initMethod(serviceDescriptor.getServiceInterfaceClass());
this.urls = new ArrayList<>(1);
}
public ProviderModel(
String serviceKey,
Object serviceInstance,
ServiceDescriptor serviceModel,
ModuleModel moduleModel,
ServiceMetadata serviceMetadata,
ClassLoader interfaceClassLoader) {
super(serviceInstance, serviceKey, serviceModel, moduleModel, serviceMetadata, interfaceClassLoader);
if (null == serviceInstance) {
throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL.");
}
initMethod(serviceModel.getServiceInterfaceClass());
this.urls = new ArrayList<>(1);
}
public Object getServiceInstance() {
return getProxyObject();
}
public List<RegisterStatedURL> getStatedUrl() {
return urls;
}
public void addStatedUrl(RegisterStatedURL url) {
this.urls.add(url);
}
public static class RegisterStatedURL {
private volatile URL registryUrl;
private volatile URL providerUrl;
private volatile boolean registered;
public RegisterStatedURL(URL providerUrl, URL registryUrl, boolean registered) {
this.providerUrl = providerUrl;
this.registered = registered;
this.registryUrl = registryUrl;
}
public URL getProviderUrl() {
return providerUrl;
}
public void setProviderUrl(URL providerUrl) {
this.providerUrl = providerUrl;
}
public boolean isRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
public URL getRegistryUrl() {
return registryUrl;
}
public void setRegistryUrl(URL registryUrl) {
this.registryUrl = registryUrl;
}
}
public List<ProviderMethodModel> getAllMethodModels() {
List<ProviderMethodModel> result = new ArrayList<ProviderMethodModel>();
for (List<ProviderMethodModel> models : methods.values()) {
result.addAll(models);
}
return result;
}
public ProviderMethodModel getMethodModel(String methodName, String[] argTypes) {
List<ProviderMethodModel> methodModels = methods.get(methodName);
if (methodModels != null) {
for (ProviderMethodModel methodModel : methodModels) {
if (Arrays.equals(argTypes, methodModel.getMethodArgTypes())) {
return methodModel;
}
}
}
return null;
}
public List<ProviderMethodModel> getMethodModelList(String methodName) {
List<ProviderMethodModel> resultList = methods.get(methodName);
return resultList == null ? Collections.emptyList() : resultList;
}
private void initMethod(Class<?> serviceInterfaceClass) {
Method[] methodsToExport = serviceInterfaceClass.getMethods();
for (Method method : methodsToExport) {
method.setAccessible(true);
List<ProviderMethodModel> methodModels = methods.computeIfAbsent(method.getName(), k -> new ArrayList<>());
methodModels.add(new ProviderMethodModel(method));
}
}
public List<URL> getServiceUrls() {
return serviceUrls;
}
public void setServiceUrls(List<URL> urls) {
this.serviceUrls = urls;
}
public long getLastInvokeTime() {
return lastInvokeTime;
}
public void updateLastInvokeTime() {
this.lastInvokeTime = System.currentTimeMillis();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProviderModel that = (ProviderModel) o;
return Objects.equals(urls, that.urls) && Objects.equals(methods, that.methods);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), urls, methods);
}
}
| 7,053 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelDestroyListener.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.rpc.model;
public interface ScopeModelDestroyListener<T extends ScopeModel> {
void onDestroy(T scopeModel);
default boolean isProtocol() {
return false;
}
}
| 7,054 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.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.rpc.model;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.context.ApplicationExt;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.context.ConfigManager;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
/**
* {@link ExtensionLoader}, {@code DubboBootstrap} and this class are at present designed to be
* singleton or static (by itself totally static or uses some static fields). So the instances
* returned from them are of process scope. If you want to support multiple dubbo servers in one
* single process, you may need to refactor those three classes.
* <p>
* Represent an application which is using Dubbo and store basic metadata info for using
* during the processing of RPC invoking.
* <p>
* ApplicationModel includes many ProviderModel which is about published services
* and many Consumer Model which is about subscribed services.
* <p>
*/
public class ApplicationModel extends ScopeModel {
protected static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModel.class);
public static final String NAME = "ApplicationModel";
private final List<ModuleModel> moduleModels = new CopyOnWriteArrayList<>();
private final List<ModuleModel> pubModuleModels = new CopyOnWriteArrayList<>();
private volatile Environment environment;
private volatile ConfigManager configManager;
private volatile ServiceRepository serviceRepository;
private volatile ApplicationDeployer deployer;
private final FrameworkModel frameworkModel;
private final ModuleModel internalModule;
private volatile ModuleModel defaultModule;
// internal module index is 0, default module index is 1
private final AtomicInteger moduleIndex = new AtomicInteger(0);
// --------- static methods ----------//
public static ApplicationModel ofNullable(ApplicationModel applicationModel) {
if (applicationModel != null) {
return applicationModel;
} else {
return defaultModel();
}
}
/**
* During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or ApplicationModel.defaultModel()
* will return a broken model, maybe cause unpredictable problem.
* Recommendation: Avoid using the default model as much as possible.
*
* @return the global default ApplicationModel
*/
public static ApplicationModel defaultModel() {
// should get from default FrameworkModel, avoid out of sync
return FrameworkModel.defaultModel().defaultApplication();
}
// ------------- instance methods ---------------//
protected ApplicationModel(FrameworkModel frameworkModel) {
this(frameworkModel, false);
}
protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) {
super(frameworkModel, ExtensionScope.APPLICATION, isInternal);
synchronized (instLock) {
Assert.notNull(frameworkModel, "FrameworkModel can not be null");
this.frameworkModel = frameworkModel;
frameworkModel.addApplication(this);
if (LOGGER.isInfoEnabled()) {
LOGGER.info(getDesc() + " is created");
}
initialize();
this.internalModule = new ModuleModel(this, true);
this.serviceRepository = new ServiceRepository(this);
ExtensionLoader<ApplicationInitListener> extensionLoader =
this.getExtensionLoader(ApplicationInitListener.class);
Set<String> listenerNames = extensionLoader.getSupportedExtensions();
for (String listenerName : listenerNames) {
extensionLoader.getExtension(listenerName).init();
}
initApplicationExts();
ExtensionLoader<ScopeModelInitializer> initializerExtensionLoader =
this.getExtensionLoader(ScopeModelInitializer.class);
Set<ScopeModelInitializer> initializers = initializerExtensionLoader.getSupportedExtensionInstances();
for (ScopeModelInitializer initializer : initializers) {
initializer.initializeApplicationModel(this);
}
Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null");
Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null");
Assert.assertTrue(
getApplicationConfigManager().isInitialized(), "ApplicationConfigManager can not be initialized");
}
}
// already synchronized in constructor
private void initApplicationExts() {
Set<ApplicationExt> exts = this.getExtensionLoader(ApplicationExt.class).getSupportedExtensionInstances();
for (ApplicationExt ext : exts) {
ext.initialize();
}
}
@Override
protected void onDestroy() {
synchronized (instLock) {
// 1. remove from frameworkModel
frameworkModel.removeApplication(this);
// 2. pre-destroy, set stopping
if (deployer != null) {
// destroy registries and unregister services from registries first to notify consumers to stop
// consuming this instance.
deployer.preDestroy();
}
// 3. Try to destroy protocols to stop this instance from receiving new requests from connections
frameworkModel.tryDestroyProtocols();
// 4. destroy application resources
for (ModuleModel moduleModel : moduleModels) {
if (moduleModel != internalModule) {
moduleModel.destroy();
}
}
// 5. destroy internal module later
internalModule.destroy();
// 6. post-destroy, release registry resources
if (deployer != null) {
deployer.postDestroy();
}
// 7. destroy other resources (e.g. ZookeeperTransporter )
notifyDestroy();
if (environment != null) {
environment.destroy();
environment = null;
}
if (configManager != null) {
configManager.destroy();
configManager = null;
}
if (serviceRepository != null) {
serviceRepository.destroy();
serviceRepository = null;
}
// 8. destroy framework if none application
frameworkModel.tryDestroy();
}
}
public FrameworkModel getFrameworkModel() {
return frameworkModel;
}
public ModuleModel newModule() {
synchronized (instLock) {
return new ModuleModel(this);
}
}
@Override
public Environment modelEnvironment() {
if (environment == null) {
environment =
(Environment) this.getExtensionLoader(ApplicationExt.class).getExtension(Environment.NAME);
}
return environment;
}
public ConfigManager getApplicationConfigManager() {
if (configManager == null) {
configManager = (ConfigManager)
this.getExtensionLoader(ApplicationExt.class).getExtension(ConfigManager.NAME);
}
return configManager;
}
public ServiceRepository getApplicationServiceRepository() {
return serviceRepository;
}
public ExecutorRepository getApplicationExecutorRepository() {
return ExecutorRepository.getInstance(this);
}
public boolean NotExistApplicationConfig() {
return !getApplicationConfigManager().getApplication().isPresent();
}
public ApplicationConfig getCurrentConfig() {
return getApplicationConfigManager().getApplicationOrElseThrow();
}
public String getApplicationName() {
return getCurrentConfig().getName();
}
public String tryGetApplicationName() {
Optional<ApplicationConfig> appCfgOptional =
getApplicationConfigManager().getApplication();
return appCfgOptional.isPresent() ? appCfgOptional.get().getName() : null;
}
void addModule(ModuleModel moduleModel, boolean isInternal) {
synchronized (instLock) {
if (!this.moduleModels.contains(moduleModel)) {
checkDestroyed();
this.moduleModels.add(moduleModel);
moduleModel.setInternalId(buildInternalId(getInternalId(), moduleIndex.getAndIncrement()));
if (!isInternal) {
pubModuleModels.add(moduleModel);
}
}
}
}
public void removeModule(ModuleModel moduleModel) {
synchronized (instLock) {
this.moduleModels.remove(moduleModel);
this.pubModuleModels.remove(moduleModel);
if (moduleModel == defaultModule) {
defaultModule = findDefaultModule();
}
}
}
void tryDestroy() {
synchronized (instLock) {
if (this.moduleModels.isEmpty()
|| (this.moduleModels.size() == 1 && this.moduleModels.get(0) == internalModule)) {
destroy();
}
}
}
private void checkDestroyed() {
if (isDestroyed()) {
throw new IllegalStateException("ApplicationModel is destroyed");
}
}
public List<ModuleModel> getModuleModels() {
return Collections.unmodifiableList(moduleModels);
}
public List<ModuleModel> getPubModuleModels() {
return Collections.unmodifiableList(pubModuleModels);
}
public ModuleModel getDefaultModule() {
if (defaultModule == null) {
synchronized (instLock) {
if (defaultModule == null) {
defaultModule = findDefaultModule();
if (defaultModule == null) {
defaultModule = this.newModule();
}
}
}
}
return defaultModule;
}
private ModuleModel findDefaultModule() {
synchronized (instLock) {
for (ModuleModel moduleModel : moduleModels) {
if (moduleModel != internalModule) {
return moduleModel;
}
}
return null;
}
}
public ModuleModel getInternalModule() {
return internalModule;
}
@Override
public void addClassLoader(ClassLoader classLoader) {
super.addClassLoader(classLoader);
if (environment != null) {
environment.refreshClassLoaders();
}
}
@Override
public void removeClassLoader(ClassLoader classLoader) {
super.removeClassLoader(classLoader);
if (environment != null) {
environment.refreshClassLoaders();
}
}
@Override
protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) {
return super.checkIfClassLoaderCanRemoved(classLoader) && !containsClassLoader(classLoader);
}
protected boolean containsClassLoader(ClassLoader classLoader) {
return moduleModels.stream()
.anyMatch(moduleModel -> moduleModel.getClassLoaders().contains(classLoader));
}
public ApplicationDeployer getDeployer() {
return deployer;
}
public void setDeployer(ApplicationDeployer deployer) {
this.deployer = deployer;
}
@Override
protected Lock acquireDestroyLock() {
return frameworkModel.acquireDestroyLock();
}
// =============================== Deprecated Methods Start =======================================
/**
* @deprecated use {@link ServiceRepository#allConsumerModels()}
*/
@Deprecated
public static Collection<ConsumerModel> allConsumerModels() {
return defaultModel().getApplicationServiceRepository().allConsumerModels();
}
/**
* @deprecated use {@link ServiceRepository#allProviderModels()}
*/
@Deprecated
public static Collection<ProviderModel> allProviderModels() {
return defaultModel().getApplicationServiceRepository().allProviderModels();
}
/**
* @deprecated use {@link FrameworkServiceRepository#lookupExportedService(String)}
*/
@Deprecated
public static ProviderModel getProviderModel(String serviceKey) {
return defaultModel().getDefaultModule().getServiceRepository().lookupExportedService(serviceKey);
}
/**
* @deprecated ConsumerModel should fetch from context
*/
@Deprecated
public static ConsumerModel getConsumerModel(String serviceKey) {
return defaultModel().getDefaultModule().getServiceRepository().lookupReferredService(serviceKey);
}
/**
* @deprecated Replace to {@link ScopeModel#modelEnvironment()}
*/
@Deprecated
public static Environment getEnvironment() {
return defaultModel().modelEnvironment();
}
/**
* @deprecated Replace to {@link ApplicationModel#getApplicationConfigManager()}
*/
@Deprecated
public static ConfigManager getConfigManager() {
return defaultModel().getApplicationConfigManager();
}
/**
* @deprecated Replace to {@link ApplicationModel#getApplicationServiceRepository()}
*/
@Deprecated
public static ServiceRepository getServiceRepository() {
return defaultModel().getApplicationServiceRepository();
}
/**
* @deprecated Replace to {@link ApplicationModel#getApplicationExecutorRepository()}
*/
@Deprecated
public static ExecutorRepository getExecutorRepository() {
return defaultModel().getApplicationExecutorRepository();
}
/**
* @deprecated Replace to {@link ApplicationModel#getCurrentConfig()}
*/
@Deprecated
public static ApplicationConfig getApplicationConfig() {
return defaultModel().getCurrentConfig();
}
/**
* @deprecated Replace to {@link ApplicationModel#getApplicationName()}
*/
@Deprecated
public static String getName() {
return defaultModel().getCurrentConfig().getName();
}
/**
* @deprecated Replace to {@link ApplicationModel#getApplicationName()}
*/
@Deprecated
public static String getApplication() {
return getName();
}
// only for unit test
@Deprecated
public static void reset() {
if (FrameworkModel.defaultModel().getDefaultAppModel() != null) {
FrameworkModel.defaultModel().getDefaultAppModel().destroy();
}
}
/**
* @deprecated only for ut
*/
@Deprecated
public void setEnvironment(Environment environment) {
this.environment = environment;
}
/**
* @deprecated only for ut
*/
@Deprecated
public void setConfigManager(ConfigManager configManager) {
this.configManager = configManager;
}
/**
* @deprecated only for ut
*/
@Deprecated
public void setServiceRepository(ServiceRepository serviceRepository) {
this.serviceRepository = serviceRepository;
}
// =============================== Deprecated Methods End =======================================
}
| 7,055 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.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.rpc.model;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
/**
* Replaced with {@link MethodDescriptor}
*/
@Deprecated
public class ConsumerMethodModel {
private final Method method;
// private final boolean isCallBack;
// private final boolean isFuture;
private final String[] parameterTypes;
private final Class<?>[] parameterClasses;
private final Class<?> returnClass;
private final String methodName;
private final boolean generic;
private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>();
public ConsumerMethodModel(Method method) {
this.method = method;
this.parameterClasses = method.getParameterTypes();
this.returnClass = method.getReturnType();
this.parameterTypes = this.createParamSignature(parameterClasses);
this.methodName = method.getName();
this.generic = methodName.equals($INVOKE) && parameterTypes != null && parameterTypes.length == 3;
}
public Method getMethod() {
return method;
}
// public ConcurrentMap<String, Object> getAttributeMap() {
// return attributeMap;
// }
public void addAttribute(String key, Object value) {
this.attributeMap.put(key, value);
}
public Object getAttribute(String key) {
return this.attributeMap.get(key);
}
public Class<?> getReturnClass() {
return returnClass;
}
public String getMethodName() {
return methodName;
}
public String[] getParameterTypes() {
return parameterTypes;
}
private String[] createParamSignature(Class<?>[] args) {
if (args == null || args.length == 0) {
return new String[] {};
}
String[] paramSig = new String[args.length];
for (int x = 0; x < args.length; x++) {
paramSig[x] = args[x].getName();
}
return paramSig;
}
public boolean isGeneric() {
return generic;
}
public Class<?>[] getParameterClasses() {
return parameterClasses;
}
}
| 7,056 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.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.rpc.model;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.config.AbstractInterfaceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.ServiceConfigBase;
import java.util.Objects;
import java.util.Set;
public class ServiceModel {
private String serviceKey;
private Object proxyObject;
private Runnable destroyRunner;
private ClassLoader classLoader;
private final ClassLoader interfaceClassLoader;
private final ModuleModel moduleModel;
private final ServiceDescriptor serviceModel;
private AbstractInterfaceConfig config;
private final ServiceMetadata serviceMetadata;
public ServiceModel(
Object proxyObject,
String serviceKey,
ServiceDescriptor serviceModel,
ModuleModel moduleModel,
ClassLoader interfaceClassLoader) {
this(proxyObject, serviceKey, serviceModel, moduleModel, null, interfaceClassLoader);
}
public ServiceModel(
Object proxyObject,
String serviceKey,
ServiceDescriptor serviceModel,
ModuleModel moduleModel,
ServiceMetadata serviceMetadata,
ClassLoader interfaceClassLoader) {
this.proxyObject = proxyObject;
this.serviceKey = serviceKey;
this.serviceModel = serviceModel;
this.moduleModel = ScopeModelUtil.getModuleModel(moduleModel);
this.serviceMetadata = serviceMetadata;
this.interfaceClassLoader = interfaceClassLoader;
if (serviceMetadata != null) {
serviceMetadata.setServiceModel(this);
}
if (interfaceClassLoader != null) {
this.classLoader = interfaceClassLoader;
}
if (this.classLoader == null) {
this.classLoader = Thread.currentThread().getContextClassLoader();
}
}
@Deprecated
public AbstractInterfaceConfig getConfig() {
return config;
}
@Deprecated
public void setConfig(AbstractInterfaceConfig config) {
this.config = config;
}
/**
* ServiceModel should be decoupled from AbstractInterfaceConfig and removed in a future version
* @return
*/
@Deprecated
public ReferenceConfigBase<?> getReferenceConfig() {
if (config == null) {
return null;
}
if (config instanceof ReferenceConfigBase) {
return (ReferenceConfigBase<?>) config;
} else {
throw new IllegalArgumentException("Current ServiceModel is not a ConsumerModel");
}
}
/**
* ServiceModel should be decoupled from AbstractInterfaceConfig and removed in a future version
* @return
*/
@Deprecated
public ServiceConfigBase<?> getServiceConfig() {
if (config == null) {
return null;
}
if (config instanceof ServiceConfigBase) {
return (ServiceConfigBase<?>) config;
} else {
throw new IllegalArgumentException("Current ServiceModel is not a ProviderModel");
}
}
public String getServiceKey() {
return serviceKey;
}
public void setProxyObject(Object proxyObject) {
this.proxyObject = proxyObject;
}
public Object getProxyObject() {
return proxyObject;
}
public ServiceDescriptor getServiceModel() {
return serviceModel;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Return all method models for the current service
*
* @return method model list
*/
public Set<MethodDescriptor> getAllMethods() {
return serviceModel.getAllMethods();
}
public Class<?> getServiceInterfaceClass() {
return serviceModel.getServiceInterfaceClass();
}
public void setServiceKey(String serviceKey) {
this.serviceKey = serviceKey;
if (serviceMetadata != null) {
serviceMetadata.setServiceKey(serviceKey);
serviceMetadata.setGroup(BaseServiceMetadata.groupFromServiceKey(serviceKey));
}
}
public String getServiceName() {
return this.serviceMetadata.getServiceKey();
}
/**
* @return serviceMetadata
*/
public ServiceMetadata getServiceMetadata() {
return serviceMetadata;
}
public ModuleModel getModuleModel() {
return moduleModel;
}
public Runnable getDestroyRunner() {
return destroyRunner;
}
public void setDestroyRunner(Runnable destroyRunner) {
this.destroyRunner = destroyRunner;
}
public ClassLoader getInterfaceClassLoader() {
return interfaceClassLoader;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServiceModel that = (ServiceModel) o;
return Objects.equals(serviceKey, that.serviceKey)
&& Objects.equals(proxyObject, that.proxyObject)
&& Objects.equals(destroyRunner, that.destroyRunner)
&& Objects.equals(classLoader, that.classLoader)
&& Objects.equals(interfaceClassLoader, that.interfaceClassLoader)
&& Objects.equals(moduleModel, that.moduleModel)
&& Objects.equals(serviceModel, that.serviceModel)
&& Objects.equals(serviceMetadata, that.serviceMetadata);
}
@Override
public int hashCode() {
return Objects.hash(
serviceKey,
proxyObject,
destroyRunner,
classLoader,
interfaceClassLoader,
moduleModel,
serviceModel,
serviceMetadata);
}
}
| 7,057 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.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.rpc.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.ServiceConfigBase;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
/**
* Service repository for module
*/
public class ModuleServiceRepository {
private final ModuleModel moduleModel;
/**
* services
*/
private final ConcurrentMap<String, List<ServiceDescriptor>> services = new ConcurrentHashMap<>();
/**
* consumers ( key - group/interface:version value - consumerModel list)
*/
private final ConcurrentMap<String, List<ConsumerModel>> consumers = new ConcurrentHashMap<>();
/**
* providers
*/
private final ConcurrentMap<String, ProviderModel> providers = new ConcurrentHashMap<>();
private final FrameworkServiceRepository frameworkServiceRepository;
public ModuleServiceRepository(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
frameworkServiceRepository =
ScopeModelUtil.getFrameworkModel(moduleModel).getServiceRepository();
}
public ModuleModel getModuleModel() {
return moduleModel;
}
/**
* @deprecated Replaced to {@link ModuleServiceRepository#registerConsumer(ConsumerModel)}
*/
@Deprecated
public void registerConsumer(
String serviceKey,
ServiceDescriptor serviceDescriptor,
ReferenceConfigBase<?> rc,
Object proxy,
ServiceMetadata serviceMetadata) {
ClassLoader classLoader = null;
if (rc != null) {
classLoader = rc.getInterfaceClassLoader();
}
ConsumerModel consumerModel = new ConsumerModel(
serviceMetadata.getServiceKey(), proxy, serviceDescriptor, serviceMetadata, null, classLoader);
this.registerConsumer(consumerModel);
}
public void registerConsumer(ConsumerModel consumerModel) {
ConcurrentHashMapUtils.computeIfAbsent(
consumers, consumerModel.getServiceKey(), (serviceKey) -> new CopyOnWriteArrayList<>())
.add(consumerModel);
}
/**
* @deprecated Replaced to {@link ModuleServiceRepository#registerProvider(ProviderModel)}
*/
@Deprecated
public void registerProvider(
String serviceKey,
Object serviceInstance,
ServiceDescriptor serviceModel,
ServiceConfigBase<?> serviceConfig,
ServiceMetadata serviceMetadata) {
ClassLoader classLoader = null;
Class<?> cla = null;
if (serviceConfig != null) {
classLoader = serviceConfig.getInterfaceClassLoader();
cla = serviceConfig.getInterfaceClass();
}
ProviderModel providerModel =
new ProviderModel(serviceKey, serviceInstance, serviceModel, serviceMetadata, classLoader);
this.registerProvider(providerModel);
}
public void registerProvider(ProviderModel providerModel) {
providers.putIfAbsent(providerModel.getServiceKey(), providerModel);
frameworkServiceRepository.registerProvider(providerModel);
}
public ServiceDescriptor registerService(ServiceDescriptor serviceDescriptor) {
return registerService(serviceDescriptor.getServiceInterfaceClass(), serviceDescriptor);
}
public ServiceDescriptor registerService(Class<?> interfaceClazz) {
ServiceDescriptor serviceDescriptor = new ReflectionServiceDescriptor(interfaceClazz);
return registerService(interfaceClazz, serviceDescriptor);
}
public ServiceDescriptor registerService(Class<?> interfaceClazz, ServiceDescriptor serviceDescriptor) {
List<ServiceDescriptor> serviceDescriptors = ConcurrentHashMapUtils.computeIfAbsent(
services, interfaceClazz.getName(), k -> new CopyOnWriteArrayList<>());
synchronized (serviceDescriptors) {
Optional<ServiceDescriptor> previous = serviceDescriptors.stream()
.filter(s -> s.getServiceInterfaceClass().equals(interfaceClazz))
.findFirst();
if (previous.isPresent()) {
return previous.get();
} else {
serviceDescriptors.add(serviceDescriptor);
return serviceDescriptor;
}
}
}
/**
* See {@link #registerService(Class)}
* <p>
* we assume:
* 1. services with different interfaces are not allowed to have the same path.
* 2. services share the same interface but has different group/version can share the same path.
* 3. path's default value is the name of the interface.
*
* @param path
* @param interfaceClass
* @return
*/
public ServiceDescriptor registerService(String path, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = registerService(interfaceClass);
// if path is different with interface name, add extra path mapping
if (!interfaceClass.getName().equals(path)) {
List<ServiceDescriptor> serviceDescriptors =
ConcurrentHashMapUtils.computeIfAbsent(services, path, _k -> new CopyOnWriteArrayList<>());
synchronized (serviceDescriptors) {
Optional<ServiceDescriptor> previous = serviceDescriptors.stream()
.filter(s -> s.getServiceInterfaceClass().equals(serviceDescriptor.getServiceInterfaceClass()))
.findFirst();
if (previous.isPresent()) {
return previous.get();
} else {
serviceDescriptors.add(serviceDescriptor);
return serviceDescriptor;
}
}
}
return serviceDescriptor;
}
@Deprecated
public void reRegisterProvider(String newServiceKey, String serviceKey) {
ProviderModel providerModel = this.providers.get(serviceKey);
frameworkServiceRepository.unregisterProvider(providerModel);
providerModel.setServiceKey(newServiceKey);
this.providers.putIfAbsent(newServiceKey, providerModel);
frameworkServiceRepository.registerProvider(providerModel);
this.providers.remove(serviceKey);
}
@Deprecated
public void reRegisterConsumer(String newServiceKey, String serviceKey) {
List<ConsumerModel> consumerModel = this.consumers.get(serviceKey);
consumerModel.forEach(c -> c.setServiceKey(newServiceKey));
ConcurrentHashMapUtils.computeIfAbsent(this.consumers, newServiceKey, (k) -> new CopyOnWriteArrayList<>())
.addAll(consumerModel);
this.consumers.remove(serviceKey);
}
public void unregisterService(Class<?> interfaceClazz) {
// TODO remove
unregisterService(interfaceClazz.getName());
}
public void unregisterService(String path) {
services.remove(path);
}
public void unregisterProvider(ProviderModel providerModel) {
frameworkServiceRepository.unregisterProvider(providerModel);
providers.remove(providerModel.getServiceKey());
}
public void unregisterConsumer(ConsumerModel consumerModel) {
consumers.get(consumerModel.getServiceKey()).remove(consumerModel);
}
public List<ServiceDescriptor> getAllServices() {
List<ServiceDescriptor> serviceDescriptors =
services.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
return Collections.unmodifiableList(serviceDescriptors);
}
public ServiceDescriptor getService(String serviceName) {
// TODO, may need to distinguish service by class loader.
List<ServiceDescriptor> serviceDescriptors = services.get(serviceName);
if (CollectionUtils.isEmpty(serviceDescriptors)) {
return null;
}
return serviceDescriptors.get(0);
}
public ServiceDescriptor lookupService(String interfaceName) {
if (interfaceName != null && services.containsKey(interfaceName)) {
List<ServiceDescriptor> serviceDescriptors = services.get(interfaceName);
return serviceDescriptors.size() > 0 ? serviceDescriptors.get(0) : null;
} else {
return null;
}
}
public MethodDescriptor lookupMethod(String interfaceName, String methodName) {
ServiceDescriptor serviceDescriptor = lookupService(interfaceName);
if (serviceDescriptor == null) {
return null;
}
List<MethodDescriptor> methods = serviceDescriptor.getMethods(methodName);
if (CollectionUtils.isEmpty(methods)) {
return null;
}
return methods.iterator().next();
}
public List<ProviderModel> getExportedServices() {
return Collections.unmodifiableList(new ArrayList<>(providers.values()));
}
public ProviderModel lookupExportedService(String serviceKey) {
return providers.get(serviceKey);
}
public List<ConsumerModel> getReferredServices() {
List<ConsumerModel> consumerModels =
consumers.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
return Collections.unmodifiableList(consumerModels);
}
/**
* @deprecated Replaced to {@link ModuleServiceRepository#lookupReferredServices(String)}
*/
@Deprecated
public ConsumerModel lookupReferredService(String serviceKey) {
if (consumers.containsKey(serviceKey)) {
List<ConsumerModel> consumerModels = consumers.get(serviceKey);
return consumerModels.size() > 0 ? consumerModels.get(0) : null;
} else {
return null;
}
}
public List<ConsumerModel> lookupReferredServices(String serviceKey) {
return consumers.get(serviceKey);
}
public void destroy() {
for (ProviderModel providerModel : providers.values()) {
frameworkServiceRepository.unregisterProvider(providerModel);
}
providers.clear();
consumers.clear();
services.clear();
}
}
| 7,058 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModelConstants.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.rpc.model;
public interface ModelConstants {
String DEPLOYER = "deployer";
/**
* Keep Dubbo running when spring is stopped
*/
String KEEP_RUNNING_ON_SPRING_CLOSED = "keepRunningOnSpringClosed";
String KEEP_RUNNING_ON_SPRING_CLOSED_KEY = "dubbo.module.keepRunningOnSpringClosed";
}
| 7,059 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelInitializer.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.rpc.model;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.SELF)
public interface ScopeModelInitializer {
void initializeFrameworkModel(FrameworkModel frameworkModel);
void initializeApplicationModel(ApplicationModel applicationModel);
void initializeModuleModel(ModuleModel moduleModel);
}
| 7,060 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.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.rpc.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class ServiceRepository {
public static final String NAME = "repository";
private final AtomicBoolean initialized = new AtomicBoolean(false);
private final ApplicationModel applicationModel;
public ServiceRepository(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
initialize();
}
private void initialize() {
if (initialized.compareAndSet(false, true)) {
Set<BuiltinServiceDetector> builtinServices = applicationModel
.getExtensionLoader(BuiltinServiceDetector.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(builtinServices)) {
for (BuiltinServiceDetector service : builtinServices) {
applicationModel.getInternalModule().getServiceRepository().registerService(service.getService());
}
}
}
}
public void destroy() {
// TODO destroy application service repository
}
public Collection<ConsumerModel> allConsumerModels() {
// aggregate from sub modules
List<ConsumerModel> allConsumerModels = new ArrayList<>();
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
allConsumerModels.addAll(moduleModel.getServiceRepository().getReferredServices());
}
return allConsumerModels;
}
public Collection<ProviderModel> allProviderModels() {
// aggregate from sub modules
List<ProviderModel> allProviderModels = new ArrayList<>();
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
allProviderModels.addAll(moduleModel.getServiceRepository().getExportedServices());
}
return allProviderModels;
}
}
| 7,061 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.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.rpc.model;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface BuiltinServiceDetector {
Class<?> getService();
}
| 7,062 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkServiceRepository.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.rpc.model;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.apache.dubbo.common.BaseServiceMetadata.interfaceFromServiceKey;
import static org.apache.dubbo.common.BaseServiceMetadata.versionFromServiceKey;
/**
* Service repository for framework
*/
public class FrameworkServiceRepository {
private final FrameworkModel frameworkModel;
// useful to find a provider model quickly with group/serviceInterfaceName:version
private final ConcurrentMap<String, ProviderModel> providers = new ConcurrentHashMap<>();
// useful to find a provider model quickly with serviceInterfaceName:version
private final ConcurrentMap<String, List<ProviderModel>> providersWithoutGroup = new ConcurrentHashMap<>();
public FrameworkServiceRepository(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
public void registerProvider(ProviderModel providerModel) {
String key = providerModel.getServiceKey();
ProviderModel previous = providers.putIfAbsent(key, providerModel);
if (previous != null && previous != providerModel) {
// TODO callback service multi instances
// throw new IllegalStateException("Register duplicate provider for key: " + key);
}
String keyWithoutGroup = keyWithoutGroup(key);
ConcurrentHashMapUtils.computeIfAbsent(
providersWithoutGroup, keyWithoutGroup, (k) -> new CopyOnWriteArrayList<>())
.add(providerModel);
}
public void unregisterProvider(ProviderModel providerModel) {
providers.remove(providerModel.getServiceKey());
String keyWithoutGroup = keyWithoutGroup(providerModel.getServiceKey());
providersWithoutGroup.remove(keyWithoutGroup);
}
public ProviderModel lookupExportedServiceWithoutGroup(String key) {
if (providersWithoutGroup.containsKey(key)) {
List<ProviderModel> providerModels = providersWithoutGroup.get(key);
return providerModels.size() > 0 ? providerModels.get(0) : null;
} else {
return null;
}
}
public List<ProviderModel> lookupExportedServicesWithoutGroup(String key) {
return providersWithoutGroup.get(key);
}
public ProviderModel lookupExportedService(String serviceKey) {
return providers.get(serviceKey);
}
public List<ProviderModel> allProviderModels() {
return Collections.unmodifiableList(new ArrayList<>(providers.values()));
}
public List<ConsumerModel> allConsumerModels() {
List<ConsumerModel> consumerModels = new LinkedList<>();
frameworkModel
.getApplicationModels()
.forEach(applicationModel -> consumerModels.addAll(
applicationModel.getApplicationServiceRepository().allConsumerModels()));
return Collections.unmodifiableList(consumerModels);
}
private static String keyWithoutGroup(String serviceKey) {
String interfaceName = interfaceFromServiceKey(serviceKey);
String version = versionFromServiceKey(serviceKey);
if (StringUtils.isEmpty(version)) {
return interfaceName;
}
return interfaceName + CommonConstants.GROUP_CHAR_SEPARATOR + version;
}
}
| 7,063 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.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.rpc.model;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.common.utils.ReflectUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Stream;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED;
public class ReflectionMethodDescriptor implements MethodDescriptor {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ReflectionMethodDescriptor.class);
private final ConcurrentMap<String, Object> attributeMap = new ConcurrentHashMap<>();
public final String methodName;
private final String[] compatibleParamSignatures;
private final Class<?>[] parameterClasses;
private final Class<?> returnClass;
private final Type[] returnTypes;
private final String paramDesc;
private final Method method;
private final boolean generic;
private final RpcType rpcType;
public ReflectionMethodDescriptor(Method method) {
this.method = method;
this.methodName = method.getName();
this.parameterClasses = method.getParameterTypes();
this.returnClass = method.getReturnType();
Type[] returnTypesResult;
try {
returnTypesResult = ReflectUtils.getReturnTypes(method);
} catch (Throwable throwable) {
logger.error(
COMMON_REFLECTIVE_OPERATION_FAILED,
"",
"",
"fail to get return types. Method name: " + methodName + " Declaring class:"
+ method.getDeclaringClass().getName(),
throwable);
returnTypesResult = new Type[] {returnClass, returnClass};
}
this.returnTypes = returnTypesResult;
this.paramDesc = ReflectUtils.getDesc(parameterClasses);
this.compatibleParamSignatures =
Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new);
this.generic = (methodName.equals($INVOKE) || methodName.equals($INVOKE_ASYNC)) && parameterClasses.length == 3;
this.rpcType = determineRpcType();
}
private RpcType determineRpcType() {
if (generic) {
return RpcType.UNARY;
}
if (parameterClasses.length > 2) {
return RpcType.UNARY;
}
if (parameterClasses.length == 1 && isStreamType(parameterClasses[0]) && isStreamType(returnClass)) {
return RpcType.BI_STREAM;
}
if (parameterClasses.length == 2
&& !isStreamType(parameterClasses[0])
&& isStreamType(parameterClasses[1])
&& returnClass.getName().equals(void.class.getName())) {
return RpcType.SERVER_STREAM;
}
if (Arrays.stream(parameterClasses).anyMatch(this::isStreamType) || isStreamType(returnClass)) {
throw new IllegalStateException(
"Bad stream method signature. method(" + methodName + ":" + paramDesc + ")");
}
// Can not determine client stream because it has same signature with bi_stream
return RpcType.UNARY;
}
private boolean isStreamType(Class<?> classType) {
return StreamObserver.class.isAssignableFrom(classType);
}
@Override
public String getMethodName() {
return methodName;
}
@Override
public Method getMethod() {
return method;
}
@Override
public String[] getCompatibleParamSignatures() {
return compatibleParamSignatures;
}
@Override
public Class<?>[] getParameterClasses() {
return parameterClasses;
}
@Override
public String getParamDesc() {
return paramDesc;
}
@Override
public Class<?> getReturnClass() {
return returnClass;
}
@Override
public Type[] getReturnTypes() {
return returnTypes;
}
@Override
public RpcType getRpcType() {
return rpcType;
}
@Override
public boolean isGeneric() {
return generic;
}
public void addAttribute(String key, Object value) {
this.attributeMap.put(key, value);
}
public Object getAttribute(String key) {
return this.attributeMap.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReflectionMethodDescriptor that = (ReflectionMethodDescriptor) o;
return generic == that.generic
&& Objects.equals(method, that.method)
&& Objects.equals(paramDesc, that.paramDesc)
&& Arrays.equals(compatibleParamSignatures, that.compatibleParamSignatures)
&& Arrays.equals(parameterClasses, that.parameterClasses)
&& Objects.equals(returnClass, that.returnClass)
&& Arrays.equals(returnTypes, that.returnTypes)
&& Objects.equals(methodName, that.methodName)
&& Objects.equals(attributeMap, that.attributeMap);
}
@Override
public int hashCode() {
int result = Objects.hash(method, paramDesc, returnClass, methodName, generic, attributeMap);
result = 31 * result + Arrays.hashCode(compatibleParamSignatures);
result = 31 * result + Arrays.hashCode(parameterClasses);
result = 31 * result + Arrays.hashCode(returnTypes);
return result;
}
}
| 7,064 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.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.rpc.model;
/**
* An interface to inject FrameworkModel/ApplicationModel/ModuleModel for SPI extensions and internal beans.
*/
public interface ScopeModelAware {
/**
* Override this method if you need get the scope model (maybe one of FrameworkModel/ApplicationModel/ModuleModel).
* @param scopeModel
*/
default void setScopeModel(ScopeModel scopeModel) {}
/**
* Override this method if you just need framework model
* @param frameworkModel
*/
default void setFrameworkModel(FrameworkModel frameworkModel) {}
/**
* Override this method if you just need application model
* @param applicationModel
*/
default void setApplicationModel(ApplicationModel applicationModel) {}
/**
* Override this method if you just need module model
* @param moduleModel
*/
default void setModuleModel(ModuleModel moduleModel) {}
}
| 7,065 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/Pack.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.rpc.model;
public interface Pack {
/**
* @param obj instance
* @return byte array
* @throws Exception when error occurs
*/
byte[] pack(Object obj) throws Exception;
}
| 7,066 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptor.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.rpc.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class ReflectionServiceDescriptor implements ServiceDescriptor {
private final String interfaceName;
private final Class<?> serviceInterfaceClass;
// to accelerate search
private final Map<String, List<MethodDescriptor>> methods = new HashMap<>();
private final Map<String, Map<String, MethodDescriptor>> descToMethods = new HashMap<>();
private final ConcurrentNavigableMap<String, FullServiceDefinition> serviceDefinitions =
new ConcurrentSkipListMap<>();
public ReflectionServiceDescriptor(String interfaceName, Class<?> interfaceClass) {
this.interfaceName = interfaceName;
this.serviceInterfaceClass = interfaceClass;
}
public void addMethod(MethodDescriptor methodDescriptor) {
methods.put(methodDescriptor.getMethodName(), Collections.singletonList(methodDescriptor));
}
public ReflectionServiceDescriptor(Class<?> interfaceClass) {
this.serviceInterfaceClass = interfaceClass;
this.interfaceName = interfaceClass.getName();
initMethods();
}
public FullServiceDefinition getFullServiceDefinition(String serviceKey) {
return serviceDefinitions.computeIfAbsent(
serviceKey,
(k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap()));
}
private void initMethods() {
Method[] methodsToExport = this.serviceInterfaceClass.getMethods();
for (Method method : methodsToExport) {
method.setAccessible(true);
MethodDescriptor methodDescriptor = new ReflectionMethodDescriptor(method);
List<MethodDescriptor> methodModels = methods.computeIfAbsent(method.getName(), (k) -> new ArrayList<>(1));
methodModels.add(methodDescriptor);
}
methods.forEach((methodName, methodList) -> {
Map<String, MethodDescriptor> descMap = descToMethods.computeIfAbsent(methodName, k -> new HashMap<>());
// not support BI_STREAM and SERVER_STREAM at the same time, for example,
// void foo(Request, StreamObserver<Response>) ---> SERVER_STREAM
// StreamObserver<Response> foo(StreamObserver<Request>) ---> BI_STREAM
long streamMethodCount = methodList.stream()
.peek(methodModel -> descMap.put(methodModel.getParamDesc(), methodModel))
.map(MethodDescriptor::getRpcType)
.filter(rpcType -> rpcType == MethodDescriptor.RpcType.SERVER_STREAM
|| rpcType == MethodDescriptor.RpcType.BI_STREAM)
.count();
if (streamMethodCount > 1L)
throw new IllegalStateException("Stream method could not be overloaded.There are " + streamMethodCount
+ " stream method signatures. method(" + methodName + ")");
});
}
public String getInterfaceName() {
return interfaceName;
}
public Class<?> getServiceInterfaceClass() {
return serviceInterfaceClass;
}
public Set<MethodDescriptor> getAllMethods() {
Set<MethodDescriptor> methodModels = new HashSet<>();
methods.forEach((k, v) -> methodModels.addAll(v));
return methodModels;
}
/**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param params
* @return
*/
public MethodDescriptor getMethod(String methodName, String params) {
Map<String, MethodDescriptor> methods = descToMethods.get(methodName);
if (CollectionUtils.isNotEmptyMap(methods)) {
return methods.get(params);
}
return null;
}
/**
* Does not use Optional as return type to avoid potential performance decrease.
*
* @param methodName
* @param paramTypes
* @return
*/
public MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes) {
List<MethodDescriptor> methodModels = methods.get(methodName);
if (CollectionUtils.isNotEmpty(methodModels)) {
for (MethodDescriptor descriptor : methodModels) {
if (Arrays.equals(paramTypes, descriptor.getParameterClasses())) {
return descriptor;
}
}
}
return null;
}
public List<MethodDescriptor> getMethods(String methodName) {
return methods.get(methodName);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReflectionServiceDescriptor that = (ReflectionServiceDescriptor) o;
return Objects.equals(interfaceName, that.interfaceName)
&& Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass)
&& Objects.equals(methods, that.methods)
&& Objects.equals(descToMethods, that.descToMethods);
}
@Override
public int hashCode() {
return Objects.hash(interfaceName, serviceInterfaceClass, methods, descToMethods);
}
}
| 7,067 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.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.rpc.executor;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ApplicationModel;
@SPI("default")
public interface IsolationExecutorSupportFactory {
ExecutorSupport createIsolationExecutorSupport(URL url);
static ExecutorSupport getIsolationExecutorSupport(URL url) {
ApplicationModel applicationModel = url.getOrDefaultApplicationModel();
ExtensionLoader<IsolationExecutorSupportFactory> extensionLoader =
applicationModel.getExtensionLoader(IsolationExecutorSupportFactory.class);
IsolationExecutorSupportFactory factory = extensionLoader.getOrDefaultExtension(url.getProtocol());
return factory.createIsolationExecutorSupport(url);
}
}
| 7,068 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultIsolationExecutorSupportFactory.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.rpc.executor;
import org.apache.dubbo.common.URL;
public class DefaultIsolationExecutorSupportFactory implements IsolationExecutorSupportFactory {
@Override
public ExecutorSupport createIsolationExecutorSupport(URL url) {
return new DefaultExecutorSupport(url);
}
}
| 7,069 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/AbstractIsolationExecutorSupport.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.rpc.executor;
import org.apache.dubbo.common.ServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.List;
import java.util.concurrent.Executor;
public abstract class AbstractIsolationExecutorSupport implements ExecutorSupport {
private final URL url;
private final ExecutorRepository executorRepository;
private final FrameworkServiceRepository frameworkServiceRepository;
public AbstractIsolationExecutorSupport(URL url) {
this.url = url;
this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel());
this.frameworkServiceRepository = url.getOrDefaultFrameworkModel().getServiceRepository();
}
@Override
public Executor getExecutor(Object data) {
ProviderModel providerModel = getProviderModel(data);
if (providerModel == null) {
return executorRepository.getExecutor(url);
}
List<URL> serviceUrls = providerModel.getServiceUrls();
if (serviceUrls == null || serviceUrls.isEmpty()) {
return executorRepository.getExecutor(url);
}
for (URL serviceUrl : serviceUrls) {
if (serviceUrl.getProtocol().equals(url.getProtocol()) && serviceUrl.getPort() == url.getPort()) {
return executorRepository.getExecutor(providerModel, serviceUrl);
}
}
return executorRepository.getExecutor(providerModel, serviceUrls.get(0));
}
protected ServiceKey getServiceKey(Object data) {
return null;
}
protected ProviderModel getProviderModel(Object data) {
ServiceKey serviceKey = getServiceKey(data);
if (serviceKey == null) {
return null;
}
return frameworkServiceRepository.lookupExportedService(serviceKey.toString());
}
}
| 7,070 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/ExecutorSupport.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.rpc.executor;
import java.util.concurrent.Executor;
public interface ExecutorSupport {
Executor getExecutor(Object data);
}
| 7,071 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.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.rpc.executor;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import java.util.concurrent.Executor;
public class DefaultExecutorSupport implements ExecutorSupport {
private final ExecutorRepository executorRepository;
private final URL url;
public DefaultExecutorSupport(URL url) {
this.url = url;
this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel());
}
@Override
public Executor getExecutor(Object data) {
return executorRepository.getExecutor(url);
}
}
| 7,072 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.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.rpc.service;
import org.apache.dubbo.rpc.model.ReflectionServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
public class ServiceDescriptorInternalCache {
private static final ServiceDescriptor genericServiceDescriptor =
new ReflectionServiceDescriptor(GenericService.class);
private static final ServiceDescriptor echoServiceDescriptor = new ReflectionServiceDescriptor(EchoService.class);
public static ServiceDescriptor genericService() {
return genericServiceDescriptor;
}
public static ServiceDescriptor echoService() {
return echoServiceDescriptor;
}
}
| 7,073 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericException.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.rpc.service;
import org.apache.dubbo.common.utils.StringUtils;
/**
* GenericException
*
* @export
*/
public class GenericException extends RuntimeException {
private static final long serialVersionUID = -1182299763306599962L;
private String exceptionClass;
private String exceptionMessage;
public GenericException() {}
public GenericException(String exceptionMessage) {
super(exceptionMessage);
this.exceptionMessage = exceptionMessage;
}
public GenericException(String exceptionClass, String exceptionMessage) {
super(exceptionMessage);
this.exceptionClass = exceptionClass;
this.exceptionMessage = exceptionMessage;
}
public GenericException(Throwable cause) {
super(StringUtils.toString(cause));
this.exceptionClass = cause.getClass().getName();
this.exceptionMessage = cause.getMessage();
}
public GenericException(String message, Throwable cause, String exceptionClass, String exceptionMessage) {
super(message, cause);
this.exceptionClass = exceptionClass;
this.exceptionMessage = exceptionMessage;
}
public String getExceptionClass() {
return exceptionClass;
}
public void setExceptionClass(String exceptionClass) {
this.exceptionClass = exceptionClass;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
}
| 7,074 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/Destroyable.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.rpc.service;
public interface Destroyable {
void $destroy();
}
| 7,075 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericService.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.rpc.service;
import java.util.concurrent.CompletableFuture;
/**
* Generic service interface
*
* @export
*/
public interface GenericService {
/**
* Generic invocation
*
* @param method Method name, e.g. findPerson. If there are overridden methods, parameter info is
* required, e.g. findPerson(java.lang.String)
* @param parameterTypes Parameter types
* @param args Arguments
* @return invocation return value
* @throws GenericException potential exception thrown from the invocation
*/
Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException;
default CompletableFuture<Object> $invokeAsync(String method, String[] parameterTypes, Object[] args)
throws GenericException {
Object object = $invoke(method, parameterTypes, args);
if (object instanceof CompletableFuture) {
return (CompletableFuture<Object>) object;
}
return CompletableFuture.completedFuture(object);
}
}
| 7,076 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.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.rpc.service;
/**
* Echo service.
* @export
*/
public interface EchoService {
/**
* echo test.
*
* @param message message.
* @return message.
*/
Object $echo(Object message);
}
| 7,077 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.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.rpc.service;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
public class GenericServiceDetector implements BuiltinServiceDetector {
@Override
public Class<?> getService() {
return GenericService.class;
}
}
| 7,078 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.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.rpc.service;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
public class EchoServiceDetector implements BuiltinServiceDetector {
@Override
public Class<?> getService() {
return EchoService.class;
}
}
| 7,079 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.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.metadata.definition;
import org.apache.dubbo.metadata.definition.model.MethodDefinition;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* {@link MethodDefinition} Builder based on Java Reflection
*
* @since 2.7.6
*/
public class MethodDefinitionBuilder {
private final TypeDefinitionBuilder builder;
public MethodDefinitionBuilder(TypeDefinitionBuilder builder) {
this.builder = builder;
}
public MethodDefinitionBuilder() {
this.builder = new TypeDefinitionBuilder();
}
/**
* Build the instance of {@link MethodDefinition}
*
* @param method {@link Method}
* @return non-null
*/
public MethodDefinition build(Method method) {
MethodDefinition md = new MethodDefinition();
md.setName(method.getName());
// Process the parameters
Class<?>[] paramTypes = method.getParameterTypes();
Type[] genericParamTypes = method.getGenericParameterTypes();
int paramSize = paramTypes.length;
String[] parameterTypes = new String[paramSize];
List<TypeDefinition> parameters = new ArrayList<>(paramSize);
for (int i = 0; i < paramSize; i++) {
TypeDefinition parameter = builder.build(genericParamTypes[i], paramTypes[i]);
parameterTypes[i] = parameter.getType();
parameters.add(parameter);
}
md.setParameterTypes(parameterTypes);
md.setParameters(parameters);
// Process return type.
TypeDefinition td = builder.build(method.getGenericReturnType(), method.getReturnType());
md.setReturnType(td.getType());
return md;
}
}
| 7,080 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.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.metadata.definition;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.definition.model.MethodDefinition;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.definition.util.ClassUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* 2015/1/27.
*/
public final class ServiceDefinitionBuilder {
/**
* Describe a Java interface in {@link ServiceDefinition}.
*
* @return Service description
*/
public static ServiceDefinition build(final Class<?> interfaceClass) {
ServiceDefinition sd = new ServiceDefinition();
build(sd, interfaceClass);
return sd;
}
public static FullServiceDefinition buildFullDefinition(final Class<?> interfaceClass) {
FullServiceDefinition sd = new FullServiceDefinition();
build(sd, interfaceClass);
return sd;
}
public static FullServiceDefinition buildFullDefinition(final Class<?> interfaceClass, Map<String, String> params) {
FullServiceDefinition sd = new FullServiceDefinition();
build(sd, interfaceClass);
sd.setParameters(params);
return sd;
}
public static <T extends ServiceDefinition> void build(T sd, final Class<?> interfaceClass) {
sd.setCanonicalName(interfaceClass.getCanonicalName());
sd.setCodeSource(ClassUtils.getCodeSource(interfaceClass));
Annotation[] classAnnotations = interfaceClass.getAnnotations();
sd.setAnnotations(annotationToStringList(classAnnotations));
TypeDefinitionBuilder builder = new TypeDefinitionBuilder();
List<Method> methods = ClassUtils.getPublicNonStaticMethods(interfaceClass);
for (Method method : methods) {
MethodDefinition md = new MethodDefinition();
md.setName(method.getName());
Annotation[] methodAnnotations = method.getAnnotations();
md.setAnnotations(annotationToStringList(methodAnnotations));
// Process parameter types.
Class<?>[] paramTypes = method.getParameterTypes();
Type[] genericParamTypes = method.getGenericParameterTypes();
String[] parameterTypes = new String[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
TypeDefinition td = builder.build(genericParamTypes[i], paramTypes[i]);
parameterTypes[i] = td.getType();
}
md.setParameterTypes(parameterTypes);
// Process return type.
TypeDefinition td = builder.build(method.getGenericReturnType(), method.getReturnType());
md.setReturnType(td.getType());
sd.getMethods().add(md);
}
sd.setTypes(builder.getTypeDefinitions());
}
private static List<String> annotationToStringList(Annotation[] annotations) {
if (annotations == null) {
return Collections.emptyList();
}
List<String> list = new ArrayList<>();
for (Annotation annotation : annotations) {
list.add(annotation.toString());
}
return list;
}
/**
* Describe a Java interface in Json schema.
*
* @return Service description
*/
public static String schema(final Class<?> clazz) {
ServiceDefinition sd = build(clazz);
return JsonUtils.toJson(sd);
}
private ServiceDefinitionBuilder() {}
}
| 7,081 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.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.metadata.definition;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.metadata.definition.builder.DefaultTypeBuilder;
import org.apache.dubbo.metadata.definition.builder.TypeBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 2015/1/27.
*/
public class TypeDefinitionBuilder {
private static final Logger logger = LoggerFactory.getLogger(TypeDefinitionBuilder.class);
public static List<TypeBuilder> BUILDERS;
public static void initBuilders(FrameworkModel model) {
Set<TypeBuilder> tbs = model.getExtensionLoader(TypeBuilder.class).getSupportedExtensionInstances();
BUILDERS = new ArrayList<>(tbs);
}
public static TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
TypeBuilder builder = getGenericTypeBuilder(clazz);
TypeDefinition td;
if (clazz.isPrimitive() || ClassUtils.isSimpleType(clazz)) { // changed since 2.7.6
td = new TypeDefinition(clazz.getCanonicalName());
typeCache.put(clazz.getCanonicalName(), td);
} else if (builder != null) {
td = builder.build(type, clazz, typeCache);
} else {
td = DefaultTypeBuilder.build(clazz, typeCache);
}
return td;
}
private static TypeBuilder getGenericTypeBuilder(Class<?> clazz) {
for (TypeBuilder builder : BUILDERS) {
try {
if (builder.accept(clazz)) {
return builder;
}
} catch (NoClassDefFoundError cnfe) {
// ignore
logger.info("Throw classNotFound (" + cnfe.getMessage() + ") in " + builder.getClass());
}
}
return null;
}
private final Map<String, TypeDefinition> typeCache = new HashMap<>();
public TypeDefinition build(Type type, Class<?> clazz) {
return build(type, clazz, typeCache);
}
public List<TypeDefinition> getTypeDefinitions() {
return new ArrayList<>(typeCache.values());
}
}
| 7,082 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.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.metadata.definition.util;
import org.apache.dubbo.common.utils.StringUtils;
import java.io.InputStream;
import java.util.Properties;
/**
* 2015/1/27.
*/
public class JaketConfigurationUtils {
private static final String CONFIGURATION_FILE = "jaket.properties";
private static String[] includedInterfacePackages;
private static String[] includedTypePackages;
private static String[] closedTypes;
static {
Properties props = new Properties();
InputStream inStream = JaketConfigurationUtils.class.getClassLoader().getResourceAsStream(CONFIGURATION_FILE);
try {
props.load(inStream);
String value = (String) props.get("included_interface_packages");
if (StringUtils.isNotEmpty(value)) {
includedInterfacePackages = value.split(",");
}
value = props.getProperty("included_type_packages");
if (StringUtils.isNotEmpty(value)) {
includedTypePackages = value.split(",");
}
value = props.getProperty("closed_types");
if (StringUtils.isNotEmpty(value)) {
closedTypes = value.split(",");
}
} catch (Throwable e) {
// Ignore it.
}
}
public static boolean isExcludedInterface(Class<?> clazz) {
if (includedInterfacePackages == null || includedInterfacePackages.length == 0) {
return false;
}
for (String packagePrefix : includedInterfacePackages) {
if (clazz.getCanonicalName().startsWith(packagePrefix)) {
return false;
}
}
return true;
}
public static boolean isExcludedType(Class<?> clazz) {
if (includedTypePackages == null || includedTypePackages.length == 0) {
return false;
}
for (String packagePrefix : includedTypePackages) {
if (clazz.getCanonicalName().startsWith(packagePrefix)) {
return false;
}
}
return true;
}
public static boolean needAnalyzing(Class<?> clazz) {
String canonicalName = clazz.getCanonicalName();
if (closedTypes != null && closedTypes.length > 0) {
for (String type : closedTypes) {
if (canonicalName.startsWith(type)) {
return false;
}
}
}
return !isExcludedType(clazz);
}
}
| 7,083 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/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.metadata.definition.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
/**
* 2015/1/27.
*/
public final class ClassUtils {
/**
* Get the code source file or class path of the Class passed in.
*
* @param clazz
* @return Jar file name or class path.
*/
public static String getCodeSource(Class<?> clazz) {
ProtectionDomain protectionDomain = clazz.getProtectionDomain();
if (protectionDomain == null || protectionDomain.getCodeSource() == null) {
return null;
}
CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
URL location = codeSource.getLocation();
if (location == null) {
return null;
}
String path = location.toExternalForm();
if (path.endsWith(".jar") && path.contains("/")) {
return path.substring(path.lastIndexOf('/') + 1);
}
return path;
}
/**
* Get all non-static fields of the Class passed in or its super classes.
* <p>
*
* @param clazz Class to parse.
* @return field list
*/
public static List<Field> getNonStaticFields(final Class<?> clazz) {
List<Field> result = new ArrayList<>();
Class<?> target = clazz;
while (target != null) {
if (JaketConfigurationUtils.isExcludedType(target)) {
break;
}
Field[] fields = target.getDeclaredFields();
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
continue;
}
result.add(field);
}
target = target.getSuperclass();
}
return result;
}
/**
* Get all public, non-static methods of the Class passed in.
* <p>
*
* @param clazz Class to parse.
* @return methods list
*/
public static List<Method> getPublicNonStaticMethods(final Class<?> clazz) {
List<Method> result = new ArrayList<Method>();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
int mod = method.getModifiers();
if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
result.add(method);
}
}
return result;
}
public static String getCanonicalNameForParameterizedType(ParameterizedType parameterizedType) {
StringBuilder sb = new StringBuilder();
Type ownerType = parameterizedType.getOwnerType();
Class<?> rawType = (Class) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
if (ownerType != null) {
if (ownerType instanceof Class) {
sb.append(((Class) ownerType).getName());
} else {
sb.append(ownerType);
}
sb.append('.');
if (ownerType instanceof ParameterizedType) {
// Find simple name of nested type by removing the
// shared prefix with owner.
sb.append(rawType.getName()
.replace(((Class) ((ParameterizedType) ownerType).getRawType()).getName() + "$", ""));
} else {
sb.append(rawType.getSimpleName());
}
} else {
sb.append(rawType.getCanonicalName());
}
if (actualTypeArguments != null && actualTypeArguments.length > 0) {
sb.append('<');
boolean first = true;
for (Type t : actualTypeArguments) {
if (!first) {
sb.append(", ");
}
if (t instanceof Class) {
Class c = (Class) t;
sb.append(c.getCanonicalName());
} else if (t instanceof ParameterizedType) {
sb.append(getCanonicalNameForParameterizedType((ParameterizedType) t));
} else {
sb.append(t.toString());
}
first = false;
}
sb.append('>');
}
return sb.toString();
}
private ClassUtils() {}
}
| 7,084 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.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.metadata.definition.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.apache.dubbo.metadata.definition.model.TypeDefinition.formatType;
import static org.apache.dubbo.metadata.definition.model.TypeDefinition.formatTypes;
/**
* 2015/1/27.
*/
public class MethodDefinition implements Serializable {
private String name;
private String[] parameterTypes;
private String returnType;
/**
* @deprecated please use parameterTypes,
* and find TypeDefinition in org.apache.dubbo.metadata.definition.model.ServiceDefinition#types
*/
@Deprecated
private List<TypeDefinition> parameters;
private List<String> annotations;
public String getName() {
return name;
}
public List<TypeDefinition> getParameters() {
if (parameters == null) {
parameters = new ArrayList<>();
}
return parameters;
}
public String[] getParameterTypes() {
return parameterTypes;
}
public String getReturnType() {
return returnType;
}
public void setName(String name) {
this.name = name;
}
public void setParameters(List<TypeDefinition> parameters) {
this.parameters = parameters;
}
public void setParameterTypes(String[] parameterTypes) {
this.parameterTypes = formatTypes(parameterTypes);
}
public void setReturnType(String returnType) {
this.returnType = formatType(returnType);
}
public List<String> getAnnotations() {
if (annotations == null) {
annotations = Collections.emptyList();
}
return annotations;
}
public void setAnnotations(List<String> annotations) {
this.annotations = annotations;
}
@Override
public String toString() {
return "MethodDefinition [name=" + name + ", parameterTypes=" + Arrays.toString(parameterTypes)
+ ", returnType=" + returnType + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof MethodDefinition)) {
return false;
}
MethodDefinition that = (MethodDefinition) o;
return Objects.equals(getName(), that.getName())
&& Arrays.equals(getParameterTypes(), that.getParameterTypes())
&& Objects.equals(getReturnType(), that.getReturnType());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getReturnType(), Arrays.toString(getParameterTypes()));
}
}
| 7,085 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.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.metadata.definition.model;
import java.util.Map;
/**
* 2018/10/25
*/
public class FullServiceDefinition extends ServiceDefinition {
private Map<String, String> parameters;
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
@Override
public String toString() {
return "FullServiceDefinition{" + "parameters=" + parameters + "} " + super.toString();
}
}
| 7,086 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.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.metadata.definition.model;
import org.apache.dubbo.metadata.definition.util.ClassUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* 2015/1/27.
*/
public class ServiceDefinition implements Serializable {
/**
* the canonical name of interface
*
* @see Class#getCanonicalName()
*/
private String canonicalName;
/**
* the location of class file
*
* @see ClassUtils#getCodeSource(Class)
*/
private String codeSource;
private List<MethodDefinition> methods;
/**
* the definitions of type
*/
private List<TypeDefinition> types;
/**
* the definitions of annotations
*/
private List<String> annotations;
public String getCanonicalName() {
return canonicalName;
}
public String getCodeSource() {
return codeSource;
}
public List<MethodDefinition> getMethods() {
if (methods == null) {
methods = new ArrayList<>();
}
return methods;
}
public List<TypeDefinition> getTypes() {
if (types == null) {
types = new ArrayList<>();
}
return types;
}
public String getUniqueId() {
return canonicalName + "@" + codeSource;
}
public void setCanonicalName(String canonicalName) {
this.canonicalName = canonicalName;
}
public void setCodeSource(String codeSource) {
this.codeSource = codeSource;
}
public void setMethods(List<MethodDefinition> methods) {
this.methods = methods;
}
public void setTypes(List<TypeDefinition> types) {
this.types = types;
}
public List<String> getAnnotations() {
if (annotations == null) {
annotations = Collections.emptyList();
}
return annotations;
}
public void setAnnotations(List<String> annotations) {
this.annotations = annotations;
}
@Override
public String toString() {
return "ServiceDefinition [canonicalName=" + canonicalName + ", codeSource=" + codeSource + ", methods="
+ methods + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ServiceDefinition)) {
return false;
}
ServiceDefinition that = (ServiceDefinition) o;
return Objects.equals(getCanonicalName(), that.getCanonicalName())
&& Objects.equals(getCodeSource(), that.getCodeSource())
&& Objects.equals(getMethods(), that.getMethods())
&& Objects.equals(getTypes(), that.getTypes());
}
@Override
public int hashCode() {
return Objects.hash(getCanonicalName(), getCodeSource(), getMethods(), getTypes());
}
}
| 7,087 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.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.metadata.definition.model;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.apache.dubbo.common.utils.StringUtils.replace;
/**
* 2015/1/27.
*/
public class TypeDefinition implements Serializable {
/**
* the name of type
*
* @see Class#getCanonicalName()
* @see org.apache.dubbo.metadata.definition.util.ClassUtils#getCanonicalNameForParameterizedType(ParameterizedType)
*/
private String type;
/**
* the items(generic parameter) of Map/List(ParameterizedType)
* <p>
* if this type is not ParameterizedType, the items is null or empty
*/
private List<String> items;
/**
* the enum's value
* <p>
* If this type is not enum, enums is null or empty
*/
private List<String> enums;
/**
* the key is property name,
* the value is property's type name
*/
private Map<String, String> properties;
public TypeDefinition() {}
public TypeDefinition(String type) {
this.setType(type);
}
/**
* Format the {@link String} array presenting Java types
*
* @param types the strings presenting Java types
* @return new String array of Java types after be formatted
* @since 2.7.9
*/
public static String[] formatTypes(String[] types) {
String[] newTypes = new String[types.length];
for (int i = 0; i < types.length; i++) {
newTypes[i] = formatType(types[i]);
}
return newTypes;
}
/**
* Format the {@link String} presenting Java type
*
* @param type the String presenting type
* @return new String presenting Java type after be formatted
* @since 2.7.9
*/
public static String formatType(String type) {
if (isGenericType(type)) {
return formatGenericType(type);
}
return type;
}
/**
* Replacing <code>", "</code> to <code>","</code> will not change the semantic of
* {@link ParameterizedType#toString()}
*
* @param type
* @return formatted type
* @see sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
*/
private static String formatGenericType(String type) {
return replace(type, ", ", ",");
}
private static boolean isGenericType(String type) {
return type.contains("<") && type.contains(">");
}
public List<String> getEnums() {
if (enums == null) {
enums = new ArrayList<>();
}
return enums;
}
public List<String> getItems() {
if (items == null) {
items = new ArrayList<>();
}
return items;
}
public Map<String, String> getProperties() {
if (properties == null) {
properties = new HashMap<>();
}
return properties;
}
public String getType() {
return type;
}
public void setEnums(List<String> enums) {
this.enums = enums;
}
public void setItems(List<String> items) {
this.items = items;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public void setType(String type) {
this.type = formatType(type);
}
@Override
public String toString() {
return "TypeDefinition [type=" + type + ", properties=" + properties + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TypeDefinition)) {
return false;
}
TypeDefinition that = (TypeDefinition) o;
return Objects.equals(getType(), that.getType())
&& Objects.equals(getItems(), that.getItems())
&& Objects.equals(getEnums(), that.getEnums())
&& Objects.equals(getProperties(), that.getProperties());
}
@Override
public int hashCode() {
return Objects.hash(getType(), getItems(), getEnums(), getProperties());
}
}
| 7,088 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.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.metadata.definition.builder;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.definition.util.ClassUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import static org.apache.dubbo.common.utils.TypeUtils.getRawClass;
import static org.apache.dubbo.common.utils.TypeUtils.isClass;
import static org.apache.dubbo.common.utils.TypeUtils.isParameterizedType;
/**
* 2015/1/27.
*/
public class MapTypeBuilder implements TypeBuilder {
@Override
public boolean accept(Class<?> clazz) {
if (clazz == null) {
return false;
}
return Map.class.isAssignableFrom(clazz);
}
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
if (!(type instanceof ParameterizedType)) {
return new TypeDefinition(clazz.getCanonicalName());
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] actualTypeArgs = parameterizedType.getActualTypeArguments();
int actualTypeArgsLength = actualTypeArgs == null ? 0 : actualTypeArgs.length;
String mapType = ClassUtils.getCanonicalNameForParameterizedType(parameterizedType);
TypeDefinition td = typeCache.get(mapType);
if (td != null) {
return td;
}
td = new TypeDefinition(mapType);
typeCache.put(mapType, td);
for (int i = 0; i < actualTypeArgsLength; i++) {
Type actualType = actualTypeArgs[i];
TypeDefinition item = null;
Class<?> rawType = getRawClass(actualType);
if (isParameterizedType(actualType)) {
// Nested collection or map.
item = TypeDefinitionBuilder.build(actualType, rawType, typeCache);
} else if (isClass(actualType)) {
item = TypeDefinitionBuilder.build(null, rawType, typeCache);
}
if (item != null) {
td.getItems().add(item.getType());
}
}
return td;
}
}
| 7,089 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.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.metadata.definition.builder;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import java.lang.reflect.Type;
import java.util.Map;
/**
* 2015/1/27.
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface TypeBuilder extends Prioritized {
/**
* Whether the build accept the class passed in.
*/
boolean accept(Class<?> clazz);
/**
* Build type definition with the type or class.
*/
TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache);
}
| 7,090 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.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.metadata.definition.builder;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import java.lang.reflect.Type;
import java.util.Map;
/**
* 2015/1/27.
*/
public class ArrayTypeBuilder implements TypeBuilder {
@Override
public boolean accept(Class<?> clazz) {
if (clazz == null) {
return false;
}
return clazz.isArray();
}
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
final String canonicalName = clazz.getCanonicalName();
TypeDefinition td = typeCache.get(canonicalName);
if (td != null) {
return td;
}
td = new TypeDefinition(canonicalName);
typeCache.put(canonicalName, td);
// Process the component type of array.
Class<?> componentType = clazz.getComponentType();
TypeDefinition itemTd = TypeDefinitionBuilder.build(componentType, componentType, typeCache);
if (itemTd != null) {
td.getItems().add(itemTd.getType());
}
return td;
}
}
| 7,091 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.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.metadata.definition.builder;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
/**
* 2015/1/27.
*/
public class EnumTypeBuilder implements TypeBuilder {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(TypeDefinitionBuilder.class);
@Override
public boolean accept(Class<?> clazz) {
if (clazz == null) {
return false;
}
return clazz.isEnum();
}
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
String canonicalName = clazz.getCanonicalName();
TypeDefinition td = typeCache.get(canonicalName);
if (td != null) {
return td;
}
td = new TypeDefinition(canonicalName);
typeCache.put(canonicalName, td);
try {
Method methodValues = clazz.getDeclaredMethod("values");
methodValues.setAccessible(true);
Object[] values = (Object[]) methodValues.invoke(clazz, new Object[0]);
int length = values.length;
for (int i = 0; i < length; i++) {
Object value = values[i];
td.getEnums().add(value.toString());
}
return td;
} catch (Throwable t) {
logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "There is an error while process class " + clazz, t);
}
return td;
}
}
| 7,092 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.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.metadata.definition.builder;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.definition.util.ClassUtils;
import org.apache.dubbo.metadata.definition.util.JaketConfigurationUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
/**
* 2015/1/27.
*/
public final class DefaultTypeBuilder {
public static TypeDefinition build(Class<?> clazz, Map<String, TypeDefinition> typeCache) {
final String canonicalName = clazz.getCanonicalName();
// Try to get a cached definition
TypeDefinition td = typeCache.get(canonicalName);
if (td != null) {
return td;
}
td = new TypeDefinition(canonicalName);
typeCache.put(canonicalName, td);
// Primitive type
if (!JaketConfigurationUtils.needAnalyzing(clazz)) {
return td;
}
// Custom type
List<Field> fields = ClassUtils.getNonStaticFields(clazz);
for (Field field : fields) {
String fieldName = field.getName();
Class<?> fieldClass = field.getType();
Type fieldType = field.getGenericType();
TypeDefinition fieldTd = TypeDefinitionBuilder.build(fieldType, fieldClass, typeCache);
td.getProperties().put(fieldName, fieldTd.getType());
}
return td;
}
private DefaultTypeBuilder() {}
}
| 7,093 |
0 | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition | Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.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.metadata.definition.builder;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.definition.util.ClassUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
/**
* 2015/1/27.
*/
public class CollectionTypeBuilder implements TypeBuilder {
@Override
public boolean accept(Class<?> clazz) {
if (clazz == null) {
return false;
}
return Collection.class.isAssignableFrom(clazz);
}
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
if (!(type instanceof ParameterizedType)) {
return new TypeDefinition(clazz.getCanonicalName());
}
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] actualTypeArgs = parameterizedType.getActualTypeArguments();
if (actualTypeArgs == null || actualTypeArgs.length != 1) {
throw new IllegalArgumentException(MessageFormat.format(
"[ServiceDefinitionBuilder] Collection type [{0}] with unexpected amount of arguments [{1}]."
+ Arrays.toString(actualTypeArgs),
type,
actualTypeArgs));
}
String colType = ClassUtils.getCanonicalNameForParameterizedType(parameterizedType);
TypeDefinition td = typeCache.get(colType);
if (td != null) {
return td;
}
td = new TypeDefinition(colType);
typeCache.put(colType, td);
Type actualType = actualTypeArgs[0];
TypeDefinition itemTd = null;
if (actualType instanceof ParameterizedType) {
// Nested collection or map.
Class<?> rawType = (Class<?>) ((ParameterizedType) actualType).getRawType();
itemTd = TypeDefinitionBuilder.build(actualType, rawType, typeCache);
} else if (actualType instanceof Class<?>) {
Class<?> actualClass = (Class<?>) actualType;
itemTd = TypeDefinitionBuilder.build(null, actualClass, typeCache);
}
if (itemTd != null) {
td.getItems().add(itemTd.getType());
}
return td;
}
}
| 7,094 |
0 | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.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.metadata.tools;
import org.apache.dubbo.metadata.rest.RestService;
import org.apache.dubbo.metadata.rest.SpringRestService;
import org.apache.dubbo.metadata.rest.User;
import java.io.IOException;
import org.junit.jupiter.api.Test;
/**
* {@link SpringRestService} Test
*
* @since 2.7.6
*/
class SpringRestServiceTest {
@Test
void test() throws IOException {
Compiler compiler = new Compiler();
compiler.compile(User.class, RestService.class, SpringRestService.class);
}
}
| 7,095 |
0 | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.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.metadata.tools;
import org.apache.dubbo.metadata.rest.RestService;
import org.apache.dubbo.metadata.rest.StandardRestService;
import org.apache.dubbo.metadata.rest.User;
import java.io.IOException;
import org.junit.jupiter.api.Test;
/**
* The test case for {@link StandardRestService}
*
* @since 2.7.6
*/
class StandardRestServiceTest {
@Test
void test() throws IOException {
Compiler compiler = new Compiler();
compiler.compile(User.class, RestService.class, StandardRestService.class);
}
}
| 7,096 |
0 | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.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.metadata.tools;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import java.util.Set;
import static javax.lang.model.SourceVersion.latestSupported;
/**
* {@link Processor} for test
*
* @since 2.7.6
*/
@SupportedAnnotationTypes("*")
public class TestProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return false;
}
public ProcessingEnvironment getProcessingEnvironment() {
return super.processingEnv;
}
public SourceVersion getSupportedSourceVersion() {
return latestSupported();
}
}
| 7,097 |
0 | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.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.metadata.tools;
import org.apache.dubbo.config.annotation.Service;
import java.io.Serializable;
/**
* {@link TestService} Implementation
*
* @since 2.7.6
*/
@Service(
interfaceName = "org.apache.dubbo.metadata.tools.TestService",
interfaceClass = TestService.class,
version = "3.0.0",
group = "test")
public class TestServiceImpl extends GenericTestService implements TestService, AutoCloseable, Serializable {
@Override
public String echo(String message) {
return "[ECHO] " + message;
}
@Override
public void close() throws Exception {}
}
| 7,098 |
0 | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata | Create_ds/dubbo/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.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.metadata.tools;
import org.apache.dubbo.metadata.rest.DefaultRestService;
import org.apache.dubbo.metadata.rest.RestService;
import org.apache.dubbo.metadata.rest.SpringRestService;
import org.apache.dubbo.metadata.rest.StandardRestService;
import org.apache.dubbo.metadata.rest.User;
import java.io.IOException;
import org.junit.jupiter.api.Test;
/**
* The test case for {@link DefaultRestService}
*
* @since 2.7.6
*/
class DefaultRestServiceTest {
@Test
void test() throws IOException {
Compiler compiler = new Compiler();
compiler.compile(
User.class,
RestService.class,
DefaultRestService.class,
SpringRestService.class,
StandardRestService.class);
}
}
| 7,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.