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-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaProcessExecutor.java | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Ease the execution of a Java process using Maven's toolchain support.
*
* @author Stephane Nicoll
*/
class JavaProcessExecutor {
private static final int EXIT_CODE_SIGINT = 130;
private final MavenSession mavenSession;
private final ToolchainManager toolchainManager;
private final Consumer<RunProcess> runProcessCustomizer;
JavaProcessExecutor(MavenSession mavenSession, ToolchainManager toolchainManager) {
this(mavenSession, toolchainManager, null);
}
private JavaProcessExecutor(MavenSession mavenSession, ToolchainManager toolchainManager,
Consumer<RunProcess> runProcessCustomizer) {
this.mavenSession = mavenSession;
this.toolchainManager = toolchainManager;
this.runProcessCustomizer = runProcessCustomizer;
}
JavaProcessExecutor withRunProcessCustomizer(Consumer<RunProcess> customizer) {
Consumer<RunProcess> combinedCustomizer = (this.runProcessCustomizer != null)
? this.runProcessCustomizer.andThen(customizer) : customizer;
return new JavaProcessExecutor(this.mavenSession, this.toolchainManager, combinedCustomizer);
}
int run(File workingDirectory, List<String> args, Map<String, String> environmentVariables)
throws MojoExecutionException {
RunProcess runProcess = new RunProcess(workingDirectory, getJavaExecutable());
if (this.runProcessCustomizer != null) {
this.runProcessCustomizer.accept(runProcess);
}
try {
int exitCode = runProcess.run(true, args, environmentVariables);
if (!hasTerminatedSuccessfully(exitCode)) {
throw new MojoExecutionException("Process terminated with exit code: " + exitCode);
}
return exitCode;
}
catch (IOException ex) {
throw new MojoExecutionException("Process execution failed", ex);
}
}
RunProcess runAsync(File workingDirectory, List<String> args, Map<String, String> environmentVariables)
throws MojoExecutionException {
try {
RunProcess runProcess = new RunProcess(workingDirectory, getJavaExecutable());
runProcess.run(false, args, environmentVariables);
return runProcess;
}
catch (IOException ex) {
throw new MojoExecutionException("Process execution failed", ex);
}
}
private boolean hasTerminatedSuccessfully(int exitCode) {
return (exitCode == 0 || exitCode == EXIT_CODE_SIGINT);
}
private String getJavaExecutable() {
Toolchain toolchain = this.toolchainManager.getToolchainFromBuildContext("jdk", this.mavenSession);
String javaExecutable = (toolchain != null) ? toolchain.findTool("java") : null;
return (javaExecutable != null) ? javaExecutable : new JavaExecutable().toString();
}
}
| 5,600 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/Include.java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
/**
* A model for a dependency to include.
*
* @author David Turanski
*/
public class Include extends FilterableDependency {
}
| 5,601 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Helper class to build the command-line arguments of a java process.
*
* @author Stephane Nicoll
*/
final class CommandLineBuilder {
private final List<String> options = new ArrayList<>();
private final List<URL> classpathElements = new ArrayList<>();
private final String mainClass;
private final List<String> arguments = new ArrayList<>();
private CommandLineBuilder(String mainClass) {
this.mainClass = mainClass;
}
static CommandLineBuilder forMainClass(String mainClass) {
return new CommandLineBuilder(mainClass);
}
CommandLineBuilder withJvmArguments(String... jvmArguments) {
if (jvmArguments != null) {
this.options.addAll(Arrays.stream(jvmArguments).filter(Objects::nonNull).collect(Collectors.toList()));
}
return this;
}
CommandLineBuilder withSystemProperties(Map<String, String> systemProperties) {
if (systemProperties != null) {
systemProperties.entrySet().stream().map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue()))
.forEach(this.options::add);
}
return this;
}
CommandLineBuilder withClasspath(URL... elements) {
this.classpathElements.addAll(Arrays.asList(elements));
return this;
}
CommandLineBuilder withArguments(String... arguments) {
if (arguments != null) {
this.arguments.addAll(Arrays.stream(arguments).filter(Objects::nonNull).collect(Collectors.toList()));
}
return this;
}
List<String> build() {
List<String> commandLine = new ArrayList<>();
if (!this.options.isEmpty()) {
commandLine.addAll(this.options);
}
if (!this.classpathElements.isEmpty()) {
commandLine.add("-cp");
commandLine.add(ClasspathBuilder.build(this.classpathElements));
}
commandLine.add(this.mainClass);
if (!this.arguments.isEmpty()) {
commandLine.addAll(this.arguments);
}
return commandLine;
}
static class ClasspathBuilder {
static String build(List<URL> classpathElements) {
StringBuilder classpath = new StringBuilder();
for (URL element : classpathElements) {
if (classpath.length() > 0) {
classpath.append(File.pathSeparator);
}
classpath.append(toFile(element));
}
return classpath.toString();
}
private static File toFile(URL element) {
try {
return new File(element.toURI());
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
}
}
/**
* Format System properties.
*/
private static class SystemPropertyFormatter {
static String format(String key, String value) {
if (key == null) {
return "";
}
if (value == null || value.isEmpty()) {
return String.format("-D%s", key);
}
return String.format("-D%s=\"%s\"", key, value);
}
}
}
| 5,602 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/IncludeFilter.java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter;
import java.util.List;
/**
* An {@link ArtifactsFilter} that filters out any artifact not matching an
* {@link Include}.
*
* @author David Turanski
*/
public class IncludeFilter extends DependencyFilter {
public IncludeFilter(List<Include> includes) {
super(includes);
}
@Override
protected boolean filter(Artifact artifact) {
for (FilterableDependency dependency : getFilters()) {
if (equals(artifact, dependency)) {
return false;
}
}
return true;
}
}
| 5,603 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaCompilerPluginConfiguration.java | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.util.Arrays;
/**
* Provides access to the Maven Java Compiler plugin configuration.
*
* @author Scott Frederick
*/
class JavaCompilerPluginConfiguration {
private final MavenProject project;
JavaCompilerPluginConfiguration(MavenProject project) {
this.project = project;
}
String getSourceMajorVersion() {
String version = getConfigurationValue("source");
if (version == null) {
version = getPropertyValue("maven.compiler.source");
}
return majorVersionFor(version);
}
String getTargetMajorVersion() {
String version = getConfigurationValue("target");
if (version == null) {
version = getPropertyValue("maven.compiler.target");
}
return majorVersionFor(version);
}
String getReleaseVersion() {
String version = getConfigurationValue("release");
if (version == null) {
version = getPropertyValue("maven.compiler.release");
}
return majorVersionFor(version);
}
private String getConfigurationValue(String propertyName) {
Plugin plugin = this.project.getPlugin("org.apache.maven.plugins:maven-compiler-plugin");
if (plugin != null) {
Object pluginConfiguration = plugin.getConfiguration();
if (pluginConfiguration instanceof Xpp3Dom) {
return getNodeValue((Xpp3Dom)pluginConfiguration, propertyName);
}
}
return null;
}
private String getPropertyValue(String propertyName) {
if (this.project.getProperties().containsKey(propertyName)) {
return this.project.getProperties().get(propertyName).toString();
}
return null;
}
private String getNodeValue(Xpp3Dom dom, String... childNames) {
Xpp3Dom childNode = dom.getChild(childNames[0]);
if (childNode == null) {
return null;
}
if (childNames.length > 1) {
return getNodeValue(childNode, Arrays.copyOfRange(childNames, 1, childNames.length));
}
return childNode.getValue();
}
private String majorVersionFor(String version) {
if (version != null && version.startsWith("1.")) {
return version.substring("1.".length());
}
return version;
}
}
| 5,604 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
@Mojo(
name = "dubbo-process-aot",
defaultPhase = LifecyclePhase.PREPARE_PACKAGE,
threadSafe = true,
requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class DubboProcessAotMojo extends AbstractAotMojo {
private static final String AOT_PROCESSOR_CLASS_NAME = "org.apache.dubbo.aot.generate.AotProcessor";
/**
* Directory containing the classes and resource files that should be packaged into
* the archive.
*/
@Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
private File classesDirectory;
/**
* Directory containing the generated sources.
*/
@Parameter(defaultValue = "${project.build.directory}/dubbo-aot/main/sources", required = true)
private File generatedSources;
/**
* Directory containing the generated resources.
*/
@Parameter(defaultValue = "${project.build.directory}/dubbo-aot/main/resources", required = true)
private File generatedResources;
/**
* Directory containing the generated classes.
*/
@Parameter(defaultValue = "${project.build.directory}/dubbo-aot/main/classes", required = true)
private File generatedClasses;
/**
* Name of the main class to use as the source for the AOT process. If not specified
* the first compiled class found that contains a 'main' method will be used.
*/
@Parameter(property = "dubbo.aot.main-class")
private String mainClass;
/**
* Application arguments that should be taken into account for AOT processing.
*/
@Parameter
private String[] arguments;
@Override
protected void executeAot() throws Exception {
URL[] classPath = getClassPath().toArray(new URL[0]);
generateAotAssets(classPath, AOT_PROCESSOR_CLASS_NAME, getAotArguments(mainClass));
compileSourceFiles(classPath, this.generatedSources, this.classesDirectory);
copyAll(this.generatedResources.toPath(), this.classesDirectory.toPath());
copyAll(this.generatedClasses.toPath(), this.classesDirectory.toPath());
}
private String[] getAotArguments(String applicationClass) {
List<String> aotArguments = new ArrayList<>();
aotArguments.add(applicationClass);
aotArguments.add(this.generatedSources.toString());
aotArguments.add(this.generatedResources.toString());
aotArguments.add(this.generatedClasses.toString());
aotArguments.add(this.project.getGroupId());
aotArguments.add(this.project.getArtifactId());
aotArguments.addAll(new RunArguments(this.arguments).getArgs());
return aotArguments.toArray(new String[0]);
}
private List<URL> getClassPath() throws Exception {
File[] directories = new File[] {this.classesDirectory, this.generatedClasses};
return getClassPath(directories, new ExcludeTestScopeArtifactFilter());
}
}
| 5,605 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/ExcludeFilter.java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.artifact.Artifact;
import java.util.Arrays;
import java.util.List;
/**
* An {DependencyFilter} that filters out any artifact matching an {@link Exclude}.
*
* @author Stephane Nicoll
* @author David Turanski
*/
public class ExcludeFilter extends DependencyFilter {
public ExcludeFilter(Exclude... excludes) {
this(Arrays.asList(excludes));
}
public ExcludeFilter(List<Exclude> excludes) {
super(excludes);
}
@Override
protected boolean filter(Artifact artifact) {
for (FilterableDependency dependency : getFilters()) {
if (equals(artifact, dependency)) {
return true;
}
}
return false;
}
}
| 5,606 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/RunArguments.java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Objects;
/**
* Parse and expose arguments specified in a single string.
*
* @author Stephane Nicoll
*/
class RunArguments {
private static final String[] NO_ARGS = {};
private final Deque<String> args = new LinkedList<>();
RunArguments(String arguments) {
this(parseArgs(arguments));
}
RunArguments(String[] args) {
if (args != null) {
Arrays.stream(args).filter(Objects::nonNull).forEach(this.args::add);
}
}
Deque<String> getArgs() {
return this.args;
}
String[] asArray() {
return this.args.toArray(new String[0]);
}
private static String[] parseArgs(String arguments) {
if (arguments == null || arguments.trim().isEmpty()) {
return NO_ARGS;
}
try {
arguments = arguments.replace('\n', ' ').replace('\t', ' ');
return CommandLineUtils.translateCommandline(arguments);
}
catch (Exception ex) {
throw new IllegalArgumentException("Failed to parse arguments [" + arguments + "]", ex);
}
}
}
| 5,607 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/MatchingGroupIdFilter.java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactFeatureFilter;
/**
* An {@link org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter
* ArtifactsFilter} that filters by matching groupId.
*
* Preferred over the
* {@link org.apache.maven.shared.artifact.filter.collection.GroupIdFilter} due to that
* classes use of {@link String#startsWith} to match on prefix.
*
* @author Mark Ingram
*/
public class MatchingGroupIdFilter extends AbstractArtifactFeatureFilter {
/**
* Create a new instance with the CSV groupId values that should be excluded.
* @param exclude the group values to exclude
*/
public MatchingGroupIdFilter(String exclude) {
super("", exclude);
}
@Override
protected String getArtifactFeature(Artifact artifact) {
return artifact.getGroupId();
}
}
| 5,608 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaExecutable.java | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin.aot;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
/**
* Provides access to the java binary executable, regardless of OS.
*
* @author Phillip Webb
*/
public class JavaExecutable {
private final File file;
public JavaExecutable() {
String javaHome = System.getProperty("java.home");
Assert.assertTrue(StringUtils.isNotEmpty(javaHome), "Unable to find java executable due to missing 'java.home'");
this.file = findInJavaHome(javaHome);
}
private File findInJavaHome(String javaHome) {
File bin = new File(new File(javaHome), "bin");
File command = new File(bin, "java.exe");
command = command.exists() ? command : new File(bin, "java");
Assert.assertTrue(command.exists(), () -> "Unable to find java in " + javaHome);
return command;
}
/**
* Create a new {@link ProcessBuilder} that will run with the Java executable.
* @param arguments the command arguments
* @return a {@link ProcessBuilder}
*/
public ProcessBuilder processBuilder(String... arguments) {
ProcessBuilder processBuilder = new ProcessBuilder(toString());
processBuilder.command().addAll(Arrays.asList(arguments));
return processBuilder;
}
@Override
public String toString() {
try {
return this.file.getCanonicalPath();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
| 5,609 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.demo.DemoService;
import org.apache.dubbo.demo.consumer.comp.DemoServiceComponent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
public class Application {
/**
* In order to make sure multicast registry works, need to specify '-Djava.net.preferIPv4Stack=true' before
* launch the application
*/
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
context.start();
DemoService service = context.getBean("demoServiceComponent", DemoServiceComponent.class);
String hello = service.sayHello("world");
System.out.println("result :" + hello);
}
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.demo.consumer.comp")
@PropertySource("classpath:/spring/dubbo-consumer.properties")
@ComponentScan(value = {"org.apache.dubbo.demo.consumer.comp"})
static class ConsumerConfiguration {}
}
| 5,610 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/comp/DemoServiceComponent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer.comp;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.demo.DemoService;
import java.util.concurrent.CompletableFuture;
import org.springframework.stereotype.Component;
@Component("demoServiceComponent")
public class DemoServiceComponent implements DemoService {
@DubboReference
private DemoService demoService;
@Override
public String sayHello(String name) {
return demoService.sayHello(name);
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
return null;
}
}
| 5,611 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
public class Application {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ProviderConfiguration.class);
context.start();
System.in.read();
}
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.demo.provider")
@PropertySource("classpath:/spring/dubbo-provider.properties")
static class ProviderConfiguration {
@Bean
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("zookeeper://127.0.0.1:2181");
return registryConfig;
}
}
}
| 5,612 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.demo.DemoService;
import org.apache.dubbo.rpc.RpcContext;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@DubboService
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
@Override
public String sayHello(String name) {
logger.info("Hello " + name + ", request from consumer: "
+ RpcContext.getServiceContext().getRemoteAddress());
return "Hello " + name + ", response from provider: "
+ RpcContext.getServiceContext().getLocalAddress();
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
return null;
}
}
| 5,613 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-provider.xml");
context.start();
System.in.read();
}
}
| 5,614 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/TripleServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.demo.TripleService;
public class TripleServiceImpl implements TripleService {
@Override
public String hello() {
return "Triple!";
}
}
| 5,615 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/RestDemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.demo.RestDemoService;
import org.apache.dubbo.rpc.RpcContext;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Map;
import po.TestPO;
public class RestDemoServiceImpl implements RestDemoService {
private static Map<String, Object> context;
private boolean called;
public String sayHello(String name) {
called = true;
return "Hello, " + name;
}
public boolean isCalled() {
return called;
}
@Override
public Integer hello(Integer a, Integer b) {
context = RpcContext.getServerAttachment().getObjectAttachments();
return a + b;
}
@Override
public String error() {
throw new RuntimeException();
}
public static Map<String, Object> getAttachments() {
return context;
}
@Override
public String getRemoteApplicationName() {
return RpcContext.getServiceContext().getRemoteApplicationName();
}
@Override
public Integer testBody(Integer b) {
return b;
}
@Override
public String testBody2(String b) {
return b;
}
@Override
public Boolean testBody2(Boolean b) {
return b;
}
@Override
public TestPO testBody2(TestPO b) {
return b;
}
@Override
public TestPO testBody5(TestPO testPO) {
return testPO;
}
public String testForm1(String test) {
return test;
}
public MultivaluedMap testForm2(MultivaluedMap map) {
return map;
}
}
| 5,616 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.demo.DemoService;
import org.apache.dubbo.rpc.RpcContext;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
@Override
public String sayHello(String name) {
logger.info("Hello " + name + ", request from consumer: "
+ RpcContext.getServiceContext().getRemoteAddress());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello " + name + ", response from provider: "
+ RpcContext.getServiceContext().getLocalAddress();
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
return "async result";
});
return cf;
}
}
| 5,617 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/GreetingServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.demo.GreetingService;
/**
*
*/
public class GreetingServiceImpl implements GreetingService {
@Override
public String hello() {
return "Greetings!";
}
}
| 5,618 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class RestProvider {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring/rest-provider.xml"});
context.refresh();
// SpringControllerService springControllerService = context.getBean(SpringControllerService.class);
// ServiceConfig<SpringControllerService> serviceConfig = new ServiceConfig<>();
// serviceConfig.setInterface(SpringControllerService.class);
// serviceConfig.setProtocol(new ProtocolConfig("rest", 8888));
// serviceConfig.setRef(springControllerService);
// serviceConfig.export();
System.out.println("dubbo service started");
System.in.read();
}
}
| 5,619 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.demo.rest.api.CurlService;
@DubboService(interfaceClass = CurlService.class, protocol = "rest")
public class CurlServiceImpl implements CurlService {
@Override
public String curl() {
return "hello,dubbo rest curl request";
}
}
| 5,620 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.demo.rest.api.JaxRsRestDemoService;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import po.User;
@Service("jaxRsRestDemoService")
public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
@Override
public Long testFormBody(Long number) {
return number;
}
@Override
public User testJavaBeanBody(User user) {
return user;
}
@Override
public int primitiveInt(int a, int b) {
return a + b;
}
@Override
public long primitiveLong(long a, Long b) {
return a + b;
}
@Override
public long primitiveByte(byte a, Long b) {
return a + b;
}
@Override
public long primitiveShort(short a, Long b, int c) {
return a + b;
}
@Override
public String testMapParam(Map<String, String> params) {
return params.get("param");
}
@Override
public String testMapHeader(Map<String, String> headers) {
return headers.get("header");
}
@Override
public List<String> testMapForm(MultivaluedMap<String, String> params) {
return params.get("form");
}
@Override
public String header(String header) {
return header;
}
@Override
public int headerInt(int header) {
return header;
}
@Override
public Integer hello(Integer a, Integer b) {
return a + b;
}
@Override
public String error() {
throw new RuntimeException("test error");
}
}
| 5,621 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.demo.rest.api.ExceptionMapperService;
import org.springframework.stereotype.Service;
@Service("exceptionMapperService")
public class ExceptionMapperServiceImpl implements ExceptionMapperService {
@Override
public String exception(String message) {
throw new RuntimeException(message);
}
}
| 5,622 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.demo.rest.api.HttpRequestAndResponseRPCContextService;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse;
import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
@Service("httpRequestAndResponseRPCContextService")
public class HttpRequestAndResponseRPCContextServiceImpl implements HttpRequestAndResponseRPCContextService {
@Override
public String httpRequestParam(String hello) {
Object request = RpcContext.getServerAttachment().getRequest();
return ((RequestFacade) request).getParameter("name");
}
@Override
public String httpRequestHeader(String hello) {
Object request = RpcContext.getServerAttachment().getRequest();
return ((RequestFacade) request).getHeader("header");
}
@Override
public List<String> httpResponseHeader(String hello) {
Object response = RpcContext.getServerAttachment().getResponse();
Map<String, List<String>> outputHeaders = ((NettyHttpResponse) response).getOutputHeaders();
String responseKey = "response";
outputHeaders.put(responseKey, Arrays.asList(hello));
return outputHeaders.get(responseKey);
}
}
| 5,623 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.demo.rest.api.HttpMethodService;
import org.springframework.stereotype.Service;
@Service("httpMethodService")
public class HttpMethodServiceImpl implements HttpMethodService {
@Override
public String sayHelloPost(String hello) {
return hello;
}
@Override
public String sayHelloDelete(String hello) {
return hello;
}
@Override
public String sayHelloHead(String hello) {
return hello;
}
@Override
public String sayHelloGet(String hello) {
return hello;
}
@Override
public String sayHelloPut(String hello) {
return hello;
}
@Override
public String sayHelloPatch(String hello) {
return hello;
}
@Override
public String sayHelloOptions(String hello) {
return hello;
}
}
| 5,624 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/DubboServiceAnnotationServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.demo.rest.api.DubboServiceAnnotationService;
@DubboService(protocol = "rest")
public class DubboServiceAnnotationServiceImpl implements DubboServiceAnnotationService {
@Override
public String annotation() {
return "Dubbo Service Annotation service demo!";
}
}
| 5,625 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.extension;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler;
public class ExceptionMapperForTest implements ExceptionHandler<RuntimeException> {
@Override
public Object result(RuntimeException exception) {
return exception.getMessage();
}
}
| 5,626 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.config;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
@DubboComponentScan("org.apache.dubbo.demo.rest")
public class DubboConfig {}
| 5,627 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import java.util.Arrays;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import po.User;
public class SpringMvcRestConsumer {
public static void main(String[] args) {
consumerService();
}
public static void consumerService() {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring/rest-consumer.xml"});
context.start();
System.out.println("spring mvc rest consumer start");
springMvcRestDemoServiceTest(context);
System.out.println("spring mvc rest consumer test success");
}
private static void springMvcRestDemoServiceTest(ClassPathXmlApplicationContext context) {
SpringRestDemoService springRestDemoService =
context.getBean("springRestDemoService", SpringRestDemoService.class);
String hello = springRestDemoService.sayHello("hello");
assertEquals("Hello, hello", hello);
Integer result = springRestDemoService.primitiveInt(1, 2);
Long resultLong = springRestDemoService.primitiveLong(1, 2l);
long resultByte = springRestDemoService.primitiveByte((byte) 1, 2l);
long resultShort = springRestDemoService.primitiveShort((short) 1, 2l, 1);
assertEquals(result, 3);
assertEquals(resultShort, 3l);
assertEquals(resultLong, 3l);
assertEquals(resultByte, 3l);
assertEquals(Long.valueOf(1l), springRestDemoService.testFormBody(1l));
MultiValueMap<String, String> forms = new LinkedMultiValueMap<>();
forms.put("form", Arrays.asList("F1"));
assertEquals(Arrays.asList("F1"), springRestDemoService.testMapForm(forms));
assertEquals(User.getInstance(), springRestDemoService.testJavaBeanBody(User.getInstance()));
}
private static void assertEquals(Object returnStr, Object exception) {
boolean equal = returnStr != null && returnStr.equals(exception);
if (equal) {
return;
} else {
throw new RuntimeException();
}
}
}
| 5,628 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.config;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
@DubboComponentScan("org.apache.dubbo.demo.rest")
public class DubboConfig {}
| 5,629 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/consumer/SpringRestDemoServiceConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.consumer;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.demo.rest.api.SpringRestDemoService;
import org.springframework.stereotype.Component;
@Component
public class SpringRestDemoServiceConsumer {
@DubboReference(interfaceClass = SpringRestDemoService.class)
SpringRestDemoService springRestDemoService;
}
| 5,630 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.demo.DemoService;
import org.apache.dubbo.demo.GreetingService;
import org.apache.dubbo.demo.RestDemoService;
import org.apache.dubbo.demo.TripleService;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import po.TestPO;
public class Application {
/**
* In order to make sure multicast registry works, need to specify '-Djava.net.preferIPv4Stack=true' before
* launch the application
*/
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml");
context.start();
DemoService demoService = context.getBean("demoService", DemoService.class);
GreetingService greetingService = context.getBean("greetingService", GreetingService.class);
RestDemoService restDemoService = context.getBean("restDemoService", RestDemoService.class);
TripleService tripleService = context.getBean("tripleService", TripleService.class);
new Thread(() -> {
while (true) {
try {
String greetings = greetingService.hello();
System.out.println(greetings + " from separated thread.");
} catch (Exception e) {
// e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
})
.start();
new Thread(() -> {
while (true) {
try {
Object restResult = restDemoService.sayHello("rest");
System.out.println(restResult + " from separated thread.");
restResult = restDemoService.testBody5(TestPO.getInstance());
System.out.println(restResult + " from separated thread.");
restResult = restDemoService.hello(1, 2);
System.out.println(restResult + " from separated thread.");
String form1 = restDemoService.testForm1("form1");
System.out.println(form1);
MultivaluedHashMap multivaluedHashMap = new MultivaluedHashMap();
multivaluedHashMap.put("1", Arrays.asList("1"));
multivaluedHashMap.put("2", Arrays.asList("2"));
MultivaluedMap form2 = restDemoService.testForm2(multivaluedHashMap);
System.out.println(form2);
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
})
.start();
while (true) {
try {
CompletableFuture<String> hello = demoService.sayHelloAsync("world");
System.out.println("result: " + hello.get());
String greetings = greetingService.hello();
System.out.println("result: " + greetings);
} catch (Exception e) {
// e.printStackTrace();
}
Thread.sleep(5000);
}
}
}
| 5,631 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringMvcRestProvider {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring/rest-provider.xml"});
context.refresh();
System.out.println("spring mvc rest provider started");
System.in.read();
}
}
| 5,632 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/SpringRestDemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.impl;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.demo.rest.api.SpringRestDemoService;
import java.util.List;
import java.util.Map;
import org.springframework.util.MultiValueMap;
import po.User;
@DubboService(interfaceClass = SpringRestDemoService.class, protocol = "rest")
public class SpringRestDemoServiceImpl implements SpringRestDemoService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
@Override
public Long testFormBody(Long number) {
return number;
}
@Override
public User testJavaBeanBody(User user) {
return user;
}
@Override
public int primitiveInt(int a, int b) {
return a + b;
}
@Override
public long primitiveLong(long a, Long b) {
return a + b;
}
@Override
public long primitiveByte(byte a, Long b) {
return a + b;
}
@Override
public long primitiveShort(short a, Long b, int c) {
return a + b;
}
@Override
public String testMapParam(Map<String, String> params) {
return params.get("param");
}
@Override
public String testMapHeader(Map<String, String> headers) {
return headers.get("header");
}
@Override
public List<String> testMapForm(MultiValueMap<String, String> params) {
return params.get("form");
}
@Override
public int headerInt(int header) {
return header;
}
@Override
public Integer hello(Integer a, Integer b) {
return a + b;
}
@Override
public String error() {
throw new RuntimeException("test error");
}
}
| 5,633 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.config;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
@DubboComponentScan("org.apache.dubbo.demo.rest")
public class DubboConfig {}
| 5,634 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import org.apache.dubbo.demo.rest.api.annotation.DubboServiceAnnotationServiceConsumer;
import java.util.Arrays;
import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import po.User;
public class RestConsumer {
public static void main(String[] args) {
consumerService();
}
public static void consumerService() {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring/rest-consumer.xml"});
context.start();
System.out.println("rest consumer start");
testExceptionMapperService(context);
testHttpMethodService(context);
httpRPCContextTest(context);
jaxRsRestDemoServiceTest(context);
annotationTest(context);
System.out.println("rest consumer test success");
}
private static void annotationTest(ClassPathXmlApplicationContext context) {
DubboServiceAnnotationServiceConsumer bean = context.getBean(DubboServiceAnnotationServiceConsumer.class);
bean.invokeAnnotationService();
}
private static void jaxRsRestDemoServiceTest(ClassPathXmlApplicationContext context) {
JaxRsRestDemoService jaxRsRestDemoService = context.getBean("jaxRsRestDemoService", JaxRsRestDemoService.class);
String hello = jaxRsRestDemoService.sayHello("hello");
assertEquals("Hello, hello", hello);
Integer result = jaxRsRestDemoService.primitiveInt(1, 2);
Long resultLong = jaxRsRestDemoService.primitiveLong(1, 2l);
long resultByte = jaxRsRestDemoService.primitiveByte((byte) 1, 2l);
long resultShort = jaxRsRestDemoService.primitiveShort((short) 1, 2l, 1);
assertEquals(result, 3);
assertEquals(resultShort, 3l);
assertEquals(resultLong, 3l);
assertEquals(resultByte, 3l);
assertEquals(Long.valueOf(1l), jaxRsRestDemoService.testFormBody(1l));
MultivaluedMapImpl<String, String> forms = new MultivaluedMapImpl<>();
forms.put("form", Arrays.asList("F1"));
assertEquals(Arrays.asList("F1"), jaxRsRestDemoService.testMapForm(forms));
assertEquals(User.getInstance(), jaxRsRestDemoService.testJavaBeanBody(User.getInstance()));
}
private static void testExceptionMapperService(ClassPathXmlApplicationContext context) {
String returnStr = "exception";
String paramStr = "exception";
ExceptionMapperService exceptionMapperService =
context.getBean("exceptionMapperService", ExceptionMapperService.class);
assertEquals(returnStr, exceptionMapperService.exception(paramStr));
}
private static void httpRPCContextTest(ClassPathXmlApplicationContext context) {
HttpRequestAndResponseRPCContextService requestAndResponseRPCContextService = context.getBean(
"httpRequestAndResponseRPCContextService", HttpRequestAndResponseRPCContextService.class);
String returnStr = "hello";
String paramStr = "hello";
assertEquals(returnStr, requestAndResponseRPCContextService.httpRequestHeader(paramStr));
assertEquals(returnStr, requestAndResponseRPCContextService.httpRequestParam(paramStr));
assertEquals(
returnStr,
requestAndResponseRPCContextService.httpResponseHeader(paramStr).get(0));
}
private static void testHttpMethodService(ClassPathXmlApplicationContext context) {
HttpMethodService httpMethodService = context.getBean("httpMethodService", HttpMethodService.class);
String returnStr = "hello";
String paramStr = "hello";
// assertEquals(null, httpMethodService.sayHelloHead(paramStr));
assertEquals(returnStr, httpMethodService.sayHelloGet(paramStr));
assertEquals(returnStr, httpMethodService.sayHelloDelete(paramStr));
assertEquals(returnStr, httpMethodService.sayHelloPut(paramStr));
assertEquals(returnStr, httpMethodService.sayHelloOptions(paramStr));
// Assert.assertEquals(returnStr, httpMethodService.sayHelloPatch(paramStr));
assertEquals(returnStr, httpMethodService.sayHelloPost(paramStr));
}
private static void assertEquals(Object returnStr, Object exception) {
boolean equal = returnStr != null && returnStr.equals(exception);
if (equal) {
return;
} else {
throw new RuntimeException();
}
}
}
| 5,635 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.config;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
@DubboComponentScan("org.apache.dubbo.demo.rest")
public class DubboConfig {}
| 5,636 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api | Create_ds/dubbo/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api.annotation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.demo.rest.api.DubboServiceAnnotationService;
import org.springframework.stereotype.Component;
@Component
public class DubboServiceAnnotationServiceConsumer {
@DubboReference(interfaceClass = DubboServiceAnnotationService.class)
DubboServiceAnnotationService dubboServiceAnnotationService;
public void invokeAnnotationService() {
String annotation = dubboServiceAnnotationService.annotation();
System.out.println(annotation);
}
}
| 5,637 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.springboot.demo.provider;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import java.util.concurrent.CountDownLatch;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDubbo(scanBasePackages = {"org.apache.dubbo.springboot.demo.provider"})
public class ProviderApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ProviderApplication.class, args);
System.out.println("dubbo service started");
new CountDownLatch(1).await();
}
}
| 5,638 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.springboot.demo.provider;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.springboot.demo.DemoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@DubboService
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
@Override
public String sayHello(String name) {
logger.info("Hello " + name + ", request from consumer: "
+ RpcContext.getContext().getRemoteAddress());
return "Hello " + name;
}
}
| 5,639 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.springboot.demo;
import java.util.concurrent.CompletableFuture;
public interface DemoService {
String sayHello(String name);
default CompletableFuture<String> sayHelloAsync(String name) {
return CompletableFuture.completedFuture(sayHello(name));
}
}
| 5,640 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.springboot.demo.consumer;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.springboot.demo.DemoService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;
@SpringBootApplication
@Service
@EnableDubbo
public class ConsumerApplication {
@DubboReference
private DemoService demoService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args);
ConsumerApplication application = context.getBean(ConsumerApplication.class);
String result = application.doSayHello("world");
System.out.println("result: " + result);
}
public String doSayHello(String name) {
return demoService.sayHello(name);
}
}
| 5,641 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterWrapperServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
public class GreeterWrapperServiceImpl implements GreeterWrapperService {
@Override
public String sayHello(String request) {
StringBuilder responseBuilder = new StringBuilder(request);
for (int i = 0; i < 20; i++) {
responseBuilder.append(responseBuilder);
}
return responseBuilder.toString();
}
}
| 5,642 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
import org.apache.dubbo.demo.hello.HelloReply;
import org.apache.dubbo.demo.hello.HelloRequest;
import java.util.concurrent.CompletableFuture;
public class GreeterServiceImpl implements GreeterService {
@Override
public HelloReply sayHello(HelloRequest request) {
return HelloReply.newBuilder().setMessage("Hello " + request.getName()).build();
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
return CompletableFuture.supplyAsync(() -> name);
}
}
| 5,643 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterWrapperService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
public interface GreeterWrapperService {
/**
* Sends a greeting
*/
String sayHello(String request);
}
| 5,644 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
import org.apache.dubbo.demo.hello.HelloReply;
import org.apache.dubbo.demo.hello.HelloRequest;
import java.util.concurrent.CompletableFuture;
public interface GreeterService {
/**
* Sends a greeting
*/
HelloReply sayHello(HelloRequest request);
CompletableFuture<String> sayHelloAsync(String request);
}
| 5,645 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.demo.GreeterService;
import org.apache.dubbo.demo.GreeterServiceImpl;
public class ApiProvider {
public static void main(String[] args) throws InterruptedException {
ServiceConfig<GreeterService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(GreeterService.class);
serviceConfig.setRef(new GreeterServiceImpl());
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(new ApplicationConfig("dubbo-demo-triple-api-provider"))
.registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
.protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1))
.service(serviceConfig)
.start()
.await();
}
}
| 5,646 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiWrapperProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.demo.GreeterWrapperService;
import org.apache.dubbo.demo.GreeterWrapperServiceImpl;
import java.io.IOException;
public class ApiWrapperProvider {
public static void main(String[] args) throws IOException {
ServiceConfig<GreeterWrapperService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(GreeterWrapperService.class);
serviceConfig.setRef(new GreeterWrapperServiceImpl());
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(new ApplicationConfig("dubbo-demo-triple-api-wrapper-provider"))
.registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
.protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1))
.service(serviceConfig)
.start()
.await();
}
}
| 5,647 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiWrapperConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.demo.GreeterWrapperService;
import java.io.IOException;
public class ApiWrapperConsumer {
public static void main(String[] args) throws IOException {
ReferenceConfig<GreeterWrapperService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(GreeterWrapperService.class);
referenceConfig.setCheck(false);
referenceConfig.setProtocol("tri");
referenceConfig.setLazy(true);
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(new ApplicationConfig("dubbo-demo-triple-api-wrapper-consumer"))
.registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
.protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1))
.reference(referenceConfig)
.start();
final GreeterWrapperService greeterWrapperService = referenceConfig.get();
System.out.println("dubbo referenceConfig started");
long st = System.currentTimeMillis();
String reply = greeterWrapperService.sayHello("haha");
// 4MB response
System.out.println("Reply length:" + reply.length() + " cost:" + (System.currentTimeMillis() - st));
System.in.read();
}
}
| 5,648 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiConsumer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.demo.GreeterService;
import org.apache.dubbo.demo.hello.HelloReply;
import org.apache.dubbo.demo.hello.HelloRequest;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class ApiConsumer {
public static void main(String[] args) throws InterruptedException, IOException {
ReferenceConfig<GreeterService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(GreeterService.class);
referenceConfig.setCheck(false);
referenceConfig.setProtocol(CommonConstants.TRIPLE);
referenceConfig.setLazy(true);
referenceConfig.setTimeout(100000);
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(new ApplicationConfig("dubbo-demo-triple-api-consumer"))
.registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
.protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1))
.reference(referenceConfig)
.start();
GreeterService greeterService = referenceConfig.get();
System.out.println("dubbo referenceConfig started");
try {
final HelloReply reply = greeterService.sayHello(
HelloRequest.newBuilder().setName("triple").build());
TimeUnit.SECONDS.sleep(1);
System.out.println("Reply: " + reply.getMessage());
CompletableFuture<String> sayHelloAsync = greeterService.sayHelloAsync("triple");
System.out.println("Async Reply: " + sayHelloAsync.get());
} catch (Throwable t) {
t.printStackTrace();
}
System.in.read();
}
}
| 5,649 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/src/main/java/org/apache/dubbo/demo/graalvm | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/src/main/java/org/apache/dubbo/demo/graalvm/consumer/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.graalvm.consumer;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.graalvm.demo.DemoService;
import java.util.HashMap;
import java.util.Map;
public class Application {
private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181";
public static void main(String[] args) {
System.setProperty("dubbo.application.logger", "log4j");
System.setProperty("native", "true");
System.setProperty("dubbo.json-framework.prefer", "fastjson");
runWithBootstrap();
}
private static void runWithBootstrap() {
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-demo-api-consumer");
applicationConfig.setQosEnable(false);
applicationConfig.setCompiler("jdk");
Map<String, String> m = new HashMap<>(1);
m.put("proxy", "jdk");
applicationConfig.setParameters(m);
ReferenceConfig<DemoService> reference = new ReferenceConfig<>();
reference.setInterface(DemoService.class);
reference.setGeneric("false");
ProtocolConfig protocolConfig = new ProtocolConfig(CommonConstants.DUBBO, -1);
protocolConfig.setSerialization("fastjson2");
bootstrap
.application(applicationConfig)
.registry(new RegistryConfig(REGISTRY_URL))
.protocol(protocolConfig)
.reference(reference)
.start();
DemoService demoService = bootstrap.getCache().get(reference);
String message = demoService.sayHello("Native");
System.out.println(message);
}
}
| 5,650 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/src/main/java/org/apache/dubbo/graalvm | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/src/main/java/org/apache/dubbo/graalvm/demo/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.graalvm.demo;
public interface DemoService {
String sayHello(String name);
}
| 5,651 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.graalvm.provider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.graalvm.demo.DemoService;
import java.util.HashMap;
import java.util.Map;
public class Application {
private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181";
public static void main(String[] args) throws Exception {
System.setProperty("dubbo.application.logger", "log4j");
System.setProperty("native", "true");
System.setProperty("dubbo.json-framework.prefer", "fastjson");
startWithBootstrap();
System.in.read();
}
private static boolean isClassic(String[] args) {
return args.length > 0 && "classic".equalsIgnoreCase(args[0]);
}
private static void startWithBootstrap() {
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-demo-api-provider");
applicationConfig.setQosEnable(false);
applicationConfig.setCompiler("jdk");
Map<String, String> m = new HashMap<>(1);
m.put("proxy", "jdk");
applicationConfig.setParameters(m);
ServiceConfig<DemoService> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
ProtocolConfig protocolConfig = new ProtocolConfig(CommonConstants.DUBBO, -1);
protocolConfig.setSerialization("fastjson2");
bootstrap
.application(applicationConfig)
.registry(new RegistryConfig(REGISTRY_URL))
.protocol(protocolConfig)
.service(service)
.start()
.await();
System.out.println("dubbo service started");
}
}
| 5,652 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm | Create_ds/dubbo/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.graalvm.provider;
import org.apache.dubbo.graalvm.demo.DemoService;
import org.apache.dubbo.rpc.RpcContext;
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
System.out.println("Hello " + name + ", request from consumer: "
+ RpcContext.getContext().getRemoteAddress());
return "Hello " + name;
}
}
| 5,653 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/TripleService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
public interface TripleService {
String hello();
}
| 5,654 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/GreetingService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
/**
*
*/
public interface GreetingService {
String hello();
}
| 5,655 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
import java.util.concurrent.CompletableFuture;
public interface DemoService {
String sayHello(String name);
default CompletableFuture<String> sayHelloAsync(String name) {
return CompletableFuture.completedFuture(sayHello(name));
}
}
| 5,656 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/RestDemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import po.TestPO;
@Path("/demoService")
public interface RestDemoService {
@GET
@Path("/hello")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b);
@GET
@Path("/error")
String error();
@POST
@Path("/say")
@Consumes({MediaType.TEXT_PLAIN})
String sayHello(String name);
@GET
@Path("/getRemoteApplicationName")
String getRemoteApplicationName();
@POST
@Path("/testBody1")
@Consumes({MediaType.TEXT_PLAIN})
Integer testBody(Integer b);
@POST
@Path("/testBody2")
@Consumes({MediaType.TEXT_PLAIN})
String testBody2(String b);
@POST
@Path("/testBody3")
@Consumes({MediaType.TEXT_PLAIN})
Boolean testBody2(Boolean b);
@POST
@Path("/testBody3")
@Consumes({MediaType.TEXT_PLAIN})
TestPO testBody2(TestPO b);
@POST
@Path("/testBody5")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
TestPO testBody5(TestPO testPO);
@POST
@Path("/testForm1")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
String testForm1(@FormParam("name") String test);
@POST
@Path("/testForm2")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
MultivaluedMap testForm2(MultivaluedMap map);
}
| 5,657 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpMethodService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import io.swagger.jaxrs.PATCH;
@Path("/demoService")
public interface HttpMethodService {
@POST
@Path("/sayPost")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloPost(String hello);
@DELETE
@Path("/sayDelete")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloDelete(@QueryParam("name") String hello);
@HEAD
@Path("/sayHead")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloHead(@QueryParam("name") String hello);
@GET
@Path("/sayGet")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloGet(@QueryParam("name") String hello);
@PUT
@Path("/sayPut")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloPut(@QueryParam("name") String hello);
@PATCH
@Path("/sayPatch")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloPatch(@QueryParam("name") String hello);
@OPTIONS
@Path("/sayOptions")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloOptions(@QueryParam("name") String hello);
}
| 5,658 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/DubboServiceAnnotationService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/annotation")
public interface DubboServiceAnnotationService {
@GET
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String annotation();
}
| 5,659 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/ExceptionMapperService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/exception/mapper")
public interface ExceptionMapperService {
@POST
@Path("/exception")
String exception(String message);
}
| 5,660 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/CurlService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/curl")
public interface CurlService {
// curl -X GET http://localhost:8888/services/curl
// http://localhost:8888/services/curl
@GET
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String curl();
}
| 5,661 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpRequestAndResponseRPCContextService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.List;
@Path("/demoService")
public interface HttpRequestAndResponseRPCContextService {
@POST
@Path("/httpRequestParam")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String httpRequestParam(@QueryParam("name") String hello);
@POST
@Path("/httpRequestHeader")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String httpRequestHeader(@HeaderParam("header") String hello);
@POST
@Path("/httpResponseHeader")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
List<String> httpResponseHeader(@HeaderParam("response") String hello);
}
| 5,662 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/SpringRestDemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import java.util.List;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import po.User;
@RequestMapping("/spring/demo/service")
public interface SpringRestDemoService {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Integer hello(@RequestParam("a") Integer a, @RequestParam("b") Integer b);
@RequestMapping(method = RequestMethod.GET, value = "/error")
String error();
@RequestMapping(method = RequestMethod.POST, value = "/say")
String sayHello(@RequestBody String name);
@RequestMapping(
method = RequestMethod.POST,
value = "/testFormBody",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
Long testFormBody(@RequestBody Long number);
@RequestMapping(
method = RequestMethod.POST,
value = "/testJavaBeanBody",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
User testJavaBeanBody(@RequestBody User user);
@RequestMapping(method = RequestMethod.GET, value = "/primitive")
int primitiveInt(@RequestParam("a") int a, @RequestParam("b") int b);
@RequestMapping(method = RequestMethod.GET, value = "/primitiveLong")
long primitiveLong(@RequestParam("a") long a, @RequestParam("b") Long b);
@RequestMapping(method = RequestMethod.GET, value = "/primitiveByte")
long primitiveByte(@RequestParam("a") byte a, @RequestParam("b") Long b);
@RequestMapping(method = RequestMethod.POST, value = "/primitiveShort")
long primitiveShort(@RequestParam("a") short a, @RequestParam("b") Long b, @RequestBody int c);
@RequestMapping(method = RequestMethod.GET, value = "/testMapParam")
String testMapParam(@RequestParam Map<String, String> params);
@RequestMapping(method = RequestMethod.GET, value = "/testMapHeader")
String testMapHeader(@RequestHeader Map<String, String> headers);
@RequestMapping(
method = RequestMethod.POST,
value = "/testMapForm",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
List<String> testMapForm(MultiValueMap<String, String> params);
@RequestMapping(method = RequestMethod.GET, value = "/headerInt")
int headerInt(@RequestHeader("header") int header);
}
| 5,663 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/JaxRsRestDemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List;
import java.util.Map;
import po.User;
/**
*
* @Consumers & @Produces can be not used ,we will make sure the content-type of request by arg type
* but the Request method is forbidden disappear
* parameters which annotation are not present , it is from the body (jaxrs annotation is different from spring web from param(only request param can ignore annotation))
*
* Every method only one param from body
*
* the path annotation must present in class & method
*/
@Path("/jaxrs/demo/service")
public interface JaxRsRestDemoService {
@GET
@Path("/hello")
Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b);
@GET
@Path("/error")
String error();
@POST
@Path("/say")
String sayHello(String name);
@POST
@Path("/testFormBody")
Long testFormBody(@FormParam("number") Long number);
@POST
@Path("/testJavaBeanBody")
@Consumes({MediaType.APPLICATION_JSON})
User testJavaBeanBody(User user);
@GET
@Path("/primitive")
int primitiveInt(@QueryParam("a") int a, @QueryParam("b") int b);
@GET
@Path("/primitiveLong")
long primitiveLong(@QueryParam("a") long a, @QueryParam("b") Long b);
@GET
@Path("/primitiveByte")
long primitiveByte(@QueryParam("a") byte a, @QueryParam("b") Long b);
@POST
@Path("/primitiveShort")
long primitiveShort(@QueryParam("a") short a, @QueryParam("b") Long b, int c);
@GET
@Path("testMapParam")
@Produces({MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN})
String testMapParam(@QueryParam("test") Map<String, String> params);
@GET
@Path("testMapHeader")
@Produces({MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN})
String testMapHeader(@HeaderParam("test") Map<String, String> headers);
@POST
@Path("testMapForm")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
List<String> testMapForm(MultivaluedMap<String, String> params);
@POST
@Path("/header")
@Consumes({MediaType.TEXT_PLAIN})
String header(@HeaderParam("header") String header);
@POST
@Path("/headerInt")
@Consumes({MediaType.TEXT_PLAIN})
int headerInt(@HeaderParam("header") int header);
}
| 5,664 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/po/User.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package po;
import java.io.Serializable;
import java.util.Objects;
public class User implements Serializable {
private Long id;
private String name;
public User() {}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static User getInstance() {
return new User(1l, "dubbo-rest");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "User (" + "id=" + id + ", name='" + name + '\'' + ')';
}
}
| 5,665 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java | Create_ds/dubbo/dubbo-demo/dubbo-demo-interface/src/main/java/po/TestPO.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package po;
public class TestPO {
private String name;
private String address;
private int age;
public TestPO(String name, String address, int age) {
this.name = name;
this.address = address;
this.age = age;
}
public TestPO() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static TestPO getInstance() {
return new TestPO("dubbo", "hangzhou", 10);
}
@Override
public String toString() {
return "TestPO{" + "name='" + name + '\'' + ", address='" + address + '\'' + ", age=" + age + '}';
}
}
| 5,666 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.demo.DemoService;
public class Application {
private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181";
public static void main(String[] args) {
startWithBootstrap();
}
private static void startWithBootstrap() {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(new ApplicationConfig("dubbo-demo-api-provider"))
.registry(new RegistryConfig(REGISTRY_URL))
.protocol(new ProtocolConfig(CommonConstants.DUBBO, -1))
.service(service)
.start()
.await();
}
}
| 5,667 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.provider;
import org.apache.dubbo.demo.DemoService;
import org.apache.dubbo.rpc.RpcContext;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
@Override
public String sayHello(String name) {
logger.info("Hello " + name + ", request from consumer: "
+ RpcContext.getServiceContext().getRemoteAddress());
return "Hello " + name + ", response from provider: "
+ RpcContext.getServiceContext().getLocalAddress();
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
return null;
}
}
| 5,668 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.demo.DemoService;
import org.apache.dubbo.rpc.service.GenericService;
public class Application {
private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181";
public static void main(String[] args) {
runWithBootstrap();
}
private static void runWithBootstrap() {
ReferenceConfig<DemoService> reference = new ReferenceConfig<>();
reference.setInterface(DemoService.class);
reference.setGeneric("true");
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(new ApplicationConfig("dubbo-demo-api-consumer"))
.registry(new RegistryConfig(REGISTRY_URL))
.protocol(new ProtocolConfig(CommonConstants.DUBBO, -1))
.reference(reference)
.start();
DemoService demoService = bootstrap.getCache().get(reference);
String message = demoService.sayHello("dubbo");
System.out.println(message);
// generic invoke
GenericService genericService = (GenericService) demoService;
Object genericInvokeResult = genericService.$invoke(
"sayHello", new String[] {String.class.getName()}, new Object[] {"dubbo generic invoke"});
System.out.println(genericInvokeResult.toString());
}
}
| 5,669 |
0 | Create_ds/dubbo/dubbo-demo/dubbo-demo-generic-call/src/main/java/org/apache/dubbo/demo | Create_ds/dubbo/dubbo-demo/dubbo-demo-generic-call/src/main/java/org/apache/dubbo/demo/consumer/GenericApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.demo.consumer;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.service.GenericService;
public class GenericApplication {
public static void main(String[] args) {
runWithBootstrap(args);
}
private static void runWithBootstrap(String[] args) {
ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
reference.setInterface("org.apache.dubbo.demo.DemoService");
String param = "dubbo generic invoke";
if (args.length > 0 && CommonConstants.GENERIC_SERIALIZATION_GSON.equals(args[0])) {
reference.setGeneric(CommonConstants.GENERIC_SERIALIZATION_GSON);
param = JsonUtils.toJson(param + " gson");
} else {
reference.setGeneric("true");
}
ApplicationConfig applicationConfig = new ApplicationConfig("demo-consumer");
MetadataReportConfig metadataReportConfig = new MetadataReportConfig();
metadataReportConfig.setAddress("zookeeper://127.0.0.1:2181");
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap
.application(applicationConfig)
.registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
.protocol(new ProtocolConfig(CommonConstants.DUBBO, -1))
.reference(reference)
.start();
// generic invoke
GenericService genericService = bootstrap.getCache().get(reference);
while (true) {
try {
Object genericInvokeResult =
genericService.$invoke("sayHello", new String[] {String.class.getName()}, new Object[] {param});
System.out.println(genericInvokeResult);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 5,670 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.*;
import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService;
import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoServiceImpl;
import javax.ws.rs.core.Response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.remoting.Constants.SERVER_KEY;
public class ResteasyResponseTest {
private Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest");
private ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
private final int availablePort = NetUtils.getAvailablePort();
private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService");
private final ModuleServiceRepository repository =
ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
@AfterEach
public void tearDown() {
protocol.destroy();
FrameworkModel.destroyAll();
}
@Test
void testResponse() {
RestDemoService server = new RestDemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, RestDemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, "netty").addParameter("timeout", 3000000);
protocol.export(proxy.getInvoker(new RestDemoServiceImpl(), RestDemoService.class, nettyUrl));
RestDemoService demoService = this.proxy.getProxy(protocol.refer(RestDemoService.class, nettyUrl));
Response response = demoService.findUserById(10);
Assertions.assertNotNull(response);
}
private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass);
ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null);
repository.registerProvider(providerModel);
return url.setServiceModel(providerModel);
}
}
| 5,671 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/User.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import java.io.Serializable;
import java.util.Objects;
/**
* User Entity
*
* @since 2.7.6
*/
public class User implements Serializable {
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static User getInstance() {
User user = new User();
user.setAge(18);
user.setName("dubbo");
user.setId(404l);
return user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(age, user.age);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
}
}
| 5,672 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.metadata.rest.media.MediaType;
import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException;
import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class MediaTypeUtilTest {
@Test
void testException() {
Assertions.assertThrows(UnSupportContentTypeException.class, () -> {
MediaTypeUtil.convertMediaType(null, "aaaaa");
});
}
@Test
void testConvertMediaType() {
MediaType mediaType =
MediaTypeUtil.convertMediaType(null, new String[] {MediaType.APPLICATION_JSON_VALUE.value});
Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType);
mediaType = MediaTypeUtil.convertMediaType(int.class, null);
Assertions.assertEquals(MediaType.TEXT_PLAIN, mediaType);
mediaType = MediaTypeUtil.convertMediaType(null, new String[] {MediaType.ALL_VALUE.value});
Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType);
mediaType = MediaTypeUtil.convertMediaType(String.class, new String[] {MediaType.TEXT_XML.value});
Assertions.assertEquals(MediaType.TEXT_XML, mediaType);
}
}
| 5,673 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.LinkedList;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.internal.util.collections.Sets;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class RpcExceptionMapperTest {
private ExceptionHandler exceptionMapper;
@BeforeEach
public void setUp() {
this.exceptionMapper = new RpcExceptionMapper();
}
@Test
void testConstraintViolationException() {
ConstraintViolationException violationException = mock(ConstraintViolationException.class);
ConstraintViolation<?> violation = mock(ConstraintViolation.class, Answers.RETURNS_DEEP_STUBS);
given(violationException.getConstraintViolations()).willReturn(Sets.newSet(violation));
RpcException rpcException = new RpcException("violation", violationException);
Object response = exceptionMapper.result(rpcException);
assertThat(response, not(nullValue()));
assertThat(response, instanceOf(ViolationReport.class));
}
@Test
void testNormalException() {
RpcException rpcException = new RpcException();
Object response = exceptionMapper.result(rpcException);
assertThat(response, not(nullValue()));
assertThat(response, instanceOf(String.class));
}
@Test
void testBuildException() {
RestConstraintViolation restConstraintViolation = new RestConstraintViolation();
String message = "message";
restConstraintViolation.setMessage(message);
String path = "path";
restConstraintViolation.setPath(path);
String value = "value";
restConstraintViolation.setValue(value);
Assertions.assertEquals(message, restConstraintViolation.getMessage());
Assertions.assertEquals(path, restConstraintViolation.getPath());
Assertions.assertEquals(value, restConstraintViolation.getValue());
}
@Test
public void testViolationReport() {
ViolationReport violationReport = new ViolationReport();
RestConstraintViolation restConstraintViolation = new RestConstraintViolation("path", "message", "value");
violationReport.addConstraintViolation(restConstraintViolation);
Assertions.assertEquals(1, violationReport.getConstraintViolations().size());
violationReport = new ViolationReport();
violationReport.setConstraintViolations(new LinkedList<>());
Assertions.assertEquals(0, violationReport.getConstraintViolations().size());
}
}
| 5,674 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.rpc.RpcContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
@Path("/demoService")
public class DemoServiceImpl implements DemoService {
private static Map<String, Object> context;
private boolean called;
@POST
@Path("/say")
@Consumes({MediaType.TEXT_PLAIN})
@Override
public String sayHello(String name) {
called = true;
return "Hello, " + name;
}
@Override
public Long testFormBody(Long number) {
return number;
}
public boolean isCalled() {
return called;
}
@Override
public int primitiveInt(int a, int b) {
return a + b;
}
@Override
public long primitiveLong(long a, Long b) {
return a + b;
}
@Override
public long primitiveByte(byte a, Long b) {
return a + b;
}
@Override
public long primitiveShort(short a, Long b, int c) {
return a + b;
}
@Override
public void request(DefaultFullHttpRequest defaultFullHttpRequest) {}
@Override
public String testMapParam(Map<String, String> params) {
return params.get("param");
}
@Override
public String testMapHeader(Map<String, String> headers) {
return headers.get("header");
}
@Override
public List<String> testMapForm(MultivaluedMap<String, String> params) {
return params.get("form");
}
@Override
public String header(String header) {
return header;
}
@Override
public int headerInt(int header) {
return header;
}
@Override
public String noStringParam(String param) {
return param;
}
@Override
public String noStringHeader(String header) {
return header;
}
@POST
@Path("/noIntHeader")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
@Override
public int noIntHeader(@HeaderParam("header") int header) {
return header;
}
@POST
@Path("/noIntParam")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
@Override
public int noIntParam(@QueryParam("header") int header) {
return header;
}
@Override
public User noBodyArg(User user) {
return user;
}
@GET
@Path("/hello")
@Override
public Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b) {
context = RpcContext.getServerAttachment().getObjectAttachments();
return a + b;
}
@GET
@Path("/error")
@Override
public String error() {
throw new RuntimeException("test error");
}
public static Map<String, Object> getAttachments() {
return context;
}
@Override
public List<User> list(List<User> users) {
return users;
}
@Override
public Set<User> set(Set<User> users) {
return users;
}
@Override
public User[] array(User[] users) {
return users;
}
@Override
public Map<String, User> stringMap(Map<String, User> userMap) {
return userMap;
}
@Override
public Map<User, User> userMap(Map<User, User> userMap) {
return userMap;
}
@Override
public User formBody(User user) {
user.setName("formBody");
return user;
}
}
| 5,675 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper;
import org.apache.dubbo.rpc.protocol.rest.mvc.SpringDemoServiceImpl;
import org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService;
import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService;
import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestServiceImpl;
import java.util.Arrays;
import java.util.Map;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.util.LinkedMultiValueMap;
import static org.apache.dubbo.remoting.Constants.SERVER_KEY;
import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
public class SpringMvcRestProtocolTest {
private Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest");
private ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
private static final int availablePort = NetUtils.getAvailablePort();
private static final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/rest?interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService");
private final ModuleServiceRepository repository =
ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
private final ExceptionMapper exceptionMapper = new ExceptionMapper();
@AfterEach
public void tearDown() {
protocol.destroy();
FrameworkModel.destroyAll();
}
public SpringRestDemoService getServerImpl() {
return new SpringDemoServiceImpl();
}
public Class<SpringRestDemoService> getServerClass() {
return SpringRestDemoService.class;
}
public Exporter<SpringRestDemoService> getExport(URL url, SpringRestDemoService server) {
url = url.addParameter(SERVER_KEY, Constants.NETTY_HTTP);
return protocol.export(proxy.getInvoker(server, getServerClass(), url));
}
public Exporter<SpringRestDemoService> getExceptionHandlerExport(URL url, SpringRestDemoService server) {
url = url.addParameter(SERVER_KEY, Constants.NETTY_HTTP);
url = url.addParameter(EXTENSION_KEY, TestExceptionMapper.class.getName());
return protocol.export(proxy.getInvoker(server, getServerClass(), url));
}
@Test
void testRestProtocol() {
URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort()
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService");
SpringRestDemoService server = getServerImpl();
url = this.registerProvider(url, server, getServerClass());
Exporter<SpringRestDemoService> exporter = getExport(url, server);
Invoker<SpringRestDemoService> invoker = protocol.refer(SpringRestDemoService.class, url);
Assertions.assertFalse(server.isCalled());
SpringRestDemoService client = proxy.getProxy(invoker);
String result = client.sayHello("haha");
Assertions.assertTrue(server.isCalled());
Assertions.assertEquals("Hello, haha", result);
String header = client.testHeader("header");
Assertions.assertEquals("header", header);
String headerInt = client.testHeaderInt(1);
Assertions.assertEquals("1", headerInt);
invoker.destroy();
exporter.unexport();
}
@Test
void testAnotherUserRestProtocol() {
URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort()
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService");
AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl();
url = this.registerProvider(url, server, SpringRestDemoService.class);
Exporter<AnotherUserRestService> exporter =
protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url));
Invoker<AnotherUserRestService> invoker = protocol.refer(AnotherUserRestService.class, url);
AnotherUserRestService client = proxy.getProxy(invoker);
User result = client.getUser(123l);
Assertions.assertEquals(123l, result.getId());
result.setName("dubbo");
Assertions.assertEquals(123l, client.registerUser(result).getId());
Assertions.assertEquals("context", client.getContext());
byte[] bytes = {1, 2, 3, 4};
Assertions.assertTrue(Arrays.equals(bytes, client.bytes(bytes)));
Assertions.assertEquals(1l, client.number(1l));
invoker.destroy();
exporter.unexport();
}
@Test
void testRestProtocolWithContextPath() {
SpringRestDemoService server = getServerImpl();
Assertions.assertFalse(server.isCalled());
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("rest://127.0.0.1:" + port
+ "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService");
url = this.registerProvider(url, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(url, server);
url = URL.valueOf("rest://127.0.0.1:" + port
+ "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService");
Invoker<SpringRestDemoService> invoker = protocol.refer(SpringRestDemoService.class, url);
SpringRestDemoService client = proxy.getProxy(invoker);
String result = client.sayHello("haha");
Assertions.assertTrue(server.isCalled());
Assertions.assertEquals("Hello, haha", result);
invoker.destroy();
exporter.unexport();
}
@Test
void testExport() {
SpringRestDemoService server = getServerImpl();
URL url = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
RpcContext.getClientAttachment().setAttachment("timeout", "200");
Exporter<SpringRestDemoService> exporter = getExport(url, server);
SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url));
Integer echoString = demoService.hello(1, 2);
assertThat(echoString, is(3));
exporter.unexport();
}
@Test
void testNettyServer() {
SpringRestDemoService server = getServerImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server);
SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl));
Integer echoString = demoService.hello(10, 10);
assertThat(echoString, is(20));
exporter.unexport();
}
@Disabled
@Test
void testServletWithoutWebConfig() {
Assertions.assertThrows(RpcException.class, () -> {
SpringRestDemoService server = getServerImpl();
URL url = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
URL servletUrl = url.addParameter(SERVER_KEY, "servlet");
protocol.export(proxy.getInvoker(server, getServerClass(), servletUrl));
});
}
@Test
void testErrorHandler() {
Assertions.assertThrows(RpcException.class, () -> {
exceptionMapper.unRegisterMapper(RuntimeException.class);
SpringRestDemoService server = getServerImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server);
SpringRestDemoService demoService =
this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl));
demoService.error();
});
}
@Test
void testInvoke() {
SpringRestDemoService server = getServerImpl();
URL url = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(url, server);
RpcInvocation rpcInvocation = new RpcInvocation(
"hello",
SpringRestDemoService.class.getName(),
"",
new Class[] {Integer.class, Integer.class},
new Integer[] {2, 3});
Result result = exporter.getInvoker().invoke(rpcInvocation);
assertThat(result.getValue(), CoreMatchers.<Object>is(5));
}
@Test
void testFilter() {
SpringRestDemoService server = getServerImpl();
URL url = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(url, server);
SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url));
Integer result = demoService.hello(1, 2);
assertThat(result, is(3));
exporter.unexport();
}
@Test
void testRpcContextFilter() {
SpringRestDemoService server = getServerImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
// use RpcContextFilter
// URL nettyUrl = url.addParameter(SERVER_KEY, "netty")
// .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter");
Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server);
SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl));
// make sure null and base64 encoded string can work
RpcContext.getClientAttachment().setAttachment("key1", null);
RpcContext.getClientAttachment().setAttachment("key2", "value");
RpcContext.getClientAttachment().setAttachment("key3", "=value");
RpcContext.getClientAttachment().setAttachment("key4", "YWJjZGVmCg==");
RpcContext.getClientAttachment().setAttachment("key5", "val=ue");
Integer result = demoService.hello(1, 2);
assertThat(result, is(3));
Map<String, Object> attachment = org.apache.dubbo.rpc.protocol.rest.mvc.SpringDemoServiceImpl.getAttachments();
assertThat(attachment.get("key1"), nullValue());
assertThat(attachment.get("key2"), equalTo("value"));
assertThat(attachment.get("key3"), equalTo("=value"));
assertThat(attachment.get("key4"), equalTo("YWJjZGVmCg=="));
assertThat(attachment.get("key5"), equalTo("val=ue"));
exporter.unexport();
}
@Disabled
@Test
void testRegFail() {
Assertions.assertThrows(RuntimeException.class, () -> {
SpringRestDemoService server = getServerImpl();
URL url = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
URL nettyUrl = url.addParameter(EXTENSION_KEY, "com.not.existing.Filter");
Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server);
});
}
@Test
void testDefaultPort() {
assertThat(protocol.getDefaultPort(), is(80));
}
@Test
void testExceptionMapper() {
SpringRestDemoService server = getServerImpl();
URL exceptionUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExceptionHandlerExport(exceptionUrl, server);
SpringRestDemoService referDemoService =
this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, exceptionUrl));
Assertions.assertEquals("test-exception", referDemoService.error());
exporter.unexport();
}
@Test
void testFormConsumerParser() {
SpringRestDemoService server = getServerImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server);
SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl));
User user = new User();
user.setAge(18);
user.setName("dubbo");
user.setId(404l);
String name = demoService.testFormBody(user);
Assertions.assertEquals("dubbo", name);
LinkedMultiValueMap<String, String> forms = new LinkedMultiValueMap<>();
forms.put("form", Arrays.asList("F1"));
Assertions.assertEquals(Arrays.asList("F1"), demoService.testFormMapBody(forms));
exporter.unexport();
}
@Test
void testPrimitive() {
SpringRestDemoService server = getServerImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, SpringRestDemoService.class);
Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server);
SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl));
Integer result = demoService.primitiveInt(1, 2);
Long resultLong = demoService.primitiveLong(1, 2l);
long resultByte = demoService.primitiveByte((byte) 1, 2l);
long resultShort = demoService.primitiveShort((short) 1, 2l, 1);
assertThat(result, is(3));
assertThat(resultShort, is(3l));
assertThat(resultLong, is(3l));
assertThat(resultByte, is(3l));
exporter.unexport();
}
public static class TestExceptionMapper implements ExceptionHandler<RuntimeException> {
@Override
public String result(RuntimeException e) {
return "test-exception";
}
}
private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass);
ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null);
repository.registerProvider(providerModel);
return url.setServiceModel(providerModel);
}
}
| 5,676 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.metadata.rest.PathMatcher;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import org.apache.dubbo.metadata.rest.ServiceRestMetadata;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver;
import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant;
import org.apache.dubbo.rpc.protocol.rest.exception.DoublePathCheckException;
import org.apache.dubbo.rpc.protocol.rest.exception.ResteasyExceptionMapper;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper;
import org.apache.dubbo.rpc.protocol.rest.filter.TraceRequestAndResponseFilter;
import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService;
import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestServiceImpl;
import org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodService;
import org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodServiceImpl;
import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException;
import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService;
import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoServiceImpl;
import org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService;
import org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerServiceImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.hamcrest.CoreMatchers;
import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.remoting.Constants.SERVER_KEY;
import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
class JaxrsRestProtocolTest {
private final Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest");
private final ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
private final int availablePort = NetUtils.getAvailablePort();
private final URL exportUrl = URL.valueOf(
"rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService");
private final ModuleServiceRepository repository =
ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
private final ExceptionMapper exceptionMapper = new ExceptionMapper();
private static final String SERVER = "netty4";
@AfterEach
public void tearDown() {
protocol.destroy();
FrameworkModel.destroyAll();
}
@Test
void testRestProtocol() {
URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort()
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService");
DemoServiceImpl server = new DemoServiceImpl();
url = this.registerProvider(url, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url));
Invoker<DemoService> invoker = protocol.refer(DemoService.class, url);
Assertions.assertFalse(server.isCalled());
DemoService client = proxy.getProxy(invoker);
String result = client.sayHello("haha");
Assertions.assertTrue(server.isCalled());
Assertions.assertEquals("Hello, haha", result);
String header = client.header("header test");
Assertions.assertEquals("header test", header);
Assertions.assertEquals(1, client.headerInt(1));
invoker.destroy();
exporter.unexport();
}
@Test
void testAnotherUserRestProtocolByDifferentRestClient() {
testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP);
testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT);
testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.URL_CONNECTION);
}
void testAnotherUserRestProtocol(String restClient) {
URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort()
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService&"
+ org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient);
AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl();
url = this.registerProvider(url, server, DemoService.class);
Exporter<AnotherUserRestService> exporter =
protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url));
Invoker<AnotherUserRestService> invoker = protocol.refer(AnotherUserRestService.class, url);
AnotherUserRestService client = proxy.getProxy(invoker);
User result = client.getUser(123l);
Assertions.assertEquals(123l, result.getId());
result.setName("dubbo");
Assertions.assertEquals(123l, client.registerUser(result).getId());
Assertions.assertEquals("context", client.getContext());
byte[] bytes = {1, 2, 3, 4};
Assertions.assertTrue(Arrays.equals(bytes, client.bytes(bytes)));
Assertions.assertEquals(1l, client.number(1l));
HashMap<String, String> map = new HashMap<>();
map.put("headers", "h1");
Assertions.assertEquals("h1", client.headerMap(map));
Assertions.assertEquals(null, client.headerMap(null));
invoker.destroy();
exporter.unexport();
}
@Test
void testRestProtocolWithContextPath() {
DemoServiceImpl server = new DemoServiceImpl();
Assertions.assertFalse(server.isCalled());
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("rest://127.0.0.1:" + port
+ "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService");
url = this.registerProvider(url, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url));
url = URL.valueOf("rest://127.0.0.1:" + port
+ "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService");
Invoker<DemoService> invoker = protocol.refer(DemoService.class, url);
DemoService client = proxy.getProxy(invoker);
String result = client.sayHello("haha");
Assertions.assertTrue(server.isCalled());
Assertions.assertEquals("Hello, haha", result);
invoker.destroy();
exporter.unexport();
}
@Test
void testExport() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
RpcContext.getClientAttachment().setAttachment("timeout", "20000");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, url));
Integer echoString = demoService.hello(1, 2);
assertThat(echoString, is(3));
exporter.unexport();
}
@Test
void testNettyServer() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER);
Exporter<DemoService> exporter =
protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Integer echoString = demoService.hello(10, 10);
assertThat(echoString, is(20));
exporter.unexport();
}
@Disabled
@Test
void testServletWithoutWebConfig() {
Assertions.assertThrows(RpcException.class, () -> {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL servletUrl = url.addParameter(SERVER_KEY, "servlet");
protocol.export(proxy.getInvoker(server, DemoService.class, servletUrl));
});
}
@Test
void testErrorHandler() {
Assertions.assertThrows(RpcException.class, () -> {
exceptionMapper.unRegisterMapper(RuntimeException.class);
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
demoService.error();
});
}
@Test
void testInvoke() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url));
RpcInvocation rpcInvocation = new RpcInvocation(
"hello", DemoService.class.getName(), "", new Class[] {Integer.class, Integer.class}, new Integer[] {
2, 3
});
Result result = exporter.getInvoker().invoke(rpcInvocation);
assertThat(result.getValue(), CoreMatchers.<Object>is(5));
}
@Test
void testFilter() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER)
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Integer result = demoService.hello(1, 2);
assertThat(result, is(3));
exporter.unexport();
}
@Disabled
@Test
void testRpcContextFilter() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
// use RpcContextFilter
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER)
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
// make sure null and base64 encoded string can work
RpcContext.getClientAttachment().setAttachment("key1", null);
RpcContext.getClientAttachment().setAttachment("key2", "value");
RpcContext.getClientAttachment().setAttachment("key3", "=value");
RpcContext.getClientAttachment().setAttachment("key4", "YWJjZGVmCg==");
RpcContext.getClientAttachment().setAttachment("key5", "val=ue");
Integer result = demoService.hello(1, 2);
assertThat(result, is(3));
Map<String, Object> attachment = DemoServiceImpl.getAttachments();
assertThat(attachment.get("key1"), nullValue());
assertThat(attachment.get("key2"), equalTo("value"));
assertThat(attachment.get("key3"), equalTo("=value"));
assertThat(attachment.get("key4"), equalTo("YWJjZGVmCg=="));
assertThat(attachment.get("key5"), equalTo("val=ue"));
exporter.unexport();
}
@Disabled
@Test
void testRegFail() {
Assertions.assertThrows(RuntimeException.class, () -> {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(EXTENSION_KEY, "com.not.existing.Filter");
protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
});
}
@Test
void testDefaultPort() {
assertThat(protocol.getDefaultPort(), is(80));
}
@Test
void testExceptionMapper() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL exceptionUrl = url.addParameter(EXTENSION_KEY, TestExceptionMapper.class.getName());
protocol.export(proxy.getInvoker(server, DemoService.class, exceptionUrl));
DemoService referDemoService = this.proxy.getProxy(protocol.refer(DemoService.class, exceptionUrl));
Assertions.assertEquals("test-exception", referDemoService.error());
}
@Test
void testRestExceptionMapper() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL exceptionUrl = url.addParameter(EXTENSION_KEY, ResteasyExceptionMapper.class.getName());
protocol.export(proxy.getInvoker(server, DemoService.class, exceptionUrl));
DemoService referDemoService = this.proxy.getProxy(protocol.refer(DemoService.class, exceptionUrl));
Assertions.assertEquals("test-exception", referDemoService.error());
}
@Test
void testFormConsumerParser() {
DemoService server = new DemoServiceImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Long number = demoService.testFormBody(18l);
Assertions.assertEquals(18l, number);
exporter.unexport();
}
@Test
void test404() {
Assertions.assertThrows(RpcException.class, () -> {
DemoService server = new DemoServiceImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException");
RestDemoForTestException restDemoForTestException =
this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl));
restDemoForTestException.test404();
exporter.unexport();
});
}
@Test
void test400() {
Assertions.assertThrows(RpcException.class, () -> {
DemoService server = new DemoServiceImpl();
URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException");
RestDemoForTestException restDemoForTestException =
this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl));
restDemoForTestException.test400("abc", "edf");
exporter.unexport();
});
}
@Test
void testPrimitive() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER)
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Integer result = demoService.primitiveInt(1, 2);
Long resultLong = demoService.primitiveLong(1, 2l);
long resultByte = demoService.primitiveByte((byte) 1, 2l);
long resultShort = demoService.primitiveShort((short) 1, 2l, 1);
assertThat(result, is(3));
assertThat(resultShort, is(3l));
assertThat(resultLong, is(3l));
assertThat(resultByte, is(3l));
exporter.unexport();
}
@Test
void testDoubleCheckException() {
Assertions.assertThrows(DoublePathCheckException.class, () -> {
DemoService server = new DemoServiceImpl();
Invoker<DemoService> invoker = proxy.getInvoker(server, DemoService.class, exportUrl);
PathAndInvokerMapper pathAndInvokerMapper = new PathAndInvokerMapper();
ServiceRestMetadata serviceRestMetadata =
MetadataResolver.resolveConsumerServiceMetadata(DemoService.class, exportUrl, "");
Map<PathMatcher, RestMethodMetadata> pathContainPathVariableToServiceMap =
serviceRestMetadata.getPathUnContainPathVariableToServiceMap();
Invoker<TestInterface> invokerNew =
proxy.getInvoker(new TestInterface() {}, TestInterface.class, exportUrl);
pathAndInvokerMapper.addPathAndInvoker(pathContainPathVariableToServiceMap, invoker);
pathAndInvokerMapper.addPathAndInvoker(pathContainPathVariableToServiceMap, invokerNew);
});
}
public static interface TestInterface {}
@Test
void testMapParam() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER)
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Map<String, String> params = new HashMap<>();
params.put("param", "P1");
;
Map<String, String> headers = new HashMap<>();
headers.put("header", "H1");
Assertions.assertEquals("P1", demoService.testMapParam(params));
Assertions.assertEquals("H1", demoService.testMapHeader(headers));
MultivaluedMapImpl<String, String> forms = new MultivaluedMapImpl<>();
forms.put("form", Arrays.asList("F1"));
Assertions.assertEquals(Arrays.asList("F1"), demoService.testMapForm(forms));
exporter.unexport();
}
@Test
void testNoArgParam() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER)
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals(null, demoService.noStringHeader(null));
Assertions.assertEquals(null, demoService.noStringParam(null));
Assertions.assertThrows(RpcException.class, () -> {
demoService.noIntHeader(1);
});
Assertions.assertThrows(RpcException.class, () -> {
demoService.noIntParam(1);
});
Assertions.assertEquals(null, demoService.noBodyArg(null));
exporter.unexport();
}
@Test
void testToken() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(RestConstant.TOKEN_KEY, "TOKEN");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals("Hello, hello", demoService.sayHello("hello"));
exporter.unexport();
}
@Test
void testHttpMethods() {
testHttpMethod(org.apache.dubbo.remoting.Constants.OK_HTTP);
testHttpMethod(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT);
testHttpMethod(org.apache.dubbo.remoting.Constants.URL_CONNECTION);
}
void testHttpMethod(String restClient) {
HttpMethodService server = new HttpMethodServiceImpl();
URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort()
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodService&"
+ org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient);
url = this.registerProvider(url, server, HttpMethodService.class);
Exporter<HttpMethodService> exporter = protocol.export(proxy.getInvoker(server, HttpMethodService.class, url));
HttpMethodService demoService = this.proxy.getProxy(protocol.refer(HttpMethodService.class, url));
String expect = "hello";
Assertions.assertEquals(null, demoService.sayHelloHead());
Assertions.assertEquals(expect, demoService.sayHelloDelete("hello"));
Assertions.assertEquals(expect, demoService.sayHelloGet("hello"));
Assertions.assertEquals(expect, demoService.sayHelloOptions("hello"));
// Assertions.assertEquals(expect, demoService.sayHelloPatch("hello"));
Assertions.assertEquals(expect, demoService.sayHelloPost("hello"));
Assertions.assertEquals(expect, demoService.sayHelloPut("hello"));
exporter.unexport();
}
public static class TestExceptionMapper implements ExceptionHandler<RuntimeException> {
@Override
public String result(RuntimeException e) {
return "test-exception";
}
}
@Test
void test405() {
int availablePort = NetUtils.getAvailablePort();
URL url = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService&");
RestDemoServiceImpl server = new RestDemoServiceImpl();
url = this.registerProvider(url, server, RestDemoService.class);
Exporter<RestDemoService> exporter = protocol.export(proxy.getInvoker(server, RestDemoService.class, url));
URL consumer = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException&");
consumer = this.registerProvider(consumer, server, RestDemoForTestException.class);
Invoker<RestDemoForTestException> invoker = protocol.refer(RestDemoForTestException.class, consumer);
RestDemoForTestException client = proxy.getProxy(invoker);
Assertions.assertThrows(RpcException.class, () -> {
client.testMethodDisallowed("aaa");
});
invoker.destroy();
exporter.unexport();
}
@Test
void testGetInvoker() {
Assertions.assertDoesNotThrow(() -> {
URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService");
TestGetInvokerService server = new TestGetInvokerServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
Exporter<TestGetInvokerService> exporter =
protocol.export(proxy.getInvoker(server, TestGetInvokerService.class, url));
TestGetInvokerService invokerService =
this.proxy.getProxy(protocol.refer(TestGetInvokerService.class, url));
String invoker = invokerService.getInvoker();
Assertions.assertEquals("success", invoker);
exporter.unexport();
});
}
@Test
void testContainerRequestFilter() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, "netty")
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TestContainerRequestFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals("return-success", demoService.sayHello("hello"));
exporter.unexport();
}
@Test
void testIntercept() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, "netty")
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.intercept.DynamicTraceInterceptor");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals("intercept", demoService.sayHello("hello"));
exporter.unexport();
}
@Test
void testResponseFilter() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, "netty")
.addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TraceFilter");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals("response-filter", demoService.sayHello("hello"));
exporter.unexport();
}
@Test
void testCollectionResult() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, "netty");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals(
User.getInstance(),
demoService.list(Arrays.asList(User.getInstance())).get(0));
HashSet<User> objects = new HashSet<>();
objects.add(User.getInstance());
Assertions.assertEquals(User.getInstance(), new ArrayList<>(demoService.set(objects)).get(0));
Assertions.assertEquals(User.getInstance(), demoService.array(objects.toArray(new User[0]))[0]);
Map<String, User> map = new HashMap<>();
map.put("map", User.getInstance());
Assertions.assertEquals(User.getInstance(), demoService.stringMap(map).get("map"));
Map<User, User> maps = new HashMap<>();
maps.put(User.getInstance(), User.getInstance());
Assertions.assertEquals(User.getInstance(), demoService.userMap(maps).get(User.getInstance()));
exporter.unexport();
}
@Test
void testReExport() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, "netty");
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
nettyUrl = url.addParameter("SERVER_KEY", "netty");
exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
exporter.unexport();
}
@Test
void testBody() {
Assertions.assertThrowsExactly(RpcException.class, () -> {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(org.apache.dubbo.remoting.Constants.PAYLOAD_KEY, 1024);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
List<User> users = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
users.add(User.getInstance());
}
demoService.list(users);
exporter.unexport();
});
}
@Test
void testRequestAndResponseFilter() {
DemoService server = new DemoServiceImpl();
URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService&extension="
+ TraceRequestAndResponseFilter.class.getName());
URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
Assertions.assertEquals("header-result", demoService.sayHello("hello"));
exporter.unexport();
}
@Test
void testFormBody() {
DemoService server = new DemoServiceImpl();
URL url = this.registerProvider(exportUrl, server, DemoService.class);
URL nettyUrl = url.addParameter(SERVER_KEY, SERVER);
Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl));
DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl));
User user = demoService.formBody(User.getInstance());
Assertions.assertEquals("formBody", user.getName());
exporter.unexport();
}
private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass);
ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null);
repository.registerProvider(providerModel);
return url.setServiceModel(providerModel);
}
}
| 5,677 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.metadata.rest.media.MediaType;
import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager;
import org.apache.dubbo.rpc.protocol.rest.message.codec.XMLCodec;
import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair;
import org.apache.dubbo.rpc.protocol.rest.rest.RegistrationResult;
import java.io.ByteArrayOutputStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class HttpMessageCodecManagerTest {
@Test
void testCodec() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
RegistrationResult registrationResult = new RegistrationResult();
registrationResult.setId(1l);
HttpMessageCodecManager.httpMessageEncode(
byteArrayOutputStream, registrationResult, null, MediaType.TEXT_XML, null);
Object o = HttpMessageCodecManager.httpMessageDecode(
byteArrayOutputStream.toByteArray(),
RegistrationResult.class,
RegistrationResult.class,
MediaType.TEXT_XML);
Assertions.assertEquals(registrationResult, o);
byteArrayOutputStream = new ByteArrayOutputStream();
MessageCodecResultPair messageCodecResultPair = HttpMessageCodecManager.httpMessageEncode(
byteArrayOutputStream, null, null, null, RegistrationResult.class);
MediaType mediaType = messageCodecResultPair.getMediaType();
Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType);
XMLCodec xmlCodec = new XMLCodec();
Assertions.assertEquals(false, xmlCodec.typeSupport(null));
}
}
| 5,678 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils;
import java.io.ByteArrayOutputStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class DataParseUtilsTest {
@Test
void testJsonConvert() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataParseUtils.writeJsonContent(User.getInstance(), byteArrayOutputStream);
Assertions.assertEquals(
"{\"age\":18,\"id\":404,\"name\":\"dubbo\"}", new String(byteArrayOutputStream.toByteArray()));
}
@Test
void testStr() {
Object convert = DataParseUtils.stringTypeConvert(boolean.class, "true");
Assertions.assertEquals(Boolean.TRUE, convert);
convert = DataParseUtils.stringTypeConvert(Boolean.class, "true");
Assertions.assertEquals(Boolean.TRUE, convert);
convert = DataParseUtils.stringTypeConvert(String.class, "true");
Assertions.assertEquals("true", convert);
convert = DataParseUtils.stringTypeConvert(int.class, "1");
Assertions.assertEquals(1, convert);
convert = DataParseUtils.stringTypeConvert(Integer.class, "1");
Assertions.assertEquals(1, convert);
}
}
| 5,679 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils;
import org.apache.dubbo.rpc.protocol.rest.util.NumberUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class NumberUtilsTest {
void testParseNumber(String numberStr) {
int integer = NumberUtils.parseNumber(numberStr, Integer.class);
Assertions.assertEquals(1, integer);
integer = NumberUtils.parseNumber(numberStr, int.class);
Assertions.assertEquals(1, integer);
long a = NumberUtils.parseNumber(numberStr, Long.class);
Assertions.assertEquals(1, a);
a = NumberUtils.parseNumber(numberStr, long.class);
Assertions.assertEquals(1, a);
byte b = NumberUtils.parseNumber(numberStr, Byte.class);
Assertions.assertEquals(1, b);
b = NumberUtils.parseNumber(numberStr, byte.class);
Assertions.assertEquals(1, b);
short c = NumberUtils.parseNumber(numberStr, Short.class);
Assertions.assertEquals(1, c);
c = NumberUtils.parseNumber(numberStr, short.class);
Assertions.assertEquals(1, c);
BigInteger f = NumberUtils.parseNumber(numberStr, BigInteger.class);
Assertions.assertEquals(1, f.intValue());
}
@Test
void testNumberToBytes() {
byte[] except = {49};
byte[] bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Integer.valueOf("1"));
Assertions.assertArrayEquals(except, bytes);
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(NumberUtils.parseNumber("1", int.class));
Assertions.assertArrayEquals(except, bytes);
except = new byte[] {49};
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Byte.valueOf("1"));
Assertions.assertArrayEquals(except, bytes);
except = new byte[] {49};
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Short.valueOf("1"));
Assertions.assertArrayEquals(except, bytes);
except = new byte[] {49};
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Long.valueOf("1"));
Assertions.assertArrayEquals(except, bytes);
except = new byte[] {49};
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(BigDecimal.valueOf(1));
Assertions.assertArrayEquals(except, bytes);
except = new byte[] {116, 114, 117, 101};
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Boolean.TRUE);
Assertions.assertArrayEquals(except, bytes);
except = new byte[] {116, 114, 117, 101};
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(true);
Assertions.assertArrayEquals(except, bytes);
bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(User.getInstance());
except = User.getInstance().toString().getBytes(StandardCharsets.UTF_8);
Assertions.assertArrayEquals(except, bytes);
}
@Test
void testNumberStr() {
testParseNumber("1");
testParseNumber("0X0001");
testParseNumber("0x0001");
testParseNumber("#1");
}
@Test
void testUnHexNumber() {
String numberStr = "1";
double e = NumberUtils.parseNumber(numberStr, Double.class);
Assertions.assertEquals(1.0, e);
e = NumberUtils.parseNumber(numberStr, double.class);
Assertions.assertEquals(1.0, e);
BigDecimal g = NumberUtils.parseNumber(numberStr, BigDecimal.class);
Assertions.assertEquals(1, g.intValue());
int integer = NumberUtils.parseNumber(numberStr, int.class);
Assertions.assertEquals(1, integer);
}
@Test
void testNegative() {
Integer integer = NumberUtils.parseNumber("-0X1", int.class);
Assertions.assertEquals(-1, integer);
BigInteger bigInteger = NumberUtils.parseNumber("-0X1", BigInteger.class);
Assertions.assertEquals(-1, bigInteger.intValue());
}
@Test
void testException() {
Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> {
Object abc = NumberUtils.parseNumber("abc", Object.class);
});
Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> {
Object abc = NumberUtils.parseNumber(null, Object.class);
});
Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> {
Object abc = NumberUtils.parseNumber("1", null);
});
}
}
| 5,680 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import org.jboss.resteasy.annotations.Form;
@Path("/demoService")
public interface DemoService {
@GET
@Path("/hello")
Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b);
@GET
@Path("/error")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
@Produces({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String error();
@POST
@Path("/say")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHello(String name);
@POST
@Path("number")
Long testFormBody(@FormParam("number") Long number);
boolean isCalled();
@GET
@Path("/primitive")
int primitiveInt(@QueryParam("a") int a, @QueryParam("b") int b);
@GET
@Path("/primitiveLong")
long primitiveLong(@QueryParam("a") long a, @QueryParam("b") Long b);
@GET
@Path("/primitiveByte")
long primitiveByte(@QueryParam("a") byte a, @QueryParam("b") Long b);
@POST
@Path("/primitiveShort")
long primitiveShort(@QueryParam("a") short a, @QueryParam("b") Long b, int c);
@GET
@Path("/request")
void request(DefaultFullHttpRequest defaultFullHttpRequest);
@GET
@Path("testMapParam")
@Produces({MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN})
String testMapParam(@QueryParam("test") Map<String, String> params);
@GET
@Path("testMapHeader")
@Produces({MediaType.TEXT_PLAIN})
@Consumes({MediaType.TEXT_PLAIN})
String testMapHeader(@HeaderParam("test") Map<String, String> headers);
@POST
@Path("testMapForm")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
List<String> testMapForm(MultivaluedMap<String, String> params);
@POST
@Path("/header")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String header(@HeaderParam("header") String header);
@POST
@Path("/headerInt")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
int headerInt(@HeaderParam("header") int header);
@POST
@Path("/noStringParam")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String noStringParam(@QueryParam("param") String param);
@POST
@Path("/noStringHeader")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String noStringHeader(@HeaderParam("header") String header);
@POST
@Path("/noIntHeader")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
int noIntHeader(int header);
@POST
@Path("/noIntParam")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
int noIntParam(int header);
@POST
@Path("/noBodyArg")
@Consumes({MediaType.APPLICATION_JSON})
User noBodyArg(User user);
@POST
@Path("/list")
List<User> list(List<User> users);
@POST
@Path("/set")
Set<User> set(Set<User> users);
@POST
@Path("/array")
User[] array(User[] users);
@POST
@Path("/stringMap")
Map<String, User> stringMap(Map<String, User> userMap);
@POST
@Path("/map")
Map<User, User> userMap(Map<User, User> userMap);
@POST
@Path("/formBody")
User formBody(@Form User user);
}
| 5,681 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class NettyRequestFacadeTest {
@Test
void testMethod() {
String uri = "/a/b?c=c&d=d";
DefaultFullHttpRequest defaultFullHttpRequest =
new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
defaultFullHttpRequest.headers().add("h1", "a");
defaultFullHttpRequest.headers().add("h1", "b");
defaultFullHttpRequest.headers().add("h2", "c");
NettyRequestFacade nettyRequestFacade = new NettyRequestFacade(defaultFullHttpRequest, null);
Assertions.assertArrayEquals(new String[] {"c"}, nettyRequestFacade.getParameterValues("c"));
Enumeration<String> parameterNames = nettyRequestFacade.getParameterNames();
List<String> names = new ArrayList<>();
while (parameterNames.hasMoreElements()) {
names.add(parameterNames.nextElement());
}
Assertions.assertArrayEquals(Arrays.asList("c", "d").toArray(), names.toArray());
Enumeration<String> headerNames = nettyRequestFacade.getHeaderNames();
List<String> heads = new ArrayList<>();
while (headerNames.hasMoreElements()) {
heads.add(headerNames.nextElement());
}
Assertions.assertArrayEquals(Arrays.asList("h1", "h2").toArray(), heads.toArray());
Assertions.assertEquals(uri, nettyRequestFacade.getRequestURI());
Assertions.assertEquals("c", nettyRequestFacade.getHeader("h2"));
Assertions.assertEquals("d", nettyRequestFacade.getParameter("d"));
Assertions.assertEquals("/a/b", nettyRequestFacade.getPath());
Assertions.assertEquals(null, nettyRequestFacade.getParameterValues("e"));
Assertions.assertArrayEquals(new String[] {"d"}, nettyRequestFacade.getParameterValues("d"));
Enumeration<String> h1s = nettyRequestFacade.getHeaders("h1");
heads = new ArrayList<>();
while (h1s.hasMoreElements()) {
heads.add(h1s.nextElement());
}
Assertions.assertArrayEquals(new String[] {"a", "b"}, heads.toArray());
Map<String, String[]> parameterMap = nettyRequestFacade.getParameterMap();
Assertions.assertArrayEquals(new String[] {"c"}, parameterMap.get("c"));
Assertions.assertArrayEquals(new String[] {"d"}, parameterMap.get("d"));
Assertions.assertEquals("GET", nettyRequestFacade.getMethod());
}
}
| 5,682 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandlerResult;
import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ExceptionMapperTest {
private final ExceptionMapper exceptionMapper = new ExceptionMapper();
@Test
void testRegister() {
exceptionMapper.registerMapper(TestExceptionHandler.class);
ExceptionHandlerResult result = exceptionMapper.exceptionToResult(new RuntimeException("test"));
Assertions.assertEquals("test", result.getEntity());
}
@Test
void testExceptionNoArgConstruct() {
Assertions.assertThrows(RuntimeException.class, () -> {
exceptionMapper.registerMapper(TestExceptionHandlerException.class);
});
}
public class TestExceptionHandler implements ExceptionHandler<RuntimeException> {
@Override
public Object result(RuntimeException exception) {
return exception.getMessage();
}
}
class TestExceptionHandlerException implements ExceptionHandler<RuntimeException> {
@Override
public Object result(RuntimeException exception) {
return exception.getMessage();
}
}
}
| 5,683 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.http.RequestTemplate;
import org.apache.dubbo.remoting.http.config.HttpClientConfig;
import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant;
import org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ServiceConfigTest {
private final Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest");
private final ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
private final ModuleServiceRepository repository =
ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
@AfterEach
public void tearDown() {
protocol.destroy();
FrameworkModel.destroyAll();
}
@Test
void testControllerService() throws Exception {
int availablePort = NetUtils.getAvailablePort();
URL url = URL.valueOf("rest://127.0.0.1:" + availablePort
+ "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService");
SpringControllerService server = new SpringControllerService();
url = this.registerProvider(url, server, SpringControllerService.class);
Exporter<SpringControllerService> exporter =
protocol.export(proxy.getInvoker(server, SpringControllerService.class, url));
OKHttpRestClient okHttpRestClient = new OKHttpRestClient(new HttpClientConfig());
RequestTemplate requestTemplate = new RequestTemplate(null, "GET", "127.0.0.1:" + availablePort);
requestTemplate.path("/controller/sayHello?say=dubbo");
requestTemplate.addHeader(RestConstant.CONTENT_TYPE, "text/plain");
requestTemplate.addHeader(RestConstant.ACCEPT, "text/plain");
requestTemplate.addHeader(RestHeaderEnum.VERSION.getHeader(), "1.0.0");
byte[] body = okHttpRestClient.send(requestTemplate).get().getBody();
Assertions.assertEquals("dubbo", new String(body));
exporter.unexport();
}
private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) {
ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass);
ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null);
repository.registerProvider(providerModel);
return url.setServiceModel(providerModel);
}
}
| 5,684 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringControllerService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.mvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/controller")
public class SpringControllerService {
@GetMapping("/sayHello")
public String sayHello(String say) {
return say;
}
}
| 5,685 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.mvc;
import org.apache.dubbo.rpc.protocol.rest.User;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("/demoService")
public interface SpringRestDemoService {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
Integer hello(@RequestParam Integer a, @RequestParam Integer b);
@RequestMapping(value = "/error", method = RequestMethod.GET)
String error();
@RequestMapping(value = "/sayHello", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE)
String sayHello(String name);
boolean isCalled();
@RequestMapping(
value = "/testFormBody",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
String testFormBody(@RequestBody User user);
@RequestMapping(
value = "/testFormMapBody",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
List<String> testFormMapBody(@RequestBody LinkedMultiValueMap map);
@RequestMapping(value = "/testHeader", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE)
String testHeader(@RequestHeader String header);
@RequestMapping(value = "/testHeaderInt", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE)
String testHeaderInt(@RequestHeader int header);
@RequestMapping(method = RequestMethod.GET, value = "/primitive")
int primitiveInt(@RequestParam("a") int a, @RequestParam("b") int b);
@RequestMapping(method = RequestMethod.GET, value = "/primitiveLong")
long primitiveLong(@RequestParam("a") long a, @RequestParam("b") Long b);
@RequestMapping(method = RequestMethod.GET, value = "/primitiveByte")
long primitiveByte(@RequestParam("a") byte a, @RequestParam("b") Long b);
@RequestMapping(method = RequestMethod.POST, value = "/primitiveShort")
long primitiveShort(@RequestParam("a") short a, @RequestParam("b") Long b, @RequestBody int c);
}
| 5,686 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.mvc;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.protocol.rest.User;
import java.util.List;
import java.util.Map;
import org.springframework.util.LinkedMultiValueMap;
public class SpringDemoServiceImpl implements SpringRestDemoService {
private static Map<String, Object> context;
private boolean called;
@Override
public String sayHello(String name) {
called = true;
return "Hello, " + name;
}
@Override
public boolean isCalled() {
return called;
}
@Override
public String testFormBody(User user) {
return user.getName();
}
@Override
public List<String> testFormMapBody(LinkedMultiValueMap map) {
return map.get("form");
}
@Override
public String testHeader(String header) {
return header;
}
@Override
public String testHeaderInt(int header) {
return String.valueOf(header);
}
@Override
public Integer hello(Integer a, Integer b) {
context = RpcContext.getServerAttachment().getObjectAttachments();
return a + b;
}
@Override
public String error() {
throw new RuntimeException();
}
public static Map<String, Object> getAttachments() {
return context;
}
@Override
public int primitiveInt(int a, int b) {
return a + b;
}
@Override
public long primitiveLong(long a, Long b) {
return a + b;
}
@Override
public long primitiveByte(byte a, Long b) {
return a + b;
}
@Override
public long primitiveShort(short a, Long b, int c) {
return a + b;
}
}
| 5,687 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.integration.swagger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import io.swagger.models.Swagger;
import org.jboss.resteasy.spi.ResteasyUriInfo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class DubboSwaggerApiListingResourceTest {
private Application app;
private ServletConfig sc;
@Test
void test() throws Exception {
DubboSwaggerApiListingResource resource = new DubboSwaggerApiListingResource();
app = mock(Application.class);
sc = mock(ServletConfig.class);
Set<Class<?>> sets = new HashSet<Class<?>>();
sets.add(SwaggerService.class);
when(sc.getServletContext()).thenReturn(mock(ServletContext.class));
when(app.getClasses()).thenReturn(sets);
Response response = resource.getListingJson(app, sc, null, new ResteasyUriInfo(new URI("http://rest.test")));
Assertions.assertNotNull(response);
Swagger swagger = (Swagger) response.getEntity();
Assertions.assertEquals("SwaggerService", swagger.getTags().get(0).getName());
Assertions.assertEquals(
"/demoService/hello", swagger.getPaths().keySet().toArray()[0].toString());
}
}
| 5,688 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.integration.swagger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Path("/demoService")
@Api(value = "SwaggerService")
public interface SwaggerService {
@GET
@Path("/hello")
@ApiOperation(value = "hello")
Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b);
}
| 5,689 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.intercept;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Priority(Priorities.USER)
public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor {
public DynamicTraceInterceptor() {}
@Override
public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext)
throws IOException, WebApplicationException {
System.out.println("Dynamic reader interceptor invoked");
return readerInterceptorContext.proceed();
}
@Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext)
throws IOException, WebApplicationException {
System.out.println("Dynamic writer interceptor invoked");
writerInterceptorContext.getOutputStream().write("intercept".getBytes(StandardCharsets.UTF_8));
writerInterceptorContext.proceed();
}
}
| 5,690 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.filter;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import java.io.IOException;
@Priority(Priorities.USER)
public class TestContainerRequestFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.abortWith(Response.status(200).entity("return-success").build());
}
}
| 5,691 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.filter;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import java.io.IOException;
@Priority(Priorities.USER)
public class TraceRequestAndResponseFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.getHeaders().add("test-response", "header-result");
}
@Override
public void filter(
ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext)
throws IOException {
String headerString = containerRequestContext.getHeaderString("test-response");
containerResponseContext.setEntity(headerString);
}
}
| 5,692 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.filter;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import java.io.IOException;
@Priority(Priorities.USER)
public class TraceFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println(
"Request filter invoked: " + requestContext.getUriInfo().getAbsolutePath());
}
@Override
public void filter(
ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext)
throws IOException {
containerResponseContext.setEntity("response-filter");
System.out.println("Response filter invoked.");
}
}
| 5,693 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/exception/ResteasyExceptionMapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ResteasyExceptionMapper implements ExceptionMapper<RuntimeException> {
@Override
public Response toResponse(RuntimeException exception) {
return Response.status(200).entity("test-exception").build();
}
}
| 5,694 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.rest;
import javax.ws.rs.*;
@Path("/demoService")
public interface HttpMethodService {
@POST
@Path("/sayPost")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloPost(@QueryParam("name") String name);
@DELETE
@Path("/sayDelete")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloDelete(@QueryParam("name") String name);
@HEAD
@Path("/sayHead")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloHead();
@GET
@Path("/sayGet")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloGet(@QueryParam("name") String name);
@PUT
@Path("/sayPut")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloPut(@QueryParam("name") String name);
@PATCH
@Path("/sayPatch")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloPatch(@QueryParam("name") String name);
@OPTIONS
@Path("/sayOptions")
@Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN})
String sayHelloOptions(@QueryParam("name") String name);
}
| 5,695 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.rest;
import org.apache.dubbo.rpc.protocol.rest.User;
import java.util.Map;
public class AnotherUserRestServiceImpl implements AnotherUserRestService {
@Override
public User getUser(Long id) {
User user = new User();
user.setId(id);
return user;
}
@Override
public RegistrationResult registerUser(User user) {
return new RegistrationResult(user.getId());
}
@Override
public String getContext() {
return "context";
}
@Override
public byte[] bytes(byte[] bytes) {
return bytes;
}
@Override
public Long number(Long number) {
return number;
}
@Override
public String headerMap(Map<String, String> headers) {
return headers.get("headers");
}
}
| 5,696 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.rest;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.protocol.rest.RestRPCInvocationUtil;
import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assertions;
public class TestGetInvokerServiceImpl implements TestGetInvokerService {
@Override
public String getInvoker() {
Object request = RpcContext.getServiceContext().getRequest();
RequestFacade requestFacade = (RequestFacade) request;
Invoker invokerByRequest = RestRPCInvocationUtil.getInvokerByRequest((RequestFacade) request);
Method hello = null;
Method hashcode = null;
try {
hello = TestGetInvokerServiceImpl.class.getDeclaredMethod("getInvoker");
hashcode = TestGetInvokerServiceImpl.class.getDeclaredMethod("hashcode");
} catch (NoSuchMethodException e) {
}
Invoker invokerByServiceInvokeMethod =
RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hello, requestFacade.getServiceDeployer());
Invoker invoker =
RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hashcode, requestFacade.getServiceDeployer());
Assertions.assertEquals(invokerByRequest, invokerByServiceInvokeMethod);
Assertions.assertNull(invoker);
return "success";
}
}
| 5,697 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/test")
public interface TestGetInvokerService {
@GET
@Path("/getInvoker")
String getInvoker();
}
| 5,698 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.rest.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/demoService")
public interface RestDemoForTestException {
@POST
@Path("/noFound")
@Produces(MediaType.TEXT_PLAIN)
String test404();
@GET
@Consumes({MediaType.TEXT_PLAIN})
@Path("/hello")
Integer test400(@QueryParam("a") String a, @QueryParam("b") String b);
@POST
@Path("{uid}")
String testMethodDisallowed(@PathParam("uid") String uid);
}
| 5,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.