diff --git a/.travis.yml b/.travis.yml index edb718cb..c0cf170b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,8 @@ language: java jdk: - openjdk7 +install: + - JAVA_HOME=$(jdk_switcher home openjdk8) ./gradlew classes testClasses after_success: - ./gradlew jacocoTestReport - bash <(curl -s https://codecov.io/bash) diff --git a/README.md b/README.md index 5b922235..650ddd5a 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,12 @@ the dependency with the `endpoints-framework` artifact from the com.google.endpoints endpoints-framework - 2.0.0-beta.8 + 2.2.2 In Gradle, the new dependency looks like this: - compile group: 'com.google.endpoints', name: 'endpoints-framework', version: '2.0.0-beta.8' + compile group: 'com.google.endpoints', name: 'endpoints-framework', version: '2.2.2' You also need to update your `web.xml`. Simply replace all instances of `SystemServiceServlet` with `EndpointsServlet` and replace `/_ah/spi/*` with diff --git a/build.gradle b/build.gradle index 9e30bc5f..4c285e58 100644 --- a/build.gradle +++ b/build.gradle @@ -97,9 +97,9 @@ def configureMaven(project, projectName, projectDescription) { url 'https://cloud.google.com/endpoints/docs/frameworks/java' scm { - connection 'scm:git:https://github.com/cloudendpoints/endpoints-java-framework' - developerConnection 'scm:git:https://github.com/cloudendpoints/endpoints-java-framework' - url 'scm:git:https://github.com/cloudendpoints/endpoints-java-framework' + connection 'scm:git:https://github.com/cloudendpoints/endpoints-java' + developerConnection 'scm:git:https://github.com/cloudendpoints/endpoints-java' + url 'scm:git:https://github.com/cloudendpoints/endpoints-java' } licenses { diff --git a/endpoints-framework-all/build.gradle b/endpoints-framework-all/build.gradle new file mode 100644 index 00000000..73394894 --- /dev/null +++ b/endpoints-framework-all/build.gradle @@ -0,0 +1,45 @@ +plugins { + id 'com.github.johnrengelman.shadow' version '1.2.3' +} + +configurations { + include + compile.extendsFrom include +} + +jar { + from { + configurations.include.collect { it.isDirectory() ? it : zipTree(it) } + } +} + +def repackagedDir = 'endpoints.repackaged' + +shadowJar { + classifier = null + relocate 'org.apache', "${repackagedDir}.org.apache" + relocate 'org.yaml', "${repackagedDir}.org.yaml" + relocate 'org.joda', "${repackagedDir}.org.joda" + relocate 'com.fasterxml', "${repackagedDir}.com.fasterxml" + relocate 'io.swagger', "${repackagedDir}.io.swagger" + relocate 'com.google.common', "${repackagedDir}.com.google.common" + relocate 'com.google.api.client', "${repackagedDir}.com.google.api.client" + relocate 'org.slf4j', "${repackagedDir}.org.slf4j" + + dependencies { + exclude(dependency('com.google.appengine:appengine-api-1.0-sdk:.*')) + exclude(dependency('javax.servlet:servlet-api:.*')) + } +} + +artifacts { + archives shadowJar +} + +dependencies { + include project(':endpoints-framework') + compile group: 'com.google.appengine', name: 'appengine-api-1.0-sdk', version: appengineVersion + compile group: 'javax.servlet', name: 'servlet-api', version: servletVersion +} + +configureMaven(project, 'Endpoints Framework', 'A framework for building RESTful web APIs.') diff --git a/endpoints-framework-guice/build.gradle b/endpoints-framework-guice/build.gradle index 5d50ac12..851fdda1 100644 --- a/endpoints-framework-guice/build.gradle +++ b/endpoints-framework-guice/build.gradle @@ -20,7 +20,7 @@ configureMaven( 'Extension to configure the Endpoints Framework via Guice.') dependencies { - compile project(':endpoints-framework') + compileOnly project(':endpoints-framework') compile group: 'com.google.inject', name: 'guice', version: guiceVersion compile group: 'com.google.inject.extensions', name: 'guice-servlet', version: guiceVersion diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/EndpointsModule.java b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/EndpointsModule.java index f0d0ffc3..ee7814eb 100644 --- a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/EndpointsModule.java +++ b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/EndpointsModule.java @@ -18,11 +18,14 @@ import com.google.api.server.spi.ServletInitializationParameters; import com.google.inject.servlet.ServletModule; +import java.util.logging.Logger; + /** * A base Guice module which provides helpers for configuring Endpoints. Consumers should extend * this class and call one of the helpers in {@link #configureServlets()}. */ public class EndpointsModule extends ServletModule { + private static final Logger logger = Logger.getLogger(EndpointsModule.class.getName()); /** * Configure Endpoints given a list of service classes using {@link GuiceEndpointsServlet}. * @@ -39,12 +42,14 @@ protected void configureEndpoints( /** * Configure Endpoints given a list of service classes. * + * @deprecated the legacy servlet is no longer available. * @param urlPattern the URL pattern to configure the servlet on. For the legacy servlet, use * "/_ah/spi/*". For the new servlet, use "/_ah/api/*" if backwards compatibility is desired, or * any other pattern if compatibility is not an issue. * @param serviceClasses the list of backend classes to be included * @param useLegacyServlet whether or not to use the old style servlet */ + @Deprecated protected void configureEndpoints( String urlPattern, Iterable> serviceClasses, boolean useLegacyServlet) { ServletInitializationParameters initParameters = ServletInitializationParameters.builder() @@ -81,9 +86,8 @@ protected void configureEndpoints( bind(ServiceMap.class) .toInstance(ServiceMap.create(binder(), initParameters.getServiceClasses())); if (useLegacyServlet) { - super.serve(urlPattern).with(GuiceSystemServiceServlet.class, initParameters.asMap()); - } else { - super.serve(urlPattern).with(GuiceEndpointsServlet.class, initParameters.asMap()); + logger.severe("the legacy servlet is no longer available."); } + super.serve(urlPattern).with(GuiceEndpointsServlet.class, initParameters.asMap()); } } diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceEndpointsServlet.java b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceEndpointsServlet.java index e93aa4ca..b53d0ec9 100644 --- a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceEndpointsServlet.java +++ b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceEndpointsServlet.java @@ -16,7 +16,6 @@ package com.google.api.server.spi.guice; import com.google.api.server.spi.EndpointsServlet; -import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Singleton; diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceSystemServiceServlet.java b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceSystemServiceServlet.java deleted file mode 100644 index 4930ef6f..00000000 --- a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceSystemServiceServlet.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.guice; - -import com.google.api.server.spi.SystemServiceServlet; -import com.google.common.base.Preconditions; -import com.google.inject.Inject; -import com.google.inject.Singleton; - -/** - * Extension of {@link SystemServiceServlet} for Guice enhanced services. - * - * @author Joe Catalano - */ -@Singleton -class GuiceSystemServiceServlet extends SystemServiceServlet { - - private final ServiceMap services; - - @Inject - public GuiceSystemServiceServlet(ServiceMap services) { - super(); - this.services = Preconditions.checkNotNull(services, "services"); - } - - @Override - protected T createService(Class serviceClass) { - return services.get(serviceClass); - } -} diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceSystemServiceServletModule.java b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceSystemServiceServletModule.java deleted file mode 100644 index f18776e0..00000000 --- a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/GuiceSystemServiceServletModule.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.guice; - -import com.google.api.server.spi.ServletInitializationParameters; -import com.google.inject.servlet.ServletModule; - -import java.util.Set; - -/** - * Extension of Guice servlet module which provides - * {@link #serveGuiceSystemServiceServlet(String, Iterable)} as a - * means to bind the {@link GuiceSystemServiceServlet} to the provided - * URL pattern and the {@code serviceClasses}. - *

- * Your application's {@link ServletModule} should extend this one and - * should call {@link #serveGuiceSystemServiceServlet(String, Iterable)} to - * serve the proxied system services. - * - * @author Joe Catalano - */ -@Deprecated -public abstract class GuiceSystemServiceServletModule extends ServletModule { - - /** - * Serves the {@link GuiceSystemServiceServlet} to the {@code urlPattern} for - * the {@code serviceClasses} services. Defaults for all init parameters are used. - * - * @param urlPattern the URL pattern to serve (i.e. /my/services/*) - * @param serviceClasses the annotated service classes to serve - */ - protected void serveGuiceSystemServiceServlet( - String urlPattern, Iterable> serviceClasses) { - ServletInitializationParameters initParameters = ServletInitializationParameters.builder() - .addServiceClasses(serviceClasses) - .build(); - serveGuiceSystemServiceServlet(urlPattern, initParameters); - } - - /** - * Serves the {@link GuiceSystemServiceServlet} to the {@code urlPattern} for the - * services specified in {@code initParameters}. The specified initialization - * parameters are used instead of the defaults. - * - * @param urlPattern the URL pattern to serve (i.e. /my/services/*) - * @param initParameters the initialization parameters to pass to the servlet - */ - protected void serveGuiceSystemServiceServlet( - String urlPattern, final ServletInitializationParameters initParameters) { - // Install system service module. - install(new SystemServiceModule() { - @Override - protected Set> getServiceClasses() { - return initParameters.getServiceClasses(); - } - }); - - super.serve(urlPattern).with(GuiceSystemServiceServlet.class, initParameters.asMap()); - } -} diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/Preconditions.java b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/Preconditions.java new file mode 100644 index 00000000..8e358bf5 --- /dev/null +++ b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/Preconditions.java @@ -0,0 +1,29 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.guice; + +/** + * Rather than shading all of Guava into an endpoints-framework-guice-all artifact, we include the + * necessary functionality in this small helper class to remove the dependency. + */ +final class Preconditions { + static T checkNotNull(T ref, String errorMessage) { + if (ref == null) { + throw new NullPointerException(errorMessage); + } + return ref; + } +} diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/ServiceMap.java b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/ServiceMap.java index ee569b02..ac69a6fb 100644 --- a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/ServiceMap.java +++ b/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/ServiceMap.java @@ -15,7 +15,6 @@ */ package com.google.api.server.spi.guice; -import com.google.common.base.Preconditions; import com.google.inject.Binder; import java.util.ArrayList; @@ -27,7 +26,7 @@ /** * A class which introduces heterogenous bindings for service providers. - * Called from {@link SystemServiceModule} and injected into {@link GuiceSystemServiceServlet}. + * Called from {@link EndpointsModule} and injected into {@link GuiceEndpointsServlet}. */ public class ServiceMap { diff --git a/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/EndpointsModuleTest.java b/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/EndpointsModuleTest.java index 35d2de9f..79f18087 100644 --- a/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/EndpointsModuleTest.java +++ b/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/EndpointsModuleTest.java @@ -118,7 +118,7 @@ public void testConfigureEndpoints_withoutInterceptor() { @Test public void testConfigureEndpoints_legacyServletWithServices() { - testServletClassWithServices(true, GuiceSystemServiceServlet.class); + testServletClassWithServices(true, GuiceEndpointsServlet.class); } @Test @@ -133,7 +133,7 @@ public void testConfigureEndpoints_defaultServletWithServices() { @Test public void testConfigureEndpoints_legacyServletWithInitParams() { - testServletClassWithInitParams(true, GuiceSystemServiceServlet.class); + testServletClassWithInitParams(true, GuiceEndpointsServlet.class); } @Test diff --git a/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/GuiceSystemServiceServletModuleTest.java b/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/GuiceSystemServiceServletModuleTest.java deleted file mode 100644 index 02f09b12..00000000 --- a/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/GuiceSystemServiceServletModuleTest.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.guice; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.server.spi.ServletInitializationParameters; -import com.google.api.server.spi.testing.TestEndpoint; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.inject.Binding; -import com.google.inject.Guice; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.servlet.InstanceFilterBinding; -import com.google.inject.servlet.InstanceServletBinding; -import com.google.inject.servlet.LinkedFilterBinding; -import com.google.inject.servlet.LinkedServletBinding; -import com.google.inject.servlet.ServletModuleTargetVisitor; -import com.google.inject.spi.DefaultBindingTargetVisitor; -import com.google.inject.spi.Elements; -import com.google.inject.spi.ProviderInstanceBinding; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.Collection; -import java.util.List; -import java.util.Set; - -/** - * Tests for {@link GuiceSystemServiceServletModule}. - */ -@RunWith(JUnit4.class) -public class GuiceSystemServiceServletModuleTest { - private static final String URL_PATTERN = "/my/path/"; - private static final Set> SERVICES = ImmutableSet.of(TestEndpoint.class); - private static final ServletInitializationParameters INIT_PARAMETERS = - ServletInitializationParameters.builder() - .addServiceClasses(SERVICES) - .setRestricted(false) - .build(); - private GuiceSystemServiceServletModule module; - - @Before - public void setUp() throws Exception { - module = new GuiceSystemServiceServletModule() { - @Override - protected void configureServlets() { - super.configureServlets(); - serveGuiceSystemServiceServlet(URL_PATTERN, INIT_PARAMETERS); - } - }; - Elements.getElements(module); - } - - /** - * Test method for - * {@link GuiceSystemServiceServletModule#serveGuiceSystemServiceServlet(String, ServletInitializationParameters)}. - */ - @Test - public void testServeGuiceSystemServiceServlet_withInterceptor() { - Injector injector = Guice.createInjector(module, new InterceptorModule()); - - Visitor visitor = new Visitor(); - for (Binding binding : injector.getAllBindings().values()) { - binding.acceptTargetVisitor(visitor); - } - - assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size()); - LinkedServletBinding servletBinding = visitor.linkedServlets.get(0); - assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern()); - assertEquals("Wrong initialization parameter provided", "false", - servletBinding.getInitParams().get("restricted")); - assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider); - - ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get(); - Collection services = serviceMap.getServices(); - assertEquals("Incorrect number of services provided", 1, services.size()); - assertEquals("Service not enhanced correctly.", SERVICES.toArray()[0], - ((Class) services.toArray()[0].getClass()).getSuperclass()); - } - - /** - * Test method for - * {@link GuiceSystemServiceServletModule#serveGuiceSystemServiceServlet(String, ServletInitializationParameters)}. - */ - @Test - public void testServeGuiceSystemServiceServlet_withoutInterceptor() { - Injector injector = Guice.createInjector(module, new DummyModule()); - - Visitor visitor = new Visitor(); - for (Binding binding : injector.getAllBindings().values()) { - binding.acceptTargetVisitor(visitor); - } - - assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size()); - LinkedServletBinding servletBinding = visitor.linkedServlets.get(0); - assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern()); - assertEquals("Wrong initialization parameter provided", "false", - servletBinding.getInitParams().get("restricted")); - assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider); - - ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get(); - Collection services = serviceMap.getServices(); - assertEquals("Incorrect number of services provided", 1, services.size()); - assertEquals("Service not provided correctly.", SERVICES.toArray()[0], - services.toArray()[0].getClass()); - } - - /** - * Test method for - * {@link GuiceSystemServiceServletModule#serveGuiceSystemServiceServlet(String, Iterable)}. - */ - @Test - public void testServeGuiceSystemServiceServlet_defaultInitParameters() { - module = new GuiceSystemServiceServletModule() { - @Override - protected void configureServlets() { - super.configureServlets(); - serveGuiceSystemServiceServlet(URL_PATTERN, SERVICES); - } - }; - Injector injector = Guice.createInjector(module, new DummyModule()); - - Visitor visitor = new Visitor(); - for (Binding binding : injector.getAllBindings().values()) { - binding.acceptTargetVisitor(visitor); - } - - assertEquals("Servlet not bound.", 1, visitor.linkedServlets.size()); - LinkedServletBinding servletBinding = visitor.linkedServlets.get(0); - assertEquals("URL pattern does not match", URL_PATTERN, servletBinding.getPattern()); - assertEquals("Wrong initialization parameter provided", "true", - servletBinding.getInitParams().get("restricted")); - assertNotNull("SystemService named provider not found.", visitor.systemServiceProvider); - - ServiceMap serviceMap = (ServiceMap) visitor.systemServiceProvider.getProvider().get(); - Collection services = serviceMap.getServices(); - assertEquals("Incorrect number of services provided", 1, services.size()); - assertEquals("Service not provided correctly.", SERVICES.toArray()[0], - services.toArray()[0].getClass()); - } - - /** - * Tests that services are injected. - */ - @Test - public void testInjected_withoutInterceptors() { - Injector injector = Guice.createInjector(module, new DummyModule()); - MockServlet mockServlet = new MockServlet(); - injector.injectMembers(mockServlet); - assertNotNull(mockServlet.services); - assertEquals(SERVICES.size(), mockServlet.services.getServices().size()); - } - - /** - * Tests that services are injected. - */ - @Test - public void testInjected_withInterceptors() { - Injector injector = Guice.createInjector(module, new InterceptorModule()); - MockServlet mockServlet = new MockServlet(); - injector.injectMembers(mockServlet); - assertNotNull(mockServlet.services); - assertEquals(SERVICES.size(), mockServlet.services.getServices().size()); - } - - private static class Visitor extends DefaultBindingTargetVisitor - implements ServletModuleTargetVisitor { - List linkedFilters = Lists.newArrayList(); - List linkedServlets = Lists.newArrayList(); - List instanceFilters = Lists.newArrayList(); - List instanceServlets = Lists.newArrayList(); - Binding systemServiceProvider = null; - - @Override - public Void visit(LinkedFilterBinding binding) { - linkedFilters.add(binding); - return null; - } - - @Override - public Void visit(InstanceFilterBinding binding) { - instanceFilters.add(binding); - return null; - } - - @Override - public Void visit(LinkedServletBinding binding) { - linkedServlets.add(binding); - return null; - } - - @Override - public Void visit(InstanceServletBinding binding) { - instanceServlets.add(binding); - return null; - } - - @Override - public Void visit(ProviderInstanceBinding providerInstanceBinding) { - extractSystemServiceBinding(providerInstanceBinding); - return null; - } - - @Override - protected Void visitOther(Binding binding) { - extractSystemServiceBinding(binding); - return null; - } - - private void extractSystemServiceBinding(Binding binding) { - Class clazz = binding.getKey().getTypeLiteral().getRawType(); - if (ServiceMap.class.equals(clazz)) { - systemServiceProvider = binding; - } - } - } - - private static class MockServlet { - @Inject - public ServiceMap services; - } -} diff --git a/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/GuiceSystemServiceServletTest.java b/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/GuiceSystemServiceServletTest.java deleted file mode 100644 index 3076f99a..00000000 --- a/endpoints-framework-guice/src/test/java/com/google/api/server/spi/guice/GuiceSystemServiceServletTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.guice; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import com.google.api.server.spi.config.Api; -import com.google.api.server.spi.config.model.ApiMethodConfig; -import com.google.api.server.spi.testing.Foo; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Module; -import com.google.inject.servlet.ServletModule; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import java.util.Set; - -import javax.inject.Inject; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; - -/** - * Tests for {@link GuiceSystemServiceServlet}. - */ -@RunWith(MockitoJUnitRunner.class) -public class GuiceSystemServiceServletTest { - @Mock protected ServletConfig servletConfig; - @Mock protected ServletContext servletContext; - @Mock protected ApiMethodConfig methodConfig; - - public static final String URL_PATTERN = "/api/service/*"; - - @Test - public void testCanCreateInjectedService() throws Exception { - Injector injector = Guice.createInjector(new TestServletModule(new InterceptorModule())); - GuiceSystemServiceServlet servlet = injector.getInstance(GuiceSystemServiceServlet.class); - when(servletConfig.getInitParameter("restricted")).thenReturn("false"); - when(servletConfig.getInitParameter("services")).thenReturn(InjectedEndpoint.class.getName()); - when(servletConfig.getInitParameter("clientIdWhitelistEnabled")).thenReturn(null); - when(servletConfig.getServletContext()).thenReturn(servletContext); - servlet.init(servletConfig); - assertEquals("testing", servlet.createService(InjectedEndpoint.class).getValue().getName()); - } - - @Api - private static class InjectedEndpoint { - @Inject - Foo foo; - - @SuppressWarnings("unused") - public Foo getValue() { - return foo; - } - } - - /** - * Test servlet module that binds the services as expected. - */ - private static class TestServletModule extends ServletModule { - - private final Module module; - - public TestServletModule(Module module) { - this.module = module; - } - - @Override - protected void configureServlets() { - bind(Foo.class).toInstance(new Foo() { - @Override - public String getName() { - return "testing"; - } - }); - install(module); - install(new SystemServiceModule() { // Bind services. - @Override - protected Set> getServiceClasses() { - return ImmutableSet.>of(InjectedEndpoint.class); - } - }); - serve(URL_PATTERN).with(GuiceSystemServiceServlet.class); - } - } -} diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/AppEngineUtil.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/AppEngineUtil.java index 4c52c73b..e3f4406b 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/AppEngineUtil.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/AppEngineUtil.java @@ -44,6 +44,11 @@ private interface AppPropertyReader { */ private static final String APP_YAML_PATH = "WEB-INF/app.yaml"; + /** + * Path in a staged WAR layout to app.yaml + */ + private static final String STAGED_APP_YAML_PATH = "app.yaml"; + /** * Given the directory of an App Engine application, returns its application id by checking * WEB-INF/app.yaml first and then WEB-INF/appengine-web.xml. @@ -117,7 +122,11 @@ public static String getDefaultHostnameFromAppId(String appId) { private static String getAppProperty(String appDir, AppPropertyReader reader) { // try app.yaml first because it may be newer - File appYamlFile = new File(new File(appDir), APP_YAML_PATH); + File appDirFile = new File(appDir); + File appYamlFile = new File(appDirFile, APP_YAML_PATH); + if (!appYamlFile.exists()) { + appYamlFile = new File(appDirFile, STAGED_APP_YAML_PATH); + } try { return AppYaml.parse(new FileReader(appYamlFile)).getApplication(); } catch (FileNotFoundException e) { diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsTool.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsTool.java index 3b60b996..ded5a58f 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsTool.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsTool.java @@ -111,11 +111,7 @@ public void printUsage(Action action) { System.out.println(action.getHelpString()); } - public static void main(String[] args) { - try { - new EndpointsTool().execute(args); - } catch (Exception e) { - System.err.println("Error: " + e.getMessage()); - } + public static void main(String[] args) throws Exception { + new EndpointsTool().execute(args); } } diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsToolAction.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsToolAction.java index 0e86e615..2380a822 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsToolAction.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/EndpointsToolAction.java @@ -223,7 +223,18 @@ protected boolean getDebug(Option debugOption) { } protected String getHostname(Option hostnameOption, String warPath) { - return getOptionOrDefault(hostnameOption, AppEngineUtil.getApplicationDefaultHostname(warPath)); + // Rather than using the getOptionOrDefault path here, which eagerly evaluates the default + // app hostname, do it manually for the lazy evaluation. In the Flex case, the app id is likely + // not in the app.yaml and is passed in manually (the quickstart does this already). Therefore, + // we don't want to evaluate it because it may throw an exception. + if (hostnameOption.getValue() != null) { + return hostnameOption.getValue(); + } + String defaultHostname = AppEngineUtil.getApplicationDefaultHostname(warPath); + if (defaultHostname != null) { + return defaultHostname; + } + return DEFAULT_HOSTNAME; } protected String getBasePath(Option basePathOption) { @@ -319,8 +330,7 @@ protected Option makeHostnameOption() { OPTION_HOSTNAME_SHORT, OPTION_HOSTNAME_LONG, "HOSTNAME", - "Sets the hostname for the generated OpenAPI document. Default is the app's default " - + "hostname."); + "Sets the hostname for the generated document. Default is the app's default hostname."); } protected Option makeBasePathOption() { @@ -328,8 +338,7 @@ protected Option makeBasePathOption() { OPTION_BASE_PATH_SHORT, OPTION_BASE_PATH_LONG, "BASE_PATH", - "Sets the base path for the generated OpenAPI document. Default is " + DEFAULT_BASE_PATH - + "."); + "Sets the base path for the generated document. Default is " + DEFAULT_BASE_PATH + "."); } /** diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GenApiConfigAction.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GenApiConfigAction.java index 3dadf3fd..6ce30559 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GenApiConfigAction.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GenApiConfigAction.java @@ -18,9 +18,11 @@ import static java.nio.charset.StandardCharsets.UTF_8; import com.google.api.server.spi.ServiceContext; +import com.google.api.server.spi.TypeLoader; import com.google.api.server.spi.config.ApiConfigException; import com.google.api.server.spi.config.jsonwriter.JsonConfigWriter; import com.google.api.server.spi.config.model.ApiConfig; +import com.google.api.server.spi.config.model.SchemaRepository; import com.google.api.server.spi.config.validation.ApiConfigValidator; import com.google.appengine.tools.util.Option; import com.google.common.io.Files; @@ -86,8 +88,10 @@ public Iterable genApiConfig( ClassLoader classLoader = new URLClassLoader(classPath, getClass().getClassLoader()); ApiConfig.Factory configFactory = new ApiConfig.Factory(); - ApiConfigValidator validator = new ApiConfigValidator(); - JsonConfigWriter jsonConfigWriter = new JsonConfigWriter(classLoader, validator); + TypeLoader typeLoader = new TypeLoader(classLoader); + SchemaRepository schemaRepository = new SchemaRepository(typeLoader); + ApiConfigValidator validator = new ApiConfigValidator(typeLoader, schemaRepository); + JsonConfigWriter jsonConfigWriter = new JsonConfigWriter(typeLoader, validator); ApiConfigGenerator generator = new AnnotationApiConfigGenerator(jsonConfigWriter, classLoader, configFactory); Map apiConfigs = generator.generateConfig( @@ -100,7 +104,7 @@ public Iterable genApiConfig( String apiConfigFileName = entry.getKey(); String apiConfigFileContent = entry.getValue(); String apiConfigFilePath = outputDir + "/" + apiConfigFileName; - Files.write(apiConfigFileContent, new File(apiConfigFilePath), UTF_8); + Files.asCharSink(new File(apiConfigFilePath), UTF_8).write(apiConfigFileContent); System.out.println("API configuration written to " + apiConfigFilePath); } } diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetClientLibAction.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetClientLibAction.java index 07434eba..c97ac3d8 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetClientLibAction.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetClientLibAction.java @@ -33,21 +33,18 @@ public class GetClientLibAction extends EndpointsToolAction { public static final String NAME = "get-client-lib"; private Option classPathOption = makeClassPathOption(); - private Option languageOption = makeLanguageOption(); - private Option outputOption = makeOutputOption(); - private Option warOption = makeWarOption(); - private Option buildSystemOption = makeBuildSystemOption(); - private Option debugOption = makeDebugOption(); + private Option hostnameOption = makeHostnameOption(); + private Option basePathOption = makeBasePathOption(); public GetClientLibAction() { super(NAME); setOptions(Arrays.asList(classPathOption, languageOption, outputOption, warOption, - buildSystemOption, debugOption)); + buildSystemOption, debugOption, hostnameOption, basePathOption)); setShortDescription("Generates a client library"); setExampleString(" get-client-lib --language=java --build_system=maven " + "com.google.devrel.samples.ttt.spi.BoardV1 com.google.devrel.samples.ttt.spi.ScoresV1"); @@ -62,8 +59,10 @@ public boolean execute() throws ClassNotFoundException, IOException, ApiConfigEx return false; } getClientLib(computeClassPath(warPath, getClassPath(classPathOption)), - getLanguage(languageOption), getOutputPath(outputOption), warPath, serviceClassNames, - getBuildSystem(buildSystemOption), getDebug(debugOption)); + getLanguage(languageOption), getOutputPath(outputOption), serviceClassNames, + getBuildSystem(buildSystemOption), getHostname(hostnameOption, warPath), + getBasePath(basePathOption), getDebug(debugOption) + ); return true; } @@ -73,16 +72,17 @@ public boolean execute() throws ClassNotFoundException, IOException, ApiConfigEx * @param classPath Class path to load service classes and their dependencies * @param language Language of the client library. Only "java" is supported right now * @param outputDirPath Directory to write output files into - * @param warPath Directory or file containing a WAR layout * @param serviceClassNames Array of service class names of the API * @param buildSystem The build system to use for the client library + * @param hostname The hostname to use + * @param basePath The base path to use * @param debug Whether or not to output intermediate output files */ public Object getClientLib(URL[] classPath, String language, String outputDirPath, - String warPath, List serviceClassNames, String buildSystem, boolean debug) - throws ClassNotFoundException, IOException, ApiConfigException { + List serviceClassNames, String buildSystem, String hostname, String basePath, + boolean debug) throws ClassNotFoundException, IOException, ApiConfigException { Map discoveryDocs = new GetDiscoveryDocAction().getDiscoveryDoc( - classPath, outputDirPath, warPath, serviceClassNames, debug); + classPath, outputDirPath, serviceClassNames, hostname, basePath, debug /* outputToDisk */); for (Map.Entry entry : discoveryDocs.entrySet()) { new GenClientLibAction().genClientLib(language, outputDirPath, entry.getValue(), buildSystem); } diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetDiscoveryDocAction.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetDiscoveryDocAction.java index 8ad979fb..88bc0fe2 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetDiscoveryDocAction.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetDiscoveryDocAction.java @@ -25,13 +25,18 @@ import com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.ApiKey; +import com.google.api.server.spi.config.model.SchemaRepository; +import com.google.api.server.spi.config.validation.ApiConfigValidator; import com.google.api.server.spi.discovery.DiscoveryGenerator; import com.google.api.server.spi.discovery.DiscoveryGenerator.DiscoveryContext; import com.google.api.server.spi.response.EndpointsPrettyPrinter; import com.google.api.services.discovery.model.RestDescription; import com.google.appengine.tools.util.Option; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; +import com.google.common.collect.Multimaps; import com.google.common.io.Files; import com.fasterxml.jackson.databind.ObjectWriter; @@ -53,18 +58,18 @@ public class GetDiscoveryDocAction extends EndpointsToolAction { public static final String NAME = "get-discovery-doc"; private Option classPathOption = makeClassPathOption(); - private Option outputOption = makeOutputOption(); - private Option warOption = makeWarOption(); - private Option debugOption = makeDebugOption(); + private Option hostnameOption = makeHostnameOption(); + private Option basePathOption = makeBasePathOption(); public GetDiscoveryDocAction() { super(NAME); - setOptions(Arrays.asList(classPathOption, outputOption, warOption, debugOption)); + setOptions(Arrays.asList(classPathOption, outputOption, warOption, debugOption, hostnameOption, + basePathOption)); setShortDescription("Generates discovery documents"); - setExampleString(" get-discovery-doc --format=rpc " + setExampleString(" get-discovery-doc " + "com.google.devrel.samples.ttt.spi.BoardV1 com.google.devrel.samples.ttt.spi.ScoresV1"); setHelpDisplayNeeded(true); } @@ -77,7 +82,8 @@ public boolean execute() throws ClassNotFoundException, IOException, ApiConfigEx return false; } getDiscoveryDoc(computeClassPath(warPath, getClassPath(classPathOption)), - getOutputPath(outputOption), warPath, serviceClassNames, getDebug(debugOption)); + getOutputPath(outputOption), serviceClassNames, getHostname(hostnameOption, warPath), + getBasePath(basePathOption), true); return true; } @@ -86,13 +92,14 @@ public boolean execute() throws ClassNotFoundException, IOException, ApiConfigEx * configuration, generating Discovery doc and generating client library into one. * @param classPath Class path to load service classes and their dependencies * @param outputDirPath Directory to write output files into - * @param warPath Directory or file containing a WAR layout * @param serviceClassNames Array of service class names of the API - * @param debug Whether or not to output intermediate output files + * @param hostname The hostname to use + * @param basePath The base path to use + * @param outputToDisk Whether or not to output discovery docs to disk */ public Map getDiscoveryDoc(URL[] classPath, String outputDirPath, - String warPath, List serviceClassNames, boolean debug) - throws ClassNotFoundException, IOException, ApiConfigException { + List serviceClassNames, String hostname, String basePath, boolean outputToDisk) + throws ClassNotFoundException, IOException, ApiConfigException { File outputDir = new File(outputDirPath); if (!outputDir.isDirectory()) { throw new IllegalArgumentException(outputDirPath + " is not a directory"); @@ -101,17 +108,30 @@ public Map getDiscoveryDoc(URL[] classPath, String outputDirPath ClassLoader classLoader = new URLClassLoader(classPath, getClass().getClassLoader()); ApiConfig.Factory configFactory = new ApiConfig.Factory(); TypeLoader typeLoader = new TypeLoader(classLoader); + SchemaRepository schemaRepository = new SchemaRepository(typeLoader); + ApiConfigValidator validator = new ApiConfigValidator(typeLoader, schemaRepository); DiscoveryGenerator discoveryGenerator = new DiscoveryGenerator(typeLoader); List apiConfigs = Lists.newArrayListWithCapacity(serviceClassNames.size()); + ImmutableListMultimap configsByKey = Multimaps.index(apiConfigs, + new Function() { + @Override + public ApiKey apply(ApiConfig input) { + return input.getApiKey(); + } + }); + for (ApiKey key : configsByKey.keys()) { + validator.validate(configsByKey.get(key)); + } ApiConfigLoader configLoader = new ApiConfigLoader( configFactory, typeLoader, new ApiConfigAnnotationReader(typeLoader.getAnnotationTypes())); - ServiceContext serviceContext = ServiceContext.create( - AppEngineUtil.getApplicationId(warPath), ServiceContext.DEFAULT_API_NAME); + ServiceContext serviceContext = ServiceContext.createFromHostname( + hostname, ServiceContext.DEFAULT_API_NAME); for (Class serviceClass : loadClasses(classLoader, serviceClassNames)) { apiConfigs.add(configLoader.loadConfiguration(serviceContext, serviceClass)); } DiscoveryGenerator.Result result = discoveryGenerator.writeDiscovery( - apiConfigs, new DiscoveryContext().setHostname(serviceContext.getAppHostName())); + apiConfigs, new DiscoveryContext().setHostname(hostname).setBasePath(basePath), + schemaRepository); ObjectWriter writer = ObjectMapperUtil.createStandardObjectMapper().writer(new EndpointsPrettyPrinter()); ImmutableMap.Builder builder = ImmutableMap.builder(); @@ -120,9 +140,11 @@ public Map getDiscoveryDoc(URL[] classPath, String outputDirPath String discoveryDocFilePath = outputDir + "/" + key.getName() + "-" + key.getVersion() + "-rest.discovery"; String docString = writer.writeValueAsString(entry.getValue()); - Files.write(docString, new File(discoveryDocFilePath), UTF_8); + if (outputToDisk) { + Files.write(docString, new File(discoveryDocFilePath), UTF_8); + System.out.println("API Discovery Document written to " + discoveryDocFilePath); + } builder.put(discoveryDocFilePath, docString); - System.out.println("API Discovery Document written to " + discoveryDocFilePath); } return builder.build(); } diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetOpenApiDocAction.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetOpenApiDocAction.java index 1e989478..dfcf47ac 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetOpenApiDocAction.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/GetOpenApiDocAction.java @@ -100,8 +100,9 @@ public String genOpenApiDoc( URL[] classPath, String outputFilePath, String hostname, String basePath, List serviceClassNames, boolean outputToDisk) throws ClassNotFoundException, IOException, ApiConfigException { - File outputDir = new File(outputFilePath).getParentFile(); - if (!outputDir.isDirectory()) { + File outputFile = new File(outputFilePath); + File outputDir = outputFile.getParentFile(); + if (!outputDir.isDirectory() || outputFile.isDirectory()) { throw new IllegalArgumentException(outputFilePath + " is not a file"); } @@ -124,7 +125,7 @@ public String genOpenApiDoc( String swaggerStr = Json.mapper().writer(new EndpointsPrettyPrinter()) .writeValueAsString(swagger); if (outputToDisk) { - Files.write(swaggerStr, new File(outputFilePath), UTF_8); + Files.write(swaggerStr, outputFile, UTF_8); System.out.println("OpenAPI document written to " + outputFilePath); } diff --git a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/WebXml.java b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/WebXml.java index 2e228ed2..79c97c2d 100644 --- a/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/WebXml.java +++ b/endpoints-framework-tools/src/main/java/com/google/api/server/spi/tools/WebXml.java @@ -1,7 +1,6 @@ package com.google.api.server.spi.tools; import com.google.api.server.spi.EndpointsServlet; -import com.google.api.server.spi.SystemServiceServlet; import com.google.common.base.Strings; import com.google.common.collect.Lists; @@ -41,7 +40,7 @@ public static WebXml parse(File webXml) /** * Find endpoint service classes defined in the web.xml. * - * Looks for a servlet with servlet-class = {@link SystemServiceServlet} or + * Looks for a servlet with servlet-class = SystemServiceServlet or * {@link EndpointsServlet}. * Does NOT handle the case of multiple mappings to the same servlet-class, * it will only return the result to first one that defines the "services" init-param @@ -52,7 +51,7 @@ public static WebXml parse(File webXml) public List endpointsServiceClasses() { XPath xpath = XPathFactory.newInstance().newXPath(); String findService = "/web-app/servlet" + "[" - + "servlet-class = '" + SystemServiceServlet.class.getName() + "'" + + "servlet-class = 'com.google.api.server.spi.SystemServiceServlet'" + " or " + "servlet-class = '" + EndpointsServlet.class.getName() + "'" + "]/init-param[param-name = 'services']/param-value/text()"; diff --git a/endpoints-framework-tools/src/main/resources/com/google/api/server/spi/tools/testing/fake-discovery-doc-rest.json b/endpoints-framework-tools/src/main/resources/com/google/api/server/spi/tools/testing/fake-discovery-doc-rest.json index f5c4ffb5..3bd712c6 100644 --- a/endpoints-framework-tools/src/main/resources/com/google/api/server/spi/tools/testing/fake-discovery-doc-rest.json +++ b/endpoints-framework-tools/src/main/resources/com/google/api/server/spi/tools/testing/fake-discovery-doc-rest.json @@ -5,8 +5,8 @@ "version": "v1", "description": "App Engine GuestBook API", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "labels": [ "labs" diff --git a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/AnnotationApiConfigGeneratorTest.java b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/AnnotationApiConfigGeneratorTest.java index 40f985c9..20316a42 100644 --- a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/AnnotationApiConfigGeneratorTest.java +++ b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/AnnotationApiConfigGeneratorTest.java @@ -131,7 +131,7 @@ public void testEndpointWithOnlyDefaultConfiguration() throws Exception { JsonNode root = objectMapper.readValue(apiConfigSource, JsonNode.class); verifyApi(root, "thirdParty.api", "https://myapp.appspot.com/_ah/api", - "myapi", "v1", "", "https://myapp.appspot.com/_ah/spi", false, false); + "myapi", "v1", "", "https://myapp.appspot.com/_ah/spi", false, true); JsonNode methodGetFoo = root.path("methods").path("myapi.endpoint0.getFoo"); verifyMethod(methodGetFoo, "foo/{id}", HttpMethod.GET, Endpoint0.class.getName() + ".getFoo", @@ -1922,7 +1922,7 @@ public void foo(R param) {} @Test public void testRequestDoesContainMap() throws Exception { - checkRequestIsNotEmpty(new SimpleFoo>() {}.getClass()); + checkRequestIsNotEmpty(new SimpleFoo>() {}.getClass()); } @Test diff --git a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetClientLibActionTest.java b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetClientLibActionTest.java index 3bb2f620..75608cd1 100644 --- a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetClientLibActionTest.java +++ b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetClientLibActionTest.java @@ -42,10 +42,11 @@ public class GetClientLibActionTest extends EndpointsToolTest { private URL[] classPath; private String language; private String outputDirPath; - private String warPath; private List serviceClassNames; private String buildSystem; private boolean debugOutput; + private String hostname; + private String basePath; private GetClientLibAction testAction; @Override @@ -61,19 +62,21 @@ public void setUp() throws Exception { classPath = null; language = null; outputDirPath = null; - warPath = null; serviceClassNames = null; + hostname = null; + basePath = null; testAction = new GetClientLibAction() { @Override public Object getClientLib( - URL[] c, String l, String o, String w, List s, String b, boolean d) { + URL[] c, String l, String o, List s, String bs, String h, String bp, boolean d) { classPath = c; language = l; outputDirPath = o; - warPath = w; serviceClassNames = s; - buildSystem = b; + buildSystem = bs; + hostname = h; + basePath = bp; debugOutput = d; return null; } @@ -82,8 +85,9 @@ public Object getClientLib( @Test public void testMissingOption() throws Exception { - tool.execute(new String[]{ - GetClientLibAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + tool.execute(new String[]{GetClientLibAction.NAME, + option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com", "MyService"}); assertFalse(usagePrinted); assertThat(Lists.newArrayList(classPath)) @@ -94,7 +98,6 @@ GetClientLibAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "c .toURL()); assertEquals(EndpointsToolAction.DEFAULT_LANGUAGE, language); assertEquals(EndpointsToolAction.DEFAULT_OUTPUT_PATH, outputDirPath); - assertEquals(EndpointsToolAction.DEFAULT_WAR_PATH, warPath); assertStringsEqual(Arrays.asList("MyService"), serviceClassNames); } @@ -108,10 +111,11 @@ GetClientLibAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), @Test public void testGetClientLib() throws Exception { - tool.execute( - new String[]{GetClientLibAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), - "classPath", option(EndpointsToolAction.OPTION_LANGUAGE_SHORT), "java", + tool.execute(new String[]{GetClientLibAction.NAME, + option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + option(EndpointsToolAction.OPTION_LANGUAGE_SHORT), "java", option(EndpointsToolAction.OPTION_OUTPUT_DIR_SHORT), "outputDir", + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com", "MyService", "MyService2"}); assertFalse(usagePrinted); assertThat(Lists.newArrayList(classPath)) @@ -122,19 +126,20 @@ public void testGetClientLib() throws Exception { .toURL()); assertEquals("java", language); assertEquals("outputDir", outputDirPath); - assertEquals(EndpointsToolAction.DEFAULT_WAR_PATH, warPath); assertStringsEqual(Arrays.asList("MyService", "MyService2"), serviceClassNames); assertEquals(null, buildSystem); assertFalse(debugOutput); + assertThat(basePath).isEqualTo("/_ah/api"); } @Test public void testGetClientLibWithBuildSystem() throws Exception { - tool.execute( - new String[]{GetClientLibAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), - "classPath", option(EndpointsToolAction.OPTION_LANGUAGE_SHORT), "java", + tool.execute(new String[]{GetClientLibAction.NAME, + option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + option(EndpointsToolAction.OPTION_LANGUAGE_SHORT), "java", option(EndpointsToolAction.OPTION_OUTPUT_DIR_SHORT), "outputDir", option(EndpointsToolAction.OPTION_BUILD_SYSTEM_SHORT), "maven", + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com", "MyService", "MyService2"}); assertFalse(usagePrinted); assertThat(Lists.newArrayList(classPath)) @@ -145,7 +150,6 @@ public void testGetClientLibWithBuildSystem() throws Exception { .toURL()); assertEquals("java", language); assertEquals("outputDir", outputDirPath); - assertEquals(EndpointsToolAction.DEFAULT_WAR_PATH, warPath); assertStringsEqual(Arrays.asList("MyService", "MyService2"), serviceClassNames); assertEquals("maven", buildSystem); assertFalse(debugOutput); @@ -153,11 +157,14 @@ public void testGetClientLibWithBuildSystem() throws Exception { @Test public void testGetClientLibWithDebugOutput() throws Exception { - tool.execute( - new String[]{GetClientLibAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), - "classPath", option(EndpointsToolAction.OPTION_LANGUAGE_SHORT), "java", + tool.execute(new String[]{GetClientLibAction.NAME, + option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + option(EndpointsToolAction.OPTION_LANGUAGE_SHORT), "java", option(EndpointsToolAction.OPTION_OUTPUT_DIR_SHORT), "outputDir", - option(EndpointsToolAction.OPTION_DEBUG, false), "MyService", "MyService2"}); + option(EndpointsToolAction.OPTION_DEBUG, false), + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com", + option(EndpointsToolAction.OPTION_BASE_PATH_SHORT), "/api", + "MyService", "MyService2"}); assertFalse(usagePrinted); assertThat(Lists.newArrayList(classPath)) .containsExactly(new File("classPath").toURI().toURL(), @@ -167,9 +174,10 @@ public void testGetClientLibWithDebugOutput() throws Exception { .toURL()); assertEquals("java", language); assertEquals("outputDir", outputDirPath); - assertEquals(EndpointsToolAction.DEFAULT_WAR_PATH, warPath); assertStringsEqual(Arrays.asList("MyService", "MyService2"), serviceClassNames); assertEquals(null, buildSystem); assertTrue(debugOutput); + assertThat(hostname).isEqualTo("foo.com"); + assertThat(basePath).isEqualTo("/api"); } } diff --git a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetDiscoveryDocActionTest.java b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetDiscoveryDocActionTest.java index 9edb055d..ea40be08 100644 --- a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetDiscoveryDocActionTest.java +++ b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/GetDiscoveryDocActionTest.java @@ -41,10 +41,11 @@ public class GetDiscoveryDocActionTest extends EndpointsToolTest { private URL[] classPath; private String outputDirPath; - private String warPath; private List serviceClassNames; private GetDiscoveryDocAction testAction; - private boolean debugOutput; + private String hostname; + private String basePath; + private boolean outputToDisk; @Override protected void addTestAction(Map commands) { @@ -58,18 +59,20 @@ public void setUp() throws Exception { usagePrinted = false; classPath = null; outputDirPath = null; - warPath = null; serviceClassNames = null; + hostname = null; + basePath = null; testAction = new GetDiscoveryDocAction() { @Override public Map getDiscoveryDoc( - URL[] c, String o, String w, List s, boolean d) { + URL[] c, String o, List s, String h, String b, boolean d) { classPath = c; outputDirPath = o; - warPath = w; serviceClassNames = s; - debugOutput = d; + hostname = h; + basePath = b; + outputToDisk = d; return null; } }; @@ -77,9 +80,10 @@ public Map getDiscoveryDoc( @Test public void testMissingOption() throws Exception { - tool.execute(new String[]{ - GetDiscoveryDocAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), - "classPath", "MyService"}); + tool.execute(new String[]{GetDiscoveryDocAction.NAME, + option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com", + "MyService"}); assertFalse(usagePrinted); assertThat(Lists.newArrayList(classPath)) .containsExactly(new File("classPath").toURI().toURL(), @@ -88,15 +92,15 @@ GetDiscoveryDocAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), .toURI() .toURL()); assertEquals(EndpointsToolAction.DEFAULT_OUTPUT_PATH, outputDirPath); - assertEquals(EndpointsToolAction.DEFAULT_WAR_PATH, warPath); assertStringsEqual(Arrays.asList("MyService"), serviceClassNames); } @Test public void testMissingArgument() throws Exception { - tool.execute(new String[]{ - GetDiscoveryDocAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), - "classPath", option(EndpointsToolAction.OPTION_OUTPUT_DIR_SHORT), "outputDir"}); + tool.execute(new String[]{GetDiscoveryDocAction.NAME, + option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", + option(EndpointsToolAction.OPTION_OUTPUT_DIR_SHORT), "outputDir", + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com"}); assertTrue(usagePrinted); } @@ -105,6 +109,8 @@ public void testGetDiscoveryDoc() throws Exception { tool.execute(new String[]{GetDiscoveryDocAction.NAME, option(EndpointsToolAction.OPTION_CLASS_PATH_SHORT), "classPath", option(EndpointsToolAction.OPTION_OUTPUT_DIR_SHORT), "outputDir", + option(EndpointsToolAction.OPTION_HOSTNAME_SHORT), "foo.com", + option(EndpointsToolAction.OPTION_BASE_PATH_SHORT), "/api", "MyService", "MyService2"}); assertFalse(usagePrinted); assertThat(Lists.newArrayList(classPath)) @@ -114,8 +120,9 @@ public void testGetDiscoveryDoc() throws Exception { .toURI() .toURL()); assertEquals("outputDir", outputDirPath); - assertEquals(EndpointsToolAction.DEFAULT_WAR_PATH, warPath); assertStringsEqual(Arrays.asList("MyService", "MyService2"), serviceClassNames); - assertFalse(debugOutput); + assertTrue(outputToDisk); + assertThat(hostname).isEqualTo("foo.com"); + assertThat(basePath).isEqualTo("/api"); } } diff --git a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/WebXmlTest.java b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/WebXmlTest.java index acf9bc0d..dcf00e90 100644 --- a/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/WebXmlTest.java +++ b/endpoints-framework-tools/src/test/java/com/google/api/server/spi/tools/WebXmlTest.java @@ -1,7 +1,6 @@ package com.google.api.server.spi.tools; import com.google.api.server.spi.EndpointsServlet; -import com.google.api.server.spi.SystemServiceServlet; import org.junit.Assert; import org.junit.Test; @@ -158,7 +157,8 @@ public void testServiceClasses_noMatchingTag() public void testServiceClasses_undefinedBehaviorMultipleSystemServiceServlets() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException { WebXml webxml = new WebXmlBuilder() - .servlet("SomeJunkServlet", SystemServiceServlet.class.getName(), "com.test.JunkEndpoint") + .servlet("SomeJunkServlet", "com.google.api.server.spi.SystemServiceServlet", + "com.test.JunkEndpoint") .endpointsServlet("com.test.EndpointOne") .servletMapping("SomeJunkServlet", WebXmlBuilder.SPI_URL) .endpointsServletMapping() @@ -210,7 +210,8 @@ static class WebXmlBuilder { static final String SPI_URL = "/_ah/spi"; static final String API_URL = "/_ah/api"; static final String SYSTEM_SERVICE_SERVLET = "SystemServiceServlet"; - static final String SYSTEM_SERVICE_SERVLET_CLASS = SystemServiceServlet.class.getName(); + static final String SYSTEM_SERVICE_SERVLET_CLASS = + "com.google.api.server.spi.SystemServiceServlet"; static final String ENDPOINTS_SERVLET = "EndpointsServlet"; static final String ENDPOINTS_SERVLET_CLASS = EndpointsServlet.class.getName(); diff --git a/endpoints-framework/build.gradle b/endpoints-framework/build.gradle index e563cdec..1645cea6 100644 --- a/endpoints-framework/build.gradle +++ b/endpoints-framework/build.gradle @@ -80,12 +80,13 @@ dependencies { // leading to test failures. transitive = false } - compile group: 'javax.servlet', name: 'servlet-api', version: servletVersion compile group: 'com.google.guava', name: 'guava', version: guavaVersion compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: jacksonVersion compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: jacksonVersion compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: jacksonVersion compile group: 'com.google.appengine', name: 'appengine-api-1.0-sdk', version: appengineVersion + compile group: 'com.google.flogger', name: 'flogger', version: floggerVersion + runtime group: 'com.google.flogger', name: 'flogger-system-backend', version: floggerVersion compile(group: 'com.google.http-client', name: 'google-http-client-jackson2', version: apiclientVersion) { exclude group: 'com.google.guava', module: 'guava-jdk5' exclude group: 'com.fasterxml.jackson.core', module: 'jackson-core' @@ -97,10 +98,12 @@ dependencies { exclude group: 'com.google.guava', module: 'guava-jdk5' } compile group: 'com.google.code.findbugs', name: 'jsr305', version: findbugsVersion + compile group: 'commons-fileupload', name: 'commons-fileupload', version: fileUploadVersion compile group: 'io.swagger', name: 'swagger-models', version: swaggerVersion compile group: 'io.swagger', name: 'swagger-core', version: swaggerVersion compile group: 'org.slf4j', name: 'slf4j-nop', version: slf4jVersion + compileOnly group: 'javax.servlet', name: 'servlet-api', version: servletVersion compileOnly "com.google.auto.value:auto-value:1.2" apt "com.google.auto.value:auto-value:1.2" @@ -113,3 +116,4 @@ dependencies { testCompile group: 'org.springframework', name: 'spring-test', version: springtestVersion testCompile group: 'com.google.guava', name: 'guava-testlib', version: guavaVersion } + diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/BackendProperties.java b/endpoints-framework/src/main/java/com/google/api/server/spi/BackendProperties.java index 51aeb491..2263b302 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/BackendProperties.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/BackendProperties.java @@ -15,9 +15,9 @@ */ package com.google.api.server.spi; -import com.google.appengine.api.utils.SystemProperty; import com.google.common.annotations.VisibleForTesting; +import com.google.common.flogger.FluentLogger; import java.util.logging.Level; import java.util.logging.Logger; @@ -28,12 +28,14 @@ * generally come from environment variables. */ public class BackendProperties { - private static final Logger logger = Logger.getLogger(BackendProperties.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); - public static final String PROJECT_NUMBER_PROPERTY = "GOOGLE_PROJECT_NUMBER"; - public static final long PROJECT_NUMBER_UNKNOWN = 0L; + static final String APP_ID_PROPERTY = "com.google.appengine.application.id"; + static final String PROJECT_NUMBER_PROPERTY = "GOOGLE_PROJECT_NUMBER"; + static final String GCLOUD_PROJECT_PROPERTY = "GCLOUD_PROJECT"; + static final long PROJECT_NUMBER_UNKNOWN = 0L; - public static final String PROJECT_ID_PROPERTY = "GOOGLE_PROJECT_ID"; + static final String PROJECT_ID_PROPERTY = "GOOGLE_PROJECT_ID"; // Inject an override to change env values read for tests. @VisibleForTesting @@ -69,7 +71,7 @@ public long getProjectNumber() { try { return Long.parseLong(property); } catch (NumberFormatException e) { - logger.log(Level.WARNING, "Project number (%s) is not an int64.", property); + logger.atWarning().log("Project number (%s) is not an int64.", property); return PROJECT_NUMBER_UNKNOWN; } } else { @@ -96,7 +98,11 @@ public String getProjectId() { @Nullable public String getApplicationId() { if (isOnAppEngine()) { - return SystemProperty.applicationId.get(); + String appId = System.getProperty(APP_ID_PROPERTY); + if (appId == null) { + appId = envReader.getenv(GCLOUD_PROJECT_PROPERTY); + } + return appId; } else { return null; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/BackendService.java b/endpoints-framework/src/main/java/com/google/api/server/spi/BackendService.java deleted file mode 100644 index 5b2610bb..00000000 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/BackendService.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi; - -import com.google.api.server.spi.config.ApiConfigException; -import com.google.api.server.spi.config.Named; -import com.google.api.server.spi.response.BadRequestException; -import com.google.api.server.spi.response.InternalServerErrorException; -import com.google.api.server.spi.response.NotFoundException; -import com.google.api.server.spi.response.ServiceUnavailableException; -import com.google.appengine.api.appidentity.AppIdentityService; -import com.google.appengine.api.appidentity.AppIdentityServiceFactory; -import com.google.appengine.api.urlfetch.HTTPHeader; -import com.google.appengine.api.urlfetch.HTTPMethod; -import com.google.appengine.api.urlfetch.HTTPRequest; -import com.google.appengine.api.urlfetch.HTTPResponse; -import com.google.appengine.api.urlfetch.URLFetchService; -import com.google.appengine.api.urlfetch.URLFetchServiceFactory; -import com.google.apphosting.api.ApiProxy; -import com.google.apphosting.api.ApiProxy.Environment; -import com.google.common.annotations.VisibleForTesting; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The reserved API backend service used for Google's own purposes. - */ -public class BackendService { - - private static final Logger logger = Logger.getLogger(BackendService.class.getName()); - private static final Logger frameworkLogger = Logger.getLogger("com.google.api.server.spi"); - - @VisibleForTesting - static final String CONFIG_RELOAD_SCOPE = - "https://www.googleapis.com/auth/endpoints.config.reload"; - - private final String minorVersion; - private final SystemService systemService; - private final BackendProperties backendProperties; - - public BackendService(SystemService systemService) { - this(getMinorVersion(), systemService, new BackendProperties()); - } - - public BackendService(String minorVersion, SystemService systemService, - BackendProperties backendProperties) { - this.minorVersion = minorVersion; - this.systemService = systemService; - this.backendProperties = backendProperties; - } - - private static String getMajorVersion() { - if (!EnvUtil.isRunningOnAppEngine()) { - // Version only exists on App Engine. - return null; - } - - Environment env = ApiProxy.getCurrentEnvironment(); - return env == null ? null : env.getVersionId().split("\\.")[0]; - } - - private static String getMinorVersion() { - if (!EnvUtil.isRunningOnAppEngine()) { - // Version only exists on App Engine. - return null; - } - - Environment env = ApiProxy.getCurrentEnvironment(); - return env == null ? null : env.getVersionId().split("\\.")[1]; - } - - /** - * Reads all WEB-INF/*.api files and return their contents in a list of strings. - * @param expectedAppRevision App revision client expects to see - * @throws InternalServerErrorException - * @throws BadRequestException - */ - public Collection getApiConfigs(@Named("appRevision") String expectedAppRevision) - throws InternalServerErrorException, BadRequestException { - if (minorVersion != null && expectedAppRevision != null) { - if (!minorVersion.equals(expectedAppRevision)) { - throw new BadRequestException("API backend's app revision '" + minorVersion + - "' not the same as expected '" + expectedAppRevision + "'"); - } - } - - try { - return systemService.getApiConfigs().values(); - } catch (ApiConfigException e) { - logger.log(Level.SEVERE, "Could not generate configuration.", e); - throw new InternalServerErrorException(e); - } - } - - /** - * Initiates a request to reload the current application's API configs. Does not work in local - * development. - * @throws ServiceUnavailableException - */ - public static void reloadApiConfigs() throws ServiceUnavailableException, NotFoundException { - if (!EnvUtil.isRunningOnAppEngine()) { - // TODO: Write a generic reload implementation that works without App Engine. - throw new NotFoundException("reload only available on App Engine"); - } - - reloadApiConfigs(getHostnameWithMajorVersion(getMajorVersion()), getMinorVersion(), - URLFetchServiceFactory.getURLFetchService()); - } - - @VisibleForTesting - static void reloadApiConfigs(String hostname, String minorVersion, URLFetchService fetcher) - throws ServiceUnavailableException { - if (hostname == null) { - throw new ServiceUnavailableException("invalid hostname"); - } - List scopes = new ArrayList(); - scopes.add(CONFIG_RELOAD_SCOPE); - AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); - AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); - try { - String reloadUrl = "https://" + hostname + "/_ah/api/discovery/v1/apis/reload" - + makeReloadQueryParameters(minorVersion); - URL url = new URL(reloadUrl); - HTTPRequest reloadRequest = new HTTPRequest(url, HTTPMethod.POST); - reloadRequest.addHeader(new HTTPHeader("Content-Type", "application/json")); - reloadRequest.addHeader( - new HTTPHeader("Authorization", "OAuth " + accessToken.getAccessToken())); - HTTPResponse reloadResponse = fetcher.fetch(reloadRequest); - if (reloadResponse.getResponseCode() != 200) { - throw new ServiceUnavailableException( - "Request returned HTTP " + reloadResponse.getResponseCode()); - } - } catch (IOException e) { - throw new ServiceUnavailableException(e); - } - } - - private static String getHostnameWithMajorVersion(String majorVersion) { - return getHostnameWithMajorVersion(getDefaultHostname(), majorVersion); - } - - // VisibleForTesting - static String getHostnameWithMajorVersion(String defaultHostname, String majorVersion) { - String hostnamePrefix = majorVersion != null ? majorVersion + "-dot-" : ""; - return hostnamePrefix + defaultHostname; - } - - private static String getDefaultHostname() { - Environment env = ApiProxy.getCurrentEnvironment(); - return env != null ? (String) env.getAttributes() - .get("com.google.appengine.runtime.default_version_hostname") - : null; - } - - private static String makeReloadQueryParameters(String minorVersion) { - if (minorVersion != null) { - return "?appMinorVersion=" + minorVersion; - } - return ""; - } - - @VisibleForTesting - static class MessageEntry { - private String level; - private String message; - - public String getLevel() { - return level; - } - - public void setLevel(String level) { - this.level = level; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - } - - private static final Map levelMap = new HashMap() {{ - put("info", Level.INFO); - put("warning", Level.WARNING); - put("error", Level.SEVERE); - }}; - - /** - * Writes an array of messages to local log, each specified at its own level. - */ - public void logMessages(@Named("messages") MessageEntry[] messages) { - for (MessageEntry entry : messages) { - Level level = levelMap.get(entry.getLevel()); - log(level == null ? Level.INFO : level, entry.getMessage()); - } - } - - /** - * Resource object for general backend properties. - */ - public static class Properties { - private long projectNumber; - private String projectId; - - public Properties(long projectNumber, String projectId) { - this.projectNumber = projectNumber; - this.projectId = projectId; - } - - public long getProjectNumber() { - return projectNumber; - } - - public String getProjectId() { - return projectId; - } - } - - /** - * Used to retrieve general properties of the backend such as expected project id. - */ - public Properties getProperties() { - return new Properties(backendProperties.getProjectNumber(), backendProperties.getProjectId()); - } - - @VisibleForTesting - void log(Level level, String message) { - if (EnvUtil.isRunningOnAppEngine()) { - logWithAppEngine(level, message); - } else { - logLocal(level, message); - } - } - - private static final Map internalLevels = - new HashMap() {{ - put(Level.INFO, ApiProxy.LogRecord.Level.info); - put(Level.WARNING, ApiProxy.LogRecord.Level.warn); - put(Level.SEVERE, ApiProxy.LogRecord.Level.error); - }}; - - private void logWithAppEngine(Level level, String message) { - ApiProxy.LogRecord.Level internalLevel = internalLevels.get(level); - ApiProxy.LogRecord record = new ApiProxy.LogRecord( - internalLevel == null ? ApiProxy.LogRecord.Level.info : internalLevel, - System.currentTimeMillis() * 1000, message); - ApiProxy.log(record); - } - - private void logLocal(Level level, String message) { - // These messages are not coming from BackendService, but from the server. Log them as coming - // from the framework as a whole instead of from this specific method or class. - frameworkLogger.logp(level, null, null, message); - } -} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/ConfiguredObjectMapper.java b/endpoints-framework/src/main/java/com/google/api/server/spi/ConfiguredObjectMapper.java index c31fe43f..03db8af8 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/ConfiguredObjectMapper.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/ConfiguredObjectMapper.java @@ -28,6 +28,7 @@ import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.common.flogger.FluentLogger; import java.util.Map; import java.util.Objects; import java.util.logging.Level; @@ -83,8 +84,7 @@ public static Builder builder() { * A builder for constructing {@link ConfiguredObjectMapper} instances. */ public static class Builder { - private static final Logger logger = - Logger.getLogger(Builder.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private int maxCacheSize; private ApiSerializationConfig config; @@ -159,9 +159,9 @@ public ConfiguredObjectMapper build() { } cache.put(key, instance); - logger.log(Level.FINE, "Cache miss, created ObjectMapper"); + logger.atFine().log("Cache miss, created ObjectMapper"); } else { - logger.log(Level.FINE, "Cache hit, reusing ObjectMapper"); + logger.atFine().log("Cache hit, reusing ObjectMapper"); } return instance; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsContext.java b/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsContext.java index 6e1ac233..205b8361 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsContext.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsContext.java @@ -27,12 +27,14 @@ public class EndpointsContext extends DispatcherContext { private final HttpServletRequest request; private final HttpServletResponse response; + private final boolean prettyPrint; public EndpointsContext(String httpMethod, String path, HttpServletRequest request, - HttpServletResponse response) { + HttpServletResponse response, boolean prettyPrint) { super(httpMethod, path); this.request = Preconditions.checkNotNull(request, "request"); this.response = Preconditions.checkNotNull(response, "response"); + this.prettyPrint = prettyPrint; } public HttpServletRequest getRequest() { @@ -42,4 +44,8 @@ public HttpServletRequest getRequest() { public HttpServletResponse getResponse() { return response; } + + public boolean isPrettyPrintEnabled() { + return prettyPrint; + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsServlet.java b/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsServlet.java index 5f9852e2..5f32bc6c 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsServlet.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/EndpointsServlet.java @@ -39,8 +39,7 @@ import javax.servlet.http.HttpServletResponse; /** - * A handler for proxy-less API serving. Unlike {@link SystemServiceServlet}, which speaks the - * JSON-based Lily protocol, this servlet understands and replies in both JSON-REST and JSON-RPC. + * A handler for proxy-less API serving. This servlet understands and replies in JSON-REST. */ public class EndpointsServlet extends HttpServlet { private static final String EXPLORER_PATH = "explorer"; @@ -60,6 +59,14 @@ public void init(ServletConfig config) throws ServletException { this.corsHandler = new CorsHandler(); } + protected ServletInitializationParameters getInitParameters() { + return initParameters; + } + + protected SystemService getSystemService() { + return systemService; + } + @Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { String method = getRequestMethod(request); @@ -68,7 +75,8 @@ public void service(HttpServletRequest request, HttpServletResponse response) th } else { String path = Strings.stripSlash( request.getRequestURI().substring(request.getServletPath().length())); - EndpointsContext context = new EndpointsContext(method, path, request, response); + EndpointsContext context = new EndpointsContext(method, path, request, response, + initParameters.isPrettyPrintEnabled()); if (!dispatcher.dispatch(method, path, context)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().append("Not Found"); @@ -99,9 +107,8 @@ private PathDispatcher createDispatcher() { MethodConfigMap methods = apiConfig.getApiClassConfig().getMethods(); for (Entry methodEntry : methods.entrySet()) { if (!methodEntry.getValue().isIgnored()) { - handlersBuilder.add( - new EndpointsMethodHandler(initParameters, getServletContext(), methodEntry.getKey(), - apiConfig, methodEntry.getValue(), systemService)); + handlersBuilder.add(createEndpointsMethodHandler(methodEntry.getKey(), + methodEntry.getValue())); } } } @@ -122,9 +129,8 @@ private SystemService createSystemService(ClassLoader classLoader, try { SystemService.Builder builder = SystemService.builder() .withDefaults(classLoader) - .setStandardConfigLoader(classLoader, false) + .setStandardConfigLoader(classLoader) .setIllegalArgumentIsBackendError(initParameters.isIllegalArgumentBackendError()) - .setBackendServiceEnabled(false) .setDiscoveryServiceEnabled(true); for (Class serviceClass : initParameters.getServiceClasses()) { builder.addService(serviceClass, createService(serviceClass)); @@ -135,6 +141,12 @@ private SystemService createSystemService(ClassLoader classLoader, } } + protected EndpointsMethodHandler createEndpointsMethodHandler(EndpointMethod method, + ApiMethodConfig methodConfig) { + return new EndpointsMethodHandler(initParameters, getServletContext(), method, + methodConfig, systemService); + } + /** * Creates a new instance of the specified service class. * diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/EnvUtil.java b/endpoints-framework/src/main/java/com/google/api/server/spi/EnvUtil.java index 76535e24..49b9c2cb 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/EnvUtil.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/EnvUtil.java @@ -15,11 +15,6 @@ */ package com.google.api.server.spi; -import com.google.appengine.api.modules.ModulesService; -import com.google.appengine.api.modules.ModulesServiceFactory; -import com.google.apphosting.api.ApiProxy; -import com.google.apphosting.api.ApiProxy.Environment; - /** * Utililty for runtime environment related operations, such as checking whether current Endpoints * backend is running on App Engine. @@ -61,22 +56,4 @@ public static boolean isRunningOnAppEngineProd() { String property = System.getProperty(ENV_APPENGINE_RUNTIME); return property != null && property.equals(ENV_APPENGINE_PROD); } - - /** - * Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on - * development server, or 2) "app_id.appspot.com" if running on external app engine prod, or - * 3) "app_id.googleplex.com" if running as Google 1st party Endpoints API, or 4) {@code null} if - * not running on App Engine (e.g. Tornado Endpoints API). - */ - public static String getAppHostName() { - if (!isRunningOnAppEngine()) { - return null; - } - Environment env = ApiProxy.getCurrentEnvironment(); - if (env != null) { // if env is null, ModulesService calls will NPE - ModulesService modules = ModulesServiceFactory.getModulesService(); - return modules.getVersionHostname(modules.getCurrentModule(), modules.getCurrentVersion()); - } - return null; - } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/ObjectMapperUtil.java b/endpoints-framework/src/main/java/com/google/api/server/spi/ObjectMapperUtil.java index 6ebf25d1..331dcc86 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/ObjectMapperUtil.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/ObjectMapperUtil.java @@ -18,7 +18,7 @@ import com.google.api.server.spi.config.annotationreader.ApiAnnotationIntrospector; import com.google.api.server.spi.config.model.ApiSerializationConfig; -import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.Base64Variants; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.AnnotationIntrospector; @@ -39,6 +39,7 @@ import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.MapType; +import com.google.api.server.spi.config.model.EndpointsFlag; import java.io.IOException; import java.lang.reflect.Array; import java.util.Collection; @@ -77,10 +78,14 @@ public static ObjectMapper createStandardObjectMapper(ApiSerializationConfig con .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true) .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .setBase64Variant(Base64Variants.MODIFIED_FOR_URL) .setSerializerFactory( BeanSerializerFactory.instance.withSerializerModifier(new DeepEmptyCheckingModifier())); - AnnotationIntrospector pair = AnnotationIntrospector.pair( - new ApiAnnotationIntrospector(config), new JacksonAnnotationIntrospector()); + AnnotationIntrospector pair = EndpointsFlag.JSON_USE_JACKSON_ANNOTATIONS.isEnabled() + ? AnnotationIntrospector.pair( + new ApiAnnotationIntrospector(config), + new JacksonAnnotationIntrospector()) + : new ApiAnnotationIntrospector(config); objectMapper.setAnnotationIntrospector(pair); return objectMapper; } @@ -107,10 +112,9 @@ public JsonSerializer modifyCollectionSerializer(SerializationConfig config, public JsonSerializer modifyMapSerializer(SerializationConfig config, MapType valueType, BeanDescription beanDesc, JsonSerializer serializer) { if (serializer instanceof MapSerializer) { - // For some reason, NON_EMPTY is not being propagated to MapSerializer, so we replace it - // with one that has it set. - return new DeepEmptyCheckingSerializer<>( - ((MapSerializer) serializer).withContentInclusion(JsonInclude.Include.NON_EMPTY)); + // TODO: We should probably be propagating the NON_EMPTY inclusion here, but it's breaking + // discovery. + return new DeepEmptyCheckingSerializer<>(serializer); } return serializer; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/PeerAuth.java b/endpoints-framework/src/main/java/com/google/api/server/spi/PeerAuth.java index f5e0dee9..0cfb9cef 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/PeerAuth.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/PeerAuth.java @@ -21,16 +21,6 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.request.Attribute; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; @@ -38,37 +28,19 @@ * Utilities used to do peer authorization. */ public class PeerAuth { - private static final Logger logger = Logger.getLogger(PeerAuth.class.getName()); - - private static volatile - Map, PeerAuthenticator> peerAuthenticatorInstances = - new HashMap, PeerAuthenticator>(); - - private static final PeerAuthenticator DEFAULT_PEER_AUTHENTICATOR = - new EndpointsPeerAuthenticator(); + private static final Singleton.Instantiator INSTANTIATOR + = new Singleton.Instantiator(new EndpointsPeerAuthenticator()); - private static final - Function, PeerAuthenticator> - INSTANTIATE_PEER_AUTHENTICATOR = - new Function, PeerAuthenticator>() { - @Override - public PeerAuthenticator apply(Class clazz) { - try { - if (clazz.getAnnotation(Singleton.class) != null) { - if (!peerAuthenticatorInstances.containsKey(clazz)) { - peerAuthenticatorInstances.put(clazz, clazz.newInstance()); - } - return peerAuthenticatorInstances.get(clazz); - } else { - return clazz.newInstance(); - } - } catch (IllegalAccessException | InstantiationException e) { - logger.log(Level.WARNING, - "Could not instantiate peer authenticator: " + clazz.getName()); - return null; - } - } - }; + /** + * Must be used to instantiate new {@link PeerAuthenticator}s to honor + * {@link com.google.api.server.spi.config.Singleton} contract. + * + * @return a new instance of clazz, or an existing one if clazz is annotated with @{@link + * com.google.api.server.spi.config.Singleton} + */ + public static PeerAuthenticator instantiatePeerAuthenticator(Class clazz) { + return INSTANTIATOR.getInstanceOrDefault(clazz); + } private final HttpServletRequest request; private final Attribute attr; @@ -78,7 +50,7 @@ public PeerAuthenticator apply(Class clazz) { PeerAuth(HttpServletRequest request) { this.request = request; attr = Attribute.from(request); - config = (ApiMethodConfig) attr.get(Attribute.API_METHOD_CONFIG); + config = attr.get(Attribute.API_METHOD_CONFIG); } static PeerAuth from(HttpServletRequest request) { @@ -87,10 +59,7 @@ static PeerAuth from(HttpServletRequest request) { @VisibleForTesting Iterable getPeerAuthenticatorInstances() { - List> classes = config.getPeerAuthenticators(); - return classes == null ? ImmutableList.of(DEFAULT_PEER_AUTHENTICATOR) - : Iterables.filter(Iterables.transform(classes, INSTANTIATE_PEER_AUTHENTICATOR), - Predicates.notNull()); + return INSTANTIATOR.getInstancesOrDefault(config.getPeerAuthenticators()); } boolean authorizePeer() { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceContext.java b/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceContext.java index 5cf625f2..1c4765af 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceContext.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceContext.java @@ -15,8 +15,6 @@ */ package com.google.api.server.spi; -import com.google.common.base.Strings; - /** * Provides context for a service class when its API configuration is being generated. */ @@ -29,7 +27,7 @@ public class ServiceContext { public static final String DEFAULT_APP_NAME = "myapp"; private final String defaultApiName; - private final String appHostName; + private final String appHostname; /** * Creates a service context with default application and API name. @@ -46,42 +44,45 @@ public static ServiceContext create() { * @param apiName Default API name to use. */ public static ServiceContext create(String applicationId, String apiName) { - return new ServiceContext(applicationId, apiName); - } - - private ServiceContext(String applicationId, String apiName) { + String hostname = null; + String defaultApiName = null; if (applicationId == null || applicationId.trim().isEmpty()) { applicationId = DEFAULT_APP_NAME; } - // For Endpoints runtime, appHostName is generated from App Engine environment directly. When - // generating endpoints client library statically from annotated class, derive appHostName from + // For Endpoints runtime, appHostname is generated from App Engine environment directly. When + // generating endpoints client library statically from annotated class, derive appHostname from // application id set in appengine-web.xml. int colon = applicationId.indexOf(":"); if (colon >= 0) { String appName = applicationId.substring(colon + 1); - this.defaultApiName = apiName == null ? appName : apiName; + defaultApiName = apiName == null ? appName : apiName; if (applicationId.substring(0, colon).equals("google.com")) { - this.appHostName = - Strings.isNullOrEmpty(EnvUtil.getAppHostName()) ? appName + ".googleplex.com" - : EnvUtil.getAppHostName(); + hostname = appName + ".googleplex.com"; } else { throw new IllegalArgumentException("Invalid application id '" + applicationId + "'"); } } else { - String appName = applicationId; - this.defaultApiName = apiName == null ? appName : apiName; - this.appHostName = - Strings.isNullOrEmpty(EnvUtil.getAppHostName()) ? applicationId + ".appspot.com" - : EnvUtil.getAppHostName(); + defaultApiName = apiName == null ? applicationId : apiName; + hostname = applicationId + ".appspot.com"; } + return new ServiceContext(hostname, defaultApiName); + } + + public static ServiceContext createFromHostname(String hostname, String apiName) { + return new ServiceContext(hostname, apiName); + } + + private ServiceContext(String appHostname, String defaultApiName) { + this.appHostname = appHostname; + this.defaultApiName = defaultApiName; } public String getDefaultApiName() { return defaultApiName; } - public String getAppHostName() { - return appHostName; + public String getAppHostname() { + return appHostname; } public String getTransferProtocol() { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceException.java b/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceException.java index 41cc3b9a..d90f97b8 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceException.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceException.java @@ -16,6 +16,7 @@ package com.google.api.server.spi; import java.util.Map; +import java.util.logging.Level; /** * Generic service exception that, in addition to a status message, has a status code, and @@ -26,6 +27,7 @@ public class ServiceException extends Exception { protected final int statusCode; protected final String reason; protected final String domain; + protected Level logLevel; public ServiceException(int statusCode, String statusMessage) { super(statusMessage); @@ -99,4 +101,17 @@ public String getDomain() { public Map getHeaders() { return null; } + + public Level getLogLevel() { + return logLevel == null ? getDefaultLoggingLevel(statusCode) : logLevel; + } + + private static Level getDefaultLoggingLevel(int statusCode) { + return statusCode >= 500 ? Level.SEVERE : Level.INFO; + } + + public static T withLogLevel(T exception, Level level) { + exception.logLevel = level; + return exception; + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/ServletInitializationParameters.java b/endpoints-framework/src/main/java/com/google/api/server/spi/ServletInitializationParameters.java index a1abd2a8..9c6a5b7e 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/ServletInitializationParameters.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/ServletInitializationParameters.java @@ -15,6 +15,7 @@ */ package com.google.api.server.spi; +import com.google.auto.value.AutoValue; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Splitter; @@ -26,172 +27,87 @@ import javax.servlet.ServletException; /** - * Initialization parameters supported by the {@link SystemServiceServlet}. + * Initialization parameters supported by the {@link EndpointsServlet}. */ -public class ServletInitializationParameters { - private static final String INIT_PARAM_NAME_SERVICES = "services"; - private static final String INIT_PARAM_NAME_RESTRICTED = "restricted"; - private static final String INIT_PARAM_NAME_CLIENT_ID_WHITELIST_ENABLED = - "clientIdWhitelistEnabled"; - private static final String INIT_PARAM_NAME_ILLEGAL_ARGUMENT_BACKEND_ERROR = - "illegalArgumentIsBackendError"; - private static final String INIT_PARAM_NAME_ENABLE_EXCEPTION_COMPATIBILITY = - "enableExceptionCompatibility"; +@AutoValue +public abstract class ServletInitializationParameters { + // Initialization parameter names used to extract values from a ServletConfig. + private static final String SERVICES = "services"; + private static final String RESTRICTED = "restricted"; + private static final String CLIENT_ID_WHITELIST_ENABLED = "clientIdWhitelistEnabled"; + private static final String ILLEGAL_ARGUMENT_BACKEND_ERROR = "illegalArgumentIsBackendError"; + private static final String EXCEPTION_COMPATIBILITY = "enableExceptionCompatibility"; + private static final String PRETTY_PRINT = "prettyPrint"; + private static final String ADD_CONTENT_LENGTH = "addContentLength"; private static final Splitter CSV_SPLITTER = Splitter.on(',').omitEmptyStrings().trimResults(); private static final Joiner CSV_JOINER = Joiner.on(',').skipNulls(); private static final Function, String> CLASS_TO_NAME = new Function, String>() { - @Override public String apply(Class clazz) { + @Override + public String apply(Class clazz) { return clazz.getName(); } }; - private final ImmutableSet> serviceClasses; - private final boolean isServletRestricted; - private final boolean isClientIdWhitelistEnabled; - private final boolean isIllegalArgumentBackendError; - private final boolean isExceptionCompatibilityEnabled; - - /** - * Returns a new {@link Builder} for this class. - */ - public static Builder builder() { - return new Builder(); - } - /** - * Constructs a new instance from the provided {@link ServletConfig} and {@link ClassLoader}. + * Returns the endpoint service classes to serve. */ - public static ServletInitializationParameters fromServletConfig( - ServletConfig config, ClassLoader classLoader) throws ServletException { - Builder builder = builder(); - if (config != null) { - String serviceClassNames = config.getInitParameter(INIT_PARAM_NAME_SERVICES); - if (serviceClassNames != null) { - for (String serviceClassName : CSV_SPLITTER.split(serviceClassNames)) { - builder.addServiceClass(getClassForName(serviceClassName, classLoader)); - } - } - String isServletRestricted = config.getInitParameter(INIT_PARAM_NAME_RESTRICTED); - if (isServletRestricted != null) { - builder.setRestricted(parseBoolean(isServletRestricted, "is servlet restricted")); - } - String isClientIdWhitelistEnabled = - config.getInitParameter(INIT_PARAM_NAME_CLIENT_ID_WHITELIST_ENABLED); - if (isClientIdWhitelistEnabled != null) { - builder.setClientIdWhitelistEnabled( - parseBoolean(isClientIdWhitelistEnabled, "is the client id whitelist enabled")); - } - String isIllegalArgumentBackendError = - config.getInitParameter(INIT_PARAM_NAME_ILLEGAL_ARGUMENT_BACKEND_ERROR); - if (isIllegalArgumentBackendError != null) { - builder.setIllegalArgumentIsBackendError(parseBoolean( - isIllegalArgumentBackendError, "is IllegalArgumentException a backend error")); - } - String isExceptionCompatibilityEnabled = - config.getInitParameter(INIT_PARAM_NAME_ENABLE_EXCEPTION_COMPATIBILITY); - if (isExceptionCompatibilityEnabled != null) { - builder.setExceptionCompatibilityEnabled( - parseBoolean(isExceptionCompatibilityEnabled, "is exception compatibility enabled")); - } - } - return builder.build(); - } - - private static boolean parseBoolean(String booleanString, String descriptionForErrors) { - if ("true".equalsIgnoreCase(booleanString)) { - return true; - } else if ("false".equalsIgnoreCase(booleanString)) { - return false; - } - throw new IllegalArgumentException(String.format( - "Expected 'true' or 'false' for %s servlet initialization parameter but got '%s'", - descriptionForErrors, booleanString)); - } - - private static Class getClassForName(String className, ClassLoader classLoader) - throws ServletException { - try { - return Class.forName(className, true, classLoader); - } catch (ClassNotFoundException e) { - throw new ServletException(String.format("Cannot find service class: %s", className), e); - } - } + public abstract ImmutableSet> getServiceClasses(); /** - * Returns the endpoint service classes to serve. + * Returns if the SPI servlet is restricted. + * + * @deprecated No longer serves any purpose and will be removed in a future release */ - public ImmutableSet> getServiceClasses() { - return serviceClasses; - } + @Deprecated + public abstract boolean isServletRestricted(); /** - * Returns {@code true} if the SPI servlet is restricted. + * Returns if client ID whitelisting is enabled. */ - public boolean isServletRestricted() { - return isServletRestricted; - } + public abstract boolean isClientIdWhitelistEnabled(); /** - * Returns {@code true} if client ID whitelisting is enabled. + * Returns if an {@link IllegalArgumentException} should be returned as a backend error (500 + * level) instead of a user error (400 level). */ - public boolean isClientIdWhitelistEnabled() { - return isClientIdWhitelistEnabled; - } + public abstract boolean isIllegalArgumentBackendError(); /** - * Returns {@code true} if an {@link IllegalArgumentException} should be returned as a backend - * error (500) instead of a user error (400). + * Returns if v1.0 style exceptions should be returned to users. In v1.0, certain codes are not + * permissible, and other codes are translated to other status codes. */ - public boolean isIllegalArgumentBackendError() { - return isIllegalArgumentBackendError; - } + public abstract boolean isExceptionCompatibilityEnabled(); /** - * Returns {@code true} if v1.0 style exceptions should be returned to users. In v1.0, certain - * codes are not permissible, and other codes are translated to other status codes. + * Returns if pretty printing should be enabled for responses by default. Defaults to true. */ - public boolean isExceptionCompatibilityEnabled() { - return isExceptionCompatibilityEnabled; - } + public abstract boolean isPrettyPrintEnabled(); /** - * Returns the parameters as a {@link java.util.Map} of parameter name to {@link String} value. + * Returns if the Content-Length header should be set on response. Should be disabled when running + * on App Engine, as Content-Length header is discarded by front-end servers. If enabled, has a + * small negative impact on CPU usage and latency. + * */ - public ImmutableMap asMap() { - ImmutableMap.Builder parameterNameToValue = ImmutableMap.builder(); - parameterNameToValue.put(INIT_PARAM_NAME_SERVICES, - CSV_JOINER.join(Iterables.transform(serviceClasses, CLASS_TO_NAME))); - parameterNameToValue.put(INIT_PARAM_NAME_RESTRICTED, Boolean.toString(isServletRestricted)); - parameterNameToValue.put( - INIT_PARAM_NAME_CLIENT_ID_WHITELIST_ENABLED, Boolean.toString(isClientIdWhitelistEnabled)); - parameterNameToValue.put(INIT_PARAM_NAME_ILLEGAL_ARGUMENT_BACKEND_ERROR, - Boolean.toString(isIllegalArgumentBackendError)); - parameterNameToValue.put(INIT_PARAM_NAME_ENABLE_EXCEPTION_COMPATIBILITY, - Boolean.toString(isExceptionCompatibilityEnabled)); - return parameterNameToValue.build(); - } + public abstract boolean isAddContentLength(); - private ServletInitializationParameters( - ImmutableSet> serviceClasses, boolean isServletRestricted, - boolean isClientIdWhitelistEnabled, boolean isIllegalArgumentBackendError, - boolean isExceptionCompatibilityEnabled) { - this.serviceClasses = serviceClasses; - this.isServletRestricted = isServletRestricted; - this.isClientIdWhitelistEnabled = isClientIdWhitelistEnabled; - this.isIllegalArgumentBackendError = isIllegalArgumentBackendError; - this.isExceptionCompatibilityEnabled = isExceptionCompatibilityEnabled; + public static Builder builder() { + return new AutoValue_ServletInitializationParameters.Builder() + .setServletRestricted(true) + .setClientIdWhitelistEnabled(true) + .setIllegalArgumentBackendError(false) + .setExceptionCompatibilityEnabled(true) + .setPrettyPrintEnabled(true) + .setAddContentLength(false); } /** * A builder for {@link ServletInitializationParameters}. */ - public static class Builder { + @AutoValue.Builder + public abstract static class Builder { private final ImmutableSet.Builder> serviceClasses = ImmutableSet.builder(); - private boolean isServletRestricted = true; - private boolean isClientIdWhitelistEnabled = true; - private boolean isIllegalArgumentBackendError = false; - private boolean isExceptionCompatibilityEnabled = true; /** * Adds an endpoint service class to serve. @@ -210,45 +126,138 @@ public Builder addServiceClasses(Iterable> serviceClasses) { } /** - * Sets if the SPI servlet is restricted ({@code true}) or not ({@code false}). If this - * method is not called, it defaults to {@code true}. + * Sets the complete list of endpoint service classes to serve. */ - public Builder setRestricted(boolean isServletRestricted) { - this.isServletRestricted = isServletRestricted; - return this; - } + public abstract Builder setServiceClasses(ImmutableSet> clazzes); /** - * Sets if the client ID whitelist is enabled ({@code true}) or not ({@code false}). If this - * method is not called, it defaults to {@code true}. + * Sets if the servlet is restricted. Defaults to {@code true}. + * + * @deprecated No longer serves any purpose and will be removed in a future release */ - public Builder setClientIdWhitelistEnabled(boolean isClientIdWhitelistEnabled) { - this.isClientIdWhitelistEnabled = isClientIdWhitelistEnabled; - return this; + @Deprecated + public abstract Builder setServletRestricted(boolean servletRestricted); + + /** + * Sets if the servlet is restricted. Retained for API compatibility. + * + * @deprecated Retained for API compatibility + */ + @Deprecated + public Builder setRestricted(boolean servletRestricted) { + return setServletRestricted(servletRestricted); } + /** + * Sets if the client ID whitelist is enabled, defaulting to {@code true}. + */ + public abstract Builder setClientIdWhitelistEnabled(boolean clientIdWhitelist); + /** * Sets if an {@link IllegalArgumentException} should be treated as a backend error (500) - * instead of a user error (400). + * instead of a user error (400). Defaults to {@code false}. */ - public Builder setIllegalArgumentIsBackendError(boolean isIllegalArgumentBackendError) { - this.isIllegalArgumentBackendError = isIllegalArgumentBackendError; - return this; - } + public abstract Builder setIllegalArgumentBackendError(boolean illegalArgumentBackendError); - public Builder setExceptionCompatibilityEnabled(boolean isExceptionCompatibilityEnabled) { - this.isExceptionCompatibilityEnabled = isExceptionCompatibilityEnabled; - return this; - } + /** + * Sets if v1.0 style exceptions should be returned to users. In v1.0, certain codes are not + * permissible, and other codes are translated to other status codes. Defaults to {@code true}. + */ + public abstract Builder setExceptionCompatibilityEnabled(boolean exceptionCompatibility); /** - * Builds a new {@link ServletInitializationParameters} instance with the values from this - * builder. + * Sets if pretty printing should be enabled for responses by default. Defaults to {@code true}. */ + public abstract Builder setPrettyPrintEnabled(boolean prettyPrint); + + /** + * Sets if the content length header should be set. Defaults to {@code false}. + */ + public abstract Builder setAddContentLength(boolean addContentLength); + + abstract ServletInitializationParameters autoBuild(); + public ServletInitializationParameters build() { - return new ServletInitializationParameters( - serviceClasses.build(), isServletRestricted, isClientIdWhitelistEnabled, - isIllegalArgumentBackendError, isExceptionCompatibilityEnabled); + return setServiceClasses(serviceClasses.build()).autoBuild(); + } + } + + /** + * Constructs a new instance from the provided {@link ServletConfig} and {@link ClassLoader}. + */ + public static ServletInitializationParameters fromServletConfig( + ServletConfig config, ClassLoader classLoader) throws ServletException { + Builder builder = builder(); + if (config != null) { + String serviceClassNames = config.getInitParameter(SERVICES); + if (serviceClassNames != null) { + for (String serviceClassName : CSV_SPLITTER.split(serviceClassNames)) { + builder.addServiceClass(getClassForName(serviceClassName, classLoader)); + } + } + String servletRestricted = config.getInitParameter(RESTRICTED); + if (servletRestricted != null) { + builder.setServletRestricted(parseBoolean(servletRestricted, RESTRICTED)); + } + String clientIdWhitelist = config.getInitParameter(CLIENT_ID_WHITELIST_ENABLED); + if (clientIdWhitelist != null) { + builder.setClientIdWhitelistEnabled( + parseBoolean(clientIdWhitelist, CLIENT_ID_WHITELIST_ENABLED)); + } + String illegalArgumentBackendError = config.getInitParameter(ILLEGAL_ARGUMENT_BACKEND_ERROR); + if (illegalArgumentBackendError != null) { + builder.setIllegalArgumentBackendError( + parseBoolean(illegalArgumentBackendError, ILLEGAL_ARGUMENT_BACKEND_ERROR)); + } + String exceptionCompatibility = config.getInitParameter(EXCEPTION_COMPATIBILITY); + if (exceptionCompatibility != null) { + builder.setExceptionCompatibilityEnabled( + parseBoolean(exceptionCompatibility, EXCEPTION_COMPATIBILITY)); + } + String prettyPrint = config.getInitParameter(PRETTY_PRINT); + if (prettyPrint != null) { + builder.setPrettyPrintEnabled(parseBoolean(prettyPrint, PRETTY_PRINT)); + } + String addContentLength = config.getInitParameter(ADD_CONTENT_LENGTH); + if (addContentLength != null) { + builder.setAddContentLength(parseBoolean(addContentLength, ADD_CONTENT_LENGTH)); + } + } + return builder.build(); + } + + private static boolean parseBoolean(String booleanString, String descriptionForErrors) { + if ("true".equalsIgnoreCase(booleanString)) { + return true; + } else if ("false".equalsIgnoreCase(booleanString)) { + return false; } + throw new IllegalArgumentException(String.format( + "Expected 'true' or 'false' for '%s' servlet initialization parameter but got '%s'", + descriptionForErrors, booleanString)); + } + + private static Class getClassForName(String className, ClassLoader classLoader) + throws ServletException { + try { + return Class.forName(className, true, classLoader); + } catch (ClassNotFoundException e) { + throw new ServletException(String.format("Cannot find service class: %s", className), e); + } + } + + /** + * Returns the parameters as a {@link java.util.Map} of parameter name to {@link String} value. + */ + public ImmutableMap asMap() { + return ImmutableMap.builder() + .put(SERVICES, CSV_JOINER.join(Iterables.transform(getServiceClasses(), CLASS_TO_NAME))) + .put(RESTRICTED, Boolean.toString(isServletRestricted())) + .put(CLIENT_ID_WHITELIST_ENABLED, Boolean.toString(isClientIdWhitelistEnabled())) + .put(ILLEGAL_ARGUMENT_BACKEND_ERROR, Boolean.toString(isIllegalArgumentBackendError())) + .put(EXCEPTION_COMPATIBILITY, Boolean.toString(isExceptionCompatibilityEnabled())) + .put(PRETTY_PRINT, Boolean.toString(isPrettyPrintEnabled())) + .put(ADD_CONTENT_LENGTH, Boolean.toString(isAddContentLength())) + .build(); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/SystemService.java b/endpoints-framework/src/main/java/com/google/api/server/spi/SystemService.java index 38ee8447..36873da8 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/SystemService.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/SystemService.java @@ -17,10 +17,8 @@ import com.google.api.server.spi.config.ApiConfigException; import com.google.api.server.spi.config.ApiConfigLoader; -import com.google.api.server.spi.config.ApiConfigSource; import com.google.api.server.spi.config.ApiConfigWriter; import com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader; -import com.google.api.server.spi.config.datastore.ApiConfigDatastoreReader; import com.google.api.server.spi.config.jsonwriter.JsonConfigWriter; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.ApiKey; @@ -38,23 +36,20 @@ import com.google.api.server.spi.response.InternalServerErrorException; import com.google.api.server.spi.response.ResultWriter; import com.google.api.server.spi.response.UnauthorizedException; -import com.google.appengine.api.oauth.OAuthRequestException; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; - +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -62,15 +57,15 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; -import java.util.logging.Logger; - import javax.annotation.Nullable; /** * System service that execute service methods. */ public class SystemService { - private static final Logger logger = Logger.getLogger(SystemService.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final String OAUTH_EXCEPTION_CLASS = + "com.google.appengine.api.oauth.OAuthRequestException"; public static final String MIME_JSON = "application/json; charset=UTF-8"; @@ -104,7 +99,6 @@ public ApiConfig apply(EndpointNode node) { private final Multimap initialConfigsByApi; private final ApiConfigLoader configLoader; - private final ApiConfigValidator validator; private final ServiceContext serviceContext; private final ApiConfigWriter configWriter; private final boolean isIllegalArgumentBackendError; @@ -144,11 +138,10 @@ public Map getMethods() { * @param appName The application's id * @param services The service classes to be registered */ - public SystemService(ApiConfigLoader configLoader, ApiConfigValidator validator, String appName, - ApiConfigWriter configWriter, Object[] services, boolean isIllegalArgumentBackendError, - boolean enableBackendService) throws ApiConfigException { - this(configLoader, validator, appName, configWriter, isIllegalArgumentBackendError, - enableBackendService); + public SystemService(ApiConfigLoader configLoader, String appName, ApiConfigWriter configWriter, + Object[] services, boolean isIllegalArgumentBackendError) + throws ApiConfigException { + this(configLoader, appName, configWriter, isIllegalArgumentBackendError); for (Object service : services) { registerService(service); } @@ -160,22 +153,18 @@ public SystemService(ApiConfigLoader configLoader, ApiConfigValidator validator, * @param configLoader The loader used to read annotation from service classes * @param appName The application's id */ - public SystemService(ApiConfigLoader configLoader, ApiConfigValidator validator, String appName, - ApiConfigWriter configWriter, boolean isIllegalArgumentBackendError, - boolean enableBackendService) throws ApiConfigException { + public SystemService(ApiConfigLoader configLoader, String appName, ApiConfigWriter configWriter, + boolean isIllegalArgumentBackendError) + throws ApiConfigException { this.servicesByName = new HashMap>(); this.endpoints = new ConcurrentHashMap(); this.serviceApiVersions = new HashMap(); this.serializationConfigs = new HashMap(); this.initialConfigsByApi = ArrayListMultimap.create(); this.configLoader = configLoader; - this.validator = validator; this.serviceContext = ServiceContext.create(appName, ServiceContext.DEFAULT_API_NAME); this.configWriter = configWriter; this.isIllegalArgumentBackendError = isIllegalArgumentBackendError; - if (enableBackendService) { - registerInternalService(new BackendService(this)); - } } /** @@ -192,7 +181,7 @@ public int registerService(Class serviceClass, Object service) throws ApiConf Preconditions.checkArgument(serviceClass.isInstance(service), "service is not an instance of " + serviceClass.getName()); ApiConfig apiConfig = configLoader.loadConfiguration(serviceContext, serviceClass); - return registerLoadedService(serviceClass, service, apiConfig, true); + return registerLoadedService(serviceClass, service, apiConfig); } public int registerService(Object service) throws ApiConfigException { @@ -200,14 +189,7 @@ public int registerService(Object service) throws ApiConfigException { return registerService(serviceClass, service); } - private int registerInternalService(Object service) throws ApiConfigException { - Class serviceClass = getServiceClass(service); - ApiConfig apiConfig = configLoader.loadInternalConfiguration(serviceContext, serviceClass); - return registerLoadedService(serviceClass, service, apiConfig, false); - } - - private int registerLoadedService(Class serviceClass, Object service, ApiConfig apiConfig, - boolean doValidation) + private int registerLoadedService(Class serviceClass, Object service, ApiConfig apiConfig) throws ApiConfigException { String fullName = serviceClass.getName(); if (!servicesByName.containsKey(fullName)) { @@ -216,10 +198,6 @@ private int registerLoadedService(Class serviceClass, Object service, ApiConf // a serialization config. This is currently required because the API information is not kept // outside of this method, but it would be nice to find a better way to clean this up. String api = apiConfig.getName() + "-" + apiConfig.getVersion(); - if (doValidation) { - validator.validate(Iterables.concat(initialConfigsByApi.get(api), - Collections.singleton(apiConfig))); - } initialConfigsByApi.put(api, apiConfig); ApiSerializationConfig serializationConfig = serializationConfigs.get(api); @@ -291,36 +269,6 @@ public EndpointMethod resolveService(String serviceName, String methodName) return getEndpointNode(serviceName).methods.get(methodName); } - /** - * Resolves a service name and a method name to the {@link ApiMethodConfig} for the method - * instance. - */ - public ApiMethodConfig resolveAndUpdateServiceConfig(String serviceName, String methodName) - throws ServiceException { - EndpointNode node = getEndpointNode(serviceName); - - if (configLoader.isStaticConfig(node.config)) { - return getMethodConfigFromNode(node, methodName); - } - - ApiConfig newConfig; - try { - newConfig = - configLoader.reloadConfiguration(serviceContext, getServiceClass(node.endpoint), - node.config); - validator.validate(newConfig); - } catch (ApiConfigException e) { - logger.log(Level.WARNING, "Could not load new endpoint config, defaulting to old.", e); - return getMethodConfigFromNode(node, methodName); - } - - if (!newConfig.equals(node.config)) { - updateEndpointConfig(node.endpoint, newConfig, node); - } - - return getMethodConfigFromNode(getEndpointNode(serviceName), methodName); - } - private ApiMethodConfig getMethodConfigFromNode(EndpointNode node, String methodName) { return node.config.getApiClassConfig().getMethods().get(node.methods.get(methodName)); } @@ -366,7 +314,7 @@ public Object findService(String name) throws ServiceException { throw new ServiceException(500, builder.toString()); } else { Object service = services.get(0); - logger.log(Level.FINE, "{0} => {1}", new Object[]{name, services.get(0)}); + logger.atFine().log("%s => %s", name, services.get(0)); return service; } } @@ -381,7 +329,7 @@ public Method findServiceMethod(Object service, String methodName) throws Servic if (endpointNode != null) { EndpointMethod method = endpointNode.methods.get(methodName); if (method != null) { - logger.log(Level.FINE, "serviceMethod={0}", method.getMethod()); + logger.atFine().log("serviceMethod=%s", method.getMethod()); return method.getMethod(); } } @@ -395,58 +343,39 @@ public Method findServiceMethod(Object service, String methodName) throws Servic public void invokeServiceMethod(Object service, Method method, ParamReader paramReader, ResultWriter resultWriter) throws IOException { - Object[] params; try { - params = paramReader.read(); - logger.log(Level.FINE, "params={0} (String)", Arrays.toString(params)); - } catch (BadRequestException e) { - resultWriter.writeError(e); - return; - } - - Object response; - try { - response = method.invoke(service, params); - } catch (IllegalArgumentException e) { - logger.log(Level.SEVERE, "exception occurred while calling backend method", e); - resultWriter.writeError(new BadRequestException(e)); - return; - } catch (IllegalAccessException e) { - logger.log(Level.SEVERE, "exception occurred while calling backend method", e); + Object[] params = paramReader.read(); + logger.atFine().log("params=%s (String)", Arrays.toString(params)); + Object response = method.invoke(service, params); + resultWriter.write(response); + } catch (IllegalArgumentException | IllegalAccessException e) { + logger.atSevere().withCause(e).log("exception occurred while calling backend method"); resultWriter.writeError(new BadRequestException(e)); - return; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); Level level = Level.INFO; - if (cause instanceof ServiceException) { resultWriter.writeError((ServiceException) cause); } else if (cause instanceof IllegalArgumentException) { - // If the backend call is to BackendService, this is an initialization error and needs to - // be logged at a higher level than info. Otherwise, it could be thrown by the API. It is - // transformed into a bad request response, so we don't need to log it at a high level. - if (isIllegalArgumentBackendError - || BackendService.class.equals(method.getDeclaringClass())) { - level = Level.SEVERE; - } resultWriter.writeError( isIllegalArgumentBackendError ? new InternalServerErrorException(cause) : new BadRequestException(cause)); - } else if (cause instanceof OAuthRequestException) { + } else if (isOAuthRequestException(cause.getClass())) { resultWriter.writeError(new UnauthorizedException(cause)); } else if (cause.getCause() != null && cause.getCause() instanceof ServiceException) { - cause = cause.getCause(); - resultWriter.writeError((ServiceException) cause); + ServiceException serviceException = (ServiceException) cause.getCause(); + level = serviceException.getLogLevel(); + resultWriter.writeError(serviceException); } else { level = Level.SEVERE; resultWriter.writeError(new InternalServerErrorException(cause)); } - logger.log(level, "exception occurred while calling backend method", - cause); - return; + logger.at(level).withCause(cause).log("exception occurred while calling backend method"); + } catch (ServiceException e) { + logger.at(e.getLogLevel()).withCause(e) + .log("exception occurred while calling backend method"); + resultWriter.writeError(e); } - - resultWriter.write(response); } /** @@ -464,6 +393,22 @@ public ImmutableList getEndpoints() { return ImmutableList.copyOf(endpoints.values()); } + private void validateRegisteredServices(ApiConfigValidator validator) throws ApiConfigException { + for (String api : initialConfigsByApi.keySet()) { + validator.validate(initialConfigsByApi.get(api)); + } + } + + private static boolean isOAuthRequestException(Class clazz) { + while (Object.class != clazz) { + if (OAUTH_EXCEPTION_CLASS.equals(clazz.getName())) { + return true; + } + clazz = clazz.getSuperclass(); + } + return false; + } + @SuppressWarnings("unchecked") private static Class getServiceClass(T service) { Class clazz = service.getClass(); @@ -506,36 +451,30 @@ public static class Builder { private String appName; private ApiConfigWriter configWriter; private boolean isIllegalArgumentBackendError; - private boolean enableBackendService; private boolean enableDiscoveryService; private Map, Object> services = Maps.newLinkedHashMap(); + private SchemaRepository schemaRepository; public Builder withDefaults(ClassLoader classLoader) throws ClassNotFoundException { - setStandardConfigLoader(classLoader, true); - setConfigValidator(new ApiConfigValidator()); + setStandardConfigLoader(classLoader); setAppName(new BackendProperties().getApplicationId()); - setConfigWriter(new JsonConfigWriter(classLoader, configValidator)); typeLoader = new TypeLoader(classLoader); isIllegalArgumentBackendError = false; - enableBackendService = true; enableDiscoveryService = false; + setConfigWriter(new JsonConfigWriter(typeLoader, configValidator)); + schemaRepository = new SchemaRepository(typeLoader); + setConfigValidator(new ApiConfigValidator(typeLoader, schemaRepository)); return this; } - public Builder setStandardConfigLoader(ClassLoader classLoader, boolean enableDatastoreReader) + public Builder setStandardConfigLoader(ClassLoader classLoader) throws ClassNotFoundException { TypeLoader typeLoader = new TypeLoader(classLoader); ApiConfigAnnotationReader annotationReader = new ApiConfigAnnotationReader(typeLoader.getAnnotationTypes()); - if (EnvUtil.isRunningOnAppEngine() && enableDatastoreReader) { - ApiConfigSource datastoreReader = new ApiConfigDatastoreReader(); - this.configLoader = new ApiConfigLoader(new ApiConfig.Factory(), typeLoader, - annotationReader, datastoreReader); - } else { - this.configLoader = new ApiConfigLoader(new ApiConfig.Factory(), typeLoader, - annotationReader); - } + this.configLoader = + new ApiConfigLoader(new ApiConfig.Factory(), typeLoader, annotationReader); return this; } @@ -559,11 +498,6 @@ public Builder setIllegalArgumentIsBackendError(boolean isIllegalArgumentBackend return this; } - public Builder setBackendServiceEnabled(boolean enableBackendService) { - this.enableBackendService = enableBackendService; - return this; - } - public Builder setDiscoveryServiceEnabled(boolean enableDiscoveryService) { this.enableDiscoveryService = enableDiscoveryService; return this; @@ -578,8 +512,8 @@ public SystemService build() throws ApiConfigException { Preconditions.checkNotNull(configLoader, "configLoader"); Preconditions.checkNotNull(configValidator, "configValidator"); Preconditions.checkNotNull(configWriter, "configWriter"); - SystemService systemService = new SystemService(configLoader, configValidator, appName, - configWriter, isIllegalArgumentBackendError, enableBackendService); + SystemService systemService = new SystemService(configLoader, appName, configWriter, + isIllegalArgumentBackendError); for (Entry, Object> entry : services.entrySet()) { systemService.registerService(entry.getKey(), entry.getValue()); } @@ -590,8 +524,9 @@ public SystemService build() throws ApiConfigException { discoveryService.initialize( new CachingDiscoveryProvider(new LocalDiscoveryProvider( getApiConfigs(systemService), new DiscoveryGenerator(typeLoader), - new SchemaRepository(typeLoader)))); + schemaRepository))); } + systemService.validateRegisteredServices(configValidator); return systemService; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/SystemServiceServlet.java b/endpoints-framework/src/main/java/com/google/api/server/spi/SystemServiceServlet.java deleted file mode 100644 index b7ed6963..00000000 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/SystemServiceServlet.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi; - -import com.google.api.server.spi.config.ApiConfigException; -import com.google.api.server.spi.config.model.ApiMethodConfig; -import com.google.api.server.spi.config.model.ApiSerializationConfig; -import com.google.api.server.spi.request.Attribute; -import com.google.api.server.spi.request.ParamReader; -import com.google.api.server.spi.request.ServletRequestParamReader; -import com.google.api.server.spi.response.BadRequestException; -import com.google.api.server.spi.response.NotFoundException; -import com.google.api.server.spi.response.ResultWriter; -import com.google.api.server.spi.response.ServletResponseResultWriter; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * SPI servlet that turns a request on an SPI endpoint into an invocation of a method on the - * {@link SystemService}. - * - * POST /_ah/spi/{Service}.{method} - */ -public class SystemServiceServlet extends HttpServlet { - private static final Pattern PATH_PATTERN = Pattern.compile("/([^/]+)\\.([^/]+)"); - private static final Logger logger = Logger.getLogger(SystemServiceServlet.class.getName()); - private volatile SystemService systemService; - private volatile ServletInitializationParameters initParameters; - - @Override - public void init(ServletConfig config) throws ServletException { - super.init(config); - ClassLoader classLoader = getUserClassLoader(config); - this.initParameters = ServletInitializationParameters.fromServletConfig(config, classLoader); - logger.log(Level.INFO, "SPI restricted: {0}", this.initParameters.isServletRestricted()); - this.systemService = createSystemService(classLoader, this.initParameters); - } - - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws IOException { - String path = request.getPathInfo(); - String[] pathParams = getPathParams(path); - if (pathParams != null) { - try { - String serviceName = pathParams[0]; - String methodName = pathParams[1]; - execute(request, response, serviceName, methodName); - } catch (ServiceException e) { - getErrorResponseWriter(response).writeError(e); - } - } else { - getErrorResponseWriter(response).writeError( - new BadRequestException("missing /{Service}.{method}")); - } - } - - private ParamReader getParamReader(EndpointMethod method, - ApiSerializationConfig serializationConfig, HttpServletRequest request) { - return new ServletRequestParamReader(method, request, getServletContext(), serializationConfig); - } - - private ResultWriter getResponseWriter(ApiSerializationConfig serializationConfig, - HttpServletResponse response) { - return new ServletResponseResultWriter(response, serializationConfig); - } - - private ResultWriter getErrorResponseWriter(HttpServletResponse response) { - return getResponseWriter(null, response); - } - - protected void execute(HttpServletRequest request, HttpServletResponse response, - String serviceName, String methodName) throws IOException, ServiceException { - logger.log(Level.FINE, "serviceName={0} methodName={1}", - new Object[] {serviceName, methodName}); - - EndpointMethod serviceMethod = systemService.resolveService(serviceName, methodName); - ApiSerializationConfig serializationConfig = systemService.getSerializationConfig(serviceName); - ResultWriter responseWriter = getResponseWriter(serializationConfig, response); - logger.log(Level.FINE, "serviceMethod={0}", serviceMethod); - ApiMethodConfig methodConfig = - systemService.resolveAndUpdateServiceConfig(serviceName, methodName); - Attribute.bindStandardRequestAttributes(request, methodConfig, initParameters); - if (!PeerAuth.from(request).authorizePeer()) { - logger.info("SPI restricted and request denied"); - getErrorResponseWriter(response).writeError(new NotFoundException("Not found")); - return; - } - ParamReader requestReader = getParamReader(serviceMethod, serializationConfig, request); - systemService.invokeServiceMethod(systemService.findService(serviceName), - serviceMethod.getMethod(), requestReader, responseWriter); - } - - private String[] getPathParams(String path) { - Matcher matcher = PATH_PATTERN.matcher(path); - if (matcher.matches()) { - if (matcher.groupCount() == 2) { - return new String[] {matcher.group(1), matcher.group(2)}; - } - } - return null; - } - - private SystemService createSystemService(ClassLoader classLoader, - ServletInitializationParameters initParameters) throws ServletException { - try { - SystemService.Builder builder = SystemService.builder() - .withDefaults(classLoader) - .setIllegalArgumentIsBackendError(initParameters.isIllegalArgumentBackendError()); - for (Class serviceClass : initParameters.getServiceClasses()) { - builder.addService(serviceClass, createService(serviceClass)); - } - return builder.build(); - } catch (ApiConfigException | ClassNotFoundException e) { - throw new ServletException(e); - } - } - - /** - * Creates a new instance of the specified service class. - * - * @param serviceClass the class of the service to create - */ - protected T createService(Class serviceClass) { - try { - return serviceClass.newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException( - String.format("Cannot instantiate service class: %s", serviceClass.getName()), e); - } catch (IllegalAccessException e) { - throw new RuntimeException( - String.format("Cannot access service class: %s", serviceClass.getName()), e); - } - } - - private ClassLoader getUserClassLoader(ServletConfig config) throws ServletException { - try { - // system space - Class contextClass = Class.forName( - "com.google.apphosting.utils.jetty.AppEngineWebAppContext$AppEngineServletContext"); - Method method = contextClass.getMethod("getClassLoader"); - return (ClassLoader) method.invoke(config.getServletContext()); - } catch (ClassNotFoundException e) { - // user space - return getClass().getClassLoader(); - } catch (NoSuchMethodException e) { - throw new ServletException(e); - } catch (IllegalAccessException e) { - throw new ServletException(e); - } catch (InvocationTargetException e) { - throw new ServletException(e); - } - } -} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/TypeLoader.java b/endpoints-framework/src/main/java/com/google/api/server/spi/TypeLoader.java index 4ebfd0a9..c93afe27 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/TypeLoader.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/TypeLoader.java @@ -87,6 +87,7 @@ private static Map, String> createParameterTypes(ClassLoader classLoade parameterTypes.put(Float.TYPE, "float"); parameterTypes.put(classLoader.loadClass("java.lang.Double"), "double"); parameterTypes.put(Double.TYPE, "double"); + parameterTypes.put(byte[].class, "string"); /* * TODO: Adding support for JSR 310 http://jcp.org/en/jsr/detail?id=310 * LocalDate --> date, LocalDateTime --> datetime @@ -96,6 +97,12 @@ private static Map, String> createParameterTypes(ClassLoader classLoade classLoader.loadClass("com.google.api.server.spi.types.DateAndTime"), "datetime"); parameterTypes.put( classLoader.loadClass("com.google.api.server.spi.types.SimpleDate"), "date"); + try { + parameterTypes.put( + classLoader.loadClass("com.google.appengine.api.datastore.Blob"), "string"); + } catch (ClassNotFoundException e) { + // Do nothing; if we're on Flex, this class won't exist. + } return Collections.unmodifiableMap(parameterTypes); } @@ -123,7 +130,11 @@ private static Map, String> createSchemaTypes(ClassLoader classLoader) schemaTypes.put(classLoader.loadClass("com.google.api.server.spi.types.DateAndTime"), "string"); schemaTypes.put(classLoader.loadClass("com.google.api.server.spi.types.SimpleDate"), "string"); schemaTypes.put(byte[].class, "string"); - schemaTypes.put(classLoader.loadClass("com.google.appengine.api.datastore.Blob"), "string"); + try { + schemaTypes.put(classLoader.loadClass("com.google.appengine.api.datastore.Blob"), "string"); + } catch (ClassNotFoundException e) { + // Do nothing; if we're on Flex, this class won't exist. + } return Collections.unmodifiableMap(schemaTypes); } @@ -140,7 +151,11 @@ private Map, String> createSchemaFormats(ClassLoader classLoader) schemaFormats.put( classLoader.loadClass("com.google.api.server.spi.types.SimpleDate"), "date"); schemaFormats.put(byte[].class, "byte"); - schemaFormats.put(classLoader.loadClass("com.google.appengine.api.datastore.Blob"), "byte"); + try { + schemaFormats.put(classLoader.loadClass("com.google.appengine.api.datastore.Blob"), "byte"); + } catch (ClassNotFoundException e) { + // Do nothing; if we're on Flex, this class won't exist. + } return Collections.unmodifiableMap(schemaFormats); } @@ -188,7 +203,11 @@ private static Class loadAnnotation(ClassLoader classLoade private Set> createInjectedClassTypes(ClassLoader classLoader) throws ClassNotFoundException { Set> injectedClassTypes = new HashSet>(); - injectedClassTypes.add(classLoader.loadClass("com.google.appengine.api.users.User")); + try { + injectedClassTypes.add(classLoader.loadClass("com.google.appengine.api.users.User")); + } catch (ClassNotFoundException e) { + // Do nothing; if we're on Flex, this class won't exist. + } injectedClassTypes.add(classLoader.loadClass("javax.servlet.http.HttpServletRequest")); injectedClassTypes.add(classLoader.loadClass("javax.servlet.ServletContext")); injectedClassTypes.add(classLoader.loadClass("com.google.api.server.spi.auth.common.User")); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsAuthenticator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsAuthenticator.java index bdb59c44..ecdb7f7e 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsAuthenticator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsAuthenticator.java @@ -20,6 +20,7 @@ import com.google.api.server.spi.config.Authenticator; import com.google.api.server.spi.config.Singleton; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.common.annotations.VisibleForTesting; import javax.servlet.http.HttpServletRequest; @@ -51,7 +52,7 @@ public EndpointsAuthenticator(GoogleJwtAuthenticator jwtAuthenticator, } @Override - public User authenticate(HttpServletRequest request) { + public User authenticate(HttpServletRequest request) throws ServiceUnavailableException { Attribute attr = Attribute.from(request); User user = jwtAuthenticator.authenticate(request); if (user == null) { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsPeerAuthenticator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsPeerAuthenticator.java index 736b3df2..b803cc76 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsPeerAuthenticator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/EndpointsPeerAuthenticator.java @@ -24,6 +24,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; @@ -50,7 +51,7 @@ public class EndpointsPeerAuthenticator implements PeerAuthenticator { private static final String PUBLIC_CERT_URL = "https://www.googleapis.com/service_accounts/v1/metadata/x509/" + SIGNER; - private static final Logger logger = Logger.getLogger(EndpointsPeerAuthenticator.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final ImmutableSet localHostAddresses = getLocalHostAddresses(); private final GoogleJwtAuthenticator jwtAuthenticator; @@ -76,7 +77,7 @@ private static ImmutableSet getLocalHostAddresses() { } ImmutableSet localHostSet = builder.build(); if (localHostSet.isEmpty()) { - logger.warning("Unable to lookup local addresses."); + logger.atWarning().log("Unable to lookup local addresses."); } return localHostSet; } @@ -105,7 +106,7 @@ public boolean authenticate(HttpServletRequest request) { // Skip peer verification for localhost request. if (localHostAddresses.contains(request.getRemoteAddr())) { - logger.fine("Skip endpoints peer verication from localhost."); + logger.atFine().log("Skip endpoints peer verication from localhost."); return true; } // Verify peer token, signer and audience. @@ -127,7 +128,7 @@ private boolean matchHostAndPort(GoogleIdToken idToken, HttpServletRequest reque return urlFromIdToken.getHost().equals(urlFromRequest.getHost()) && getPort(urlFromIdToken) == getPort(urlFromRequest); } catch (MalformedURLException e) { - logger.warning("Invalid URL from request"); + logger.atWarning().log("Invalid URL from request"); return false; } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticator.java index 601134d7..218d6ee6 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticator.java @@ -22,6 +22,7 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.scope.AuthScopeExpression; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.appengine.api.oauth.OAuthRequestException; import com.google.appengine.api.oauth.OAuthService; import com.google.appengine.api.oauth.OAuthServiceFactory; @@ -30,6 +31,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; +import com.google.common.flogger.FluentLogger; import java.util.logging.Level; import java.util.logging.Logger; @@ -41,8 +43,7 @@ */ @Singleton class GoogleAppEngineAuthenticator implements Authenticator { - private static final Logger logger = - Logger.getLogger(GoogleAppEngineAuthenticator.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final OAuthService oauthService; private final UserService userService; @@ -56,7 +57,7 @@ public GoogleAppEngineAuthenticator(OAuthService oauthService, UserService userS } @VisibleForTesting - String getOAuth2ClientIdDev(String token) { + String getOAuth2ClientIdDev(String token) throws ServiceUnavailableException { GoogleAuth.TokenInfo tokenInfo = GoogleAuth.getTokenInfoRemote(token); return tokenInfo != null ? tokenInfo.clientId : null; } @@ -68,7 +69,7 @@ boolean shouldTryCookieAuth(ApiMethodConfig config) { @VisibleForTesting com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, - ApiMethodConfig config) { + ApiMethodConfig config) throws ServiceUnavailableException { String token = GoogleAuth.getAuthToken(request); if (!GoogleAuth.isOAuth2Token(token)) { return null; @@ -85,13 +86,13 @@ com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, authorized = scopeExpression.isAuthorized(ImmutableSet.copyOf(authorizedScopes)); } if (!authorized) { - logger.warning( - "Access token does not contain sufficient scopes from: " + scopeExpression); + logger.atWarning().log( + "Access token does not contain sufficient scopes from: %s", scopeExpression); return null; } clientId = oauthService.getClientId(allScopes); } catch (OAuthRequestException e) { - logger.log(Level.WARNING, "Failed to get client id for '" + scopeExpression + "'", e); + logger.atWarning().withCause(e).log("Failed to get client id for '%s'", scopeExpression); return null; } } else { // Dev env. @@ -100,7 +101,7 @@ com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, // Check client id. if ((Attribute.from(request).isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST) && !GoogleAuth.checkClientId(clientId, config.getClientIds(), true))) { - logger.warning("ClientId is not allowed: " + clientId); + logger.atWarning().log("ClientId is not allowed: %s", clientId); return null; } @@ -108,20 +109,20 @@ com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, com.google.appengine.api.users.User appEngineUser = oauthService.getCurrentUser(allScopes); return appEngineUser; } catch (OAuthRequestException e) { - logger.log(Level.WARNING, "Failed to get user for '" + scopeExpression + "'", e); + logger.atWarning().withCause(e).log("Failed to get user for '%s'", scopeExpression); } return null; } @Override - public User authenticate(HttpServletRequest request) { + public User authenticate(HttpServletRequest request) throws ServiceUnavailableException { Attribute attr = Attribute.from(request); if (!EnvUtil.isRunningOnAppEngine()) { return null; } com.google.appengine.api.users.User appEngineUser = null; - ApiMethodConfig config = (ApiMethodConfig) attr.get(Attribute.API_METHOD_CONFIG); + ApiMethodConfig config = attr.get(Attribute.API_METHOD_CONFIG); if (!attr.isEnabled(Attribute.SKIP_TOKEN_AUTH)) { appEngineUser = getOAuth2User(request, config); } @@ -133,10 +134,7 @@ public User authenticate(HttpServletRequest request) { } User user = new User(appEngineUser.getEmail()); if (attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) { - logger.log(Level.INFO, "appEngineUser = {0}", appEngineUser); attr.set(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser); - } else { - logger.log(Level.INFO, "User = {0}", user); } return user; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAuth.java b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAuth.java index 6e04f9c4..fea0a77b 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAuth.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleAuth.java @@ -16,19 +16,22 @@ package com.google.api.server.spi.auth; import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpIOExceptionHandler; import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.util.Key; import com.google.api.server.spi.Client; import com.google.api.server.spi.Constant; import com.google.api.server.spi.Strings; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; @@ -37,7 +40,7 @@ * Common auth utils for built-in authenticators. */ public class GoogleAuth { - private static final Logger logger = Logger.getLogger(GoogleAuth.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // Identifies JSON Web Tokens // From java/com/google/gaia/client/AuthSubRequestDetector.java @@ -45,9 +48,9 @@ public class GoogleAuth { private static final Pattern JWT_PATTERN = Pattern.compile(String.format("%s\\.%s\\.%s", BASE64_REGEX, BASE64_REGEX, BASE64_REGEX)); - // Remote API for validating OAuth2 access token. + // Remote API for validating access or id token. private static final String TOKEN_INFO_ENDPOINT = - "https://www.googleapis.com/oauth2/v2/tokeninfo?access_token="; + "https://www.googleapis.com/oauth2/v2/tokeninfo"; @VisibleForTesting static final String AUTHORIZATION_HEADER = "Authorization"; @@ -69,7 +72,7 @@ public class GoogleAuth { static final List SKIP_CLIENT_ID_CHECK_LIST = ImmutableList.of(Constant.SKIP_CLIENT_ID_CHECK); - static String getAuthToken(HttpServletRequest request) { + public static String getAuthToken(HttpServletRequest request) { if (request.getAttribute(Attribute.AUTH_TOKEN) == null) { String token = getAuthTokenFromHeader(request.getHeader(AUTHORIZATION_HEADER)); if (token == null) { @@ -111,14 +114,14 @@ private static String matchAuthScheme(String authHeader) { return null; } - static boolean isJwt(String token) { + public static boolean isJwt(String token) { if (token == null) { return false; } return JWT_PATTERN.matcher(token).matches(); } - static boolean isOAuth2Token(String token) { + public static boolean isOAuth2Token(String token) { if (token == null) { return false; } @@ -172,29 +175,77 @@ public static class TokenInfo { @Key("issued_to") public String clientId; @Key("scope") public String scopes; @Key("user_id") public String userId; + @Key("audience") public String audience; + @Key("expires_in") public Integer expiresIn; + @Key("verified_email") public Boolean verifiedEmail; + @Key("error_description") public String errorDescription; } /** * Get OAuth2 token info from remote token validation API. + * Retries IOExceptions and 5xx responses once. */ - static TokenInfo getTokenInfoRemote(String token) { + public static TokenInfo getTokenInfoRemote(String token) throws ServiceUnavailableException { try { + String tokenParam; + if (isOAuth2Token(token)) { + tokenParam = "?access_token="; + } else if(isJwt(token)) { + tokenParam = "?id_token="; + } else { + return null; + } HttpRequest request = Client.getInstance().getJsonHttpRequestFactory() - .buildGetRequest(new GenericUrl(TOKEN_INFO_ENDPOINT + token)); + .buildGetRequest(new GenericUrl(TOKEN_INFO_ENDPOINT + tokenParam + token)); + configureErrorHandling(request); return parseTokenInfo(request); } catch (IOException e) { - logger.log(Level.WARNING, "Failed to retrieve tokeninfo", e); - return null; + throw new ServiceUnavailableException("Failed to perform access token validation", e); } } @VisibleForTesting - static TokenInfo parseTokenInfo(HttpRequest request) throws IOException { - TokenInfo info = request.execute().parseAs(TokenInfo.class); + static TokenInfo parseTokenInfo(HttpRequest request) + throws IOException, ServiceUnavailableException { + HttpResponse response = request.execute(); + int statusCode = response.getStatusCode(); + TokenInfo info = response.parseAs(TokenInfo.class); + if (statusCode != 200) { + String errorDescription = "Unknown error"; + if (info != null && info.errorDescription != null) { + errorDescription = info.errorDescription; + } + errorDescription += " (" + statusCode + ")"; + if (statusCode >= 500) { + logger.atSevere().log("Error validating access token: %s", errorDescription); + throw new ServiceUnavailableException("Failed to validate access token"); + } + logger.atInfo().log("Invalid access token: %s", errorDescription); + return null; + } if (info == null || Strings.isEmptyOrWhitespace(info.email)) { - logger.log(Level.WARNING, "Access token does not contain email scope"); + logger.atWarning().log("Access token does not contain email scope"); return null; } return info; } + + @VisibleForTesting + static void configureErrorHandling(HttpRequest request) { + request.setNumberOfRetries(1) + .setThrowExceptionOnExecuteError(false) + .setIOExceptionHandler(new HttpIOExceptionHandler() { + @Override + public boolean handleIOException(HttpRequest request, boolean supportsRetry) { + return true; // consider all IOException as transient + } + }) + .setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() { + @Override + public boolean handleResponse(HttpRequest request, HttpResponse response, + boolean supportsRetry) { + return response.getStatusCode() >= 500; // only retry Google's backend errors + } + }); + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleJwtAuthenticator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleJwtAuthenticator.java index 2a624754..426af4fd 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleJwtAuthenticator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleJwtAuthenticator.java @@ -24,12 +24,9 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.request.Attribute; import com.google.common.annotations.VisibleForTesting; - +import com.google.common.flogger.FluentLogger; import java.io.IOException; import java.security.GeneralSecurityException; -import java.util.logging.Level; -import java.util.logging.Logger; - import javax.servlet.http.HttpServletRequest; /** @@ -37,7 +34,7 @@ */ @Singleton public class GoogleJwtAuthenticator implements Authenticator { - private static final Logger logger = Logger.getLogger(GoogleJwtAuthenticator.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final GoogleIdTokenVerifier verifier; public GoogleJwtAuthenticator() { @@ -57,7 +54,7 @@ GoogleIdToken verifyToken(String token) { try { return verifier.verify(token); } catch (GeneralSecurityException | IOException | IllegalArgumentException e) { - logger.warning(e.getMessage()); + logger.atWarning().withCause(e).log("error while verifying JWT"); return null; } } @@ -79,20 +76,22 @@ public User authenticate(HttpServletRequest request) { return null; } + attr.set(Attribute.ID_TOKEN, idToken); + String clientId = idToken.getPayload().getAuthorizedParty(); String audience = (String) idToken.getPayload().getAudience(); - ApiMethodConfig config = (ApiMethodConfig) attr.get(Attribute.API_METHOD_CONFIG); + ApiMethodConfig config = attr.get(Attribute.API_METHOD_CONFIG); // Check client id. if ((attr.isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST) && !GoogleAuth.checkClientId(clientId, config.getClientIds(), false))) { - logger.warning("ClientId is not allowed: " + clientId); + logger.atWarning().log("ClientId is not allowed: %s", clientId); return null; } // Check audience. if (!GoogleAuth.checkAudience(audience, config.getAudiences(), clientId)) { - logger.warning("Audience is not allowed: " + audience); + logger.atWarning().log("Audience is not allowed: %s", audience); return null; } @@ -103,9 +102,6 @@ public User authenticate(HttpServletRequest request) { com.google.appengine.api.users.User appEngineUser = (email == null) ? null : new com.google.appengine.api.users.User(email, ""); attr.set(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser); - logger.log(Level.INFO, "appEngineUser = {0}", appEngineUser); - } else { - logger.log(Level.INFO, "user = {0}", user); } return user; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleOAuth2Authenticator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleOAuth2Authenticator.java index 5524bb6e..5f442810 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleOAuth2Authenticator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/auth/GoogleOAuth2Authenticator.java @@ -22,11 +22,11 @@ import com.google.api.server.spi.config.Singleton; import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletRequest; @@ -36,10 +36,10 @@ */ @Singleton public class GoogleOAuth2Authenticator implements Authenticator { - private static final Logger logger = Logger.getLogger(GoogleOAuth2Authenticator.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override - public User authenticate(HttpServletRequest request) { + public User authenticate(HttpServletRequest request) throws ServiceUnavailableException { Attribute attr = Attribute.from(request); if (attr.isEnabled(Attribute.SKIP_TOKEN_AUTH)) { return null; @@ -55,24 +55,26 @@ public User authenticate(HttpServletRequest request) { return null; } + attr.set(Attribute.TOKEN_INFO, tokenInfo); + ApiMethodConfig config = (ApiMethodConfig) request.getAttribute(Attribute.API_METHOD_CONFIG); // Check scopes. if (Strings.isEmptyOrWhitespace(tokenInfo.scopes)) { - logger.warning("Access token does not contain a valid scope"); + logger.atWarning().log("Access token does not contain a valid scope"); return null; } String[] authorizedScopes = tokenInfo.scopes.split("\\s+"); if (!config.getScopeExpression().isAuthorized(ImmutableSet.copyOf(authorizedScopes))) { - logger.warning( - "Access token does not contain sufficient scopes from: " + config.getScopeExpression()); + logger.atWarning().log( + "Access token does not contain sufficient scopes from: %s", config.getScopeExpression()); return null; } // Check clientId. if (attr.isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST) && !GoogleAuth.checkClientId(tokenInfo.clientId, config.getClientIds(), true)) { - logger.warning("ClientId is not allowed: " + tokenInfo.clientId); + logger.atWarning().log("ClientId is not allowed: %s", tokenInfo.clientId); return null; } @@ -80,16 +82,13 @@ public User authenticate(HttpServletRequest request) { if (attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) { com.google.appengine.api.users.User appEngineUser = new com.google.appengine.api.users.User(tokenInfo.email, ""); - logger.log(Level.INFO, "appEngineUser = {0}", appEngineUser); request.setAttribute(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser); - } else { - logger.log(Level.INFO, "user = {0}", user); } return user; } @VisibleForTesting - TokenInfo getTokenInfoRemote(String token) { + TokenInfo getTokenInfoRemote(String token) throws ServiceUnavailableException { return GoogleAuth.getTokenInfoRemote(token); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Api.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Api.java index bbf7fcce..3edbf46f 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Api.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Api.java @@ -34,6 +34,7 @@ * methods will be exposed below this path. This will default to * "https://yourapp.appspot.com/_ah/api". */ + @Deprecated String root() default ""; /** @@ -77,6 +78,7 @@ * method calls. This will default to "https://yourapp.appspot.com/_ah/spi". Non-secure http URLs * will be automatically converted to use https. */ + @Deprecated String backendRoot() default ""; /** @@ -198,4 +200,9 @@ ApiIssuerAudience[] issuerAudiences() default { * no effect unless used with endpoints-management-control-appengine. */ AnnotationBoolean apiKeyRequired() default AnnotationBoolean.UNSPECIFIED; + + /** + * Rate limiting metric definitions that are used in this API. + */ + ApiLimitMetric[] limitDefinitions() default {}; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiLimitMetric.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiLimitMetric.java new file mode 100644 index 00000000..adcd6e80 --- /dev/null +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiLimitMetric.java @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.config; + +/** + * A rate limiting metric. + */ +public @interface ApiLimitMetric { + /** + * A limit identifier, consisting of alphanumeric characters and hyphens. + */ + String name(); + + /** + * A human readable description of the metric, e.g. Bookstore Read API Requests per Minute. + */ + String displayName() default ""; + + /** + * The default cost limit. + */ + int limit(); +} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMethod.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMethod.java index 70f279bb..3065fa77 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMethod.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMethod.java @@ -128,4 +128,9 @@ ApiIssuerAudience[] issuerAudiences() default { * no effect unless used with endpoints-management-control-appengine. */ AnnotationBoolean apiKeyRequired() default AnnotationBoolean.UNSPECIFIED; + + /** + * A list of metric costs associated with this method. + */ + ApiMetricCost[] metricCosts() default {}; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMetricCost.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMetricCost.java new file mode 100644 index 00000000..e94f528f --- /dev/null +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiMetricCost.java @@ -0,0 +1,31 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.config; + +/** + * Metric cost definition for a method. + */ +public @interface ApiMetricCost { + /** + * The metric name, which must be defined using {@link ApiLimitMetric}. + */ + String name(); + + /** + * The cost charged to the metric. + */ + int cost(); +} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiResourceProperty.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiResourceProperty.java index 7f1c30cd..10dd0eb8 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiResourceProperty.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ApiResourceProperty.java @@ -20,6 +20,10 @@ /** * Annotation for configuring bean properties for API resources. + *

+ * This annotation can be used on all parts of the definition of a property: the field, the + * accessor (getter), or the mutator (setter). However, it should only be used on one of the three; + * behavior for multiple annotations on one property is not defined. */ @Retention(RetentionPolicy.RUNTIME) public @interface ApiResourceProperty { @@ -29,6 +33,12 @@ */ String name() default ""; + /** + * The description that the property represented by the annotated getter, setter, or field should appear + * as in the API. + */ + String description() default ""; + /** * Whether or not the property represented by the annotated getter, setter or field should be * ignored for the API. diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java index 084e698f..923a8930 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Authenticator.java @@ -15,6 +15,7 @@ */ package com.google.api.server.spi.config; +import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.auth.common.User; import javax.servlet.http.HttpServletRequest; @@ -35,5 +36,5 @@ public interface Authenticator { * * @return The authenticated user or null if there is no auth or auth has failed. */ - User authenticate(HttpServletRequest request); + User authenticate(HttpServletRequest request) throws ServiceException; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java index e686e873..3e193911 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java @@ -21,9 +21,10 @@ import java.lang.annotation.Target; /** - * Annotation to specify the description of an API parameter. + * Annotation to specify the description of an API parameter or enum constants. + * The description will be ignored if the annotation is used on resource fields. */ -@Target(ElementType.PARAMETER) +@Target({ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Description { /** diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ResourcePropertySchema.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ResourcePropertySchema.java index e6c07c17..f7a3460d 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/ResourcePropertySchema.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/ResourcePropertySchema.java @@ -29,6 +29,7 @@ */ public class ResourcePropertySchema { private final TypeToken type; + private String description; private ResourcePropertySchema(TypeToken type) { this.type = type; @@ -48,6 +49,14 @@ public TypeToken getType() { return type; } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + /** * Returns a default resource property schema for a given type. * diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Singleton.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Singleton.java index f3004c01..198a7afc 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/Singleton.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/Singleton.java @@ -15,10 +15,19 @@ */ package com.google.api.server.spi.config; +import com.google.common.base.Function; +import com.google.common.base.Predicates; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import com.google.common.flogger.FluentLogger; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; /** * Annotation used with Authenticator and PeerAuthenticator to denote only one instance will be @@ -28,4 +37,53 @@ @Target(value = ElementType.TYPE) @Retention(value = RetentionPolicy.RUNTIME) public @interface Singleton { + + /** + * Instantiates instances of A, honoring the @{@link Singleton} contract. + * Return a default instance when passed null values. + */ + class Instantiator { + + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); + + private volatile Map, A> instances = new HashMap<>(); + + private final A defaultValue; + + private final Function, A> instantiator + = new Function, A>() { + @Override + public A apply(Class clazz) { + try { + if (clazz.getAnnotation(Singleton.class) != null) { + if (!instances.containsKey(clazz)) { + instances.put(clazz, clazz.newInstance()); + } + return instances.get(clazz); + } else { + return clazz.newInstance(); + } + } catch (IllegalAccessException | InstantiationException e) { + logger.atWarning().log("Could not instantiate: %s", clazz.getName()); + return null; + } + } + }; + + public Instantiator(A defaultValue) { + this.defaultValue = defaultValue; + } + + public A getInstanceOrDefault(Class clazz) { + return clazz == null ? defaultValue : instantiator.apply(clazz); + } + + public Iterable getInstancesOrDefault(List> classes) { + return classes == null ? ImmutableList.of(defaultValue) + : Iterables.filter(Iterables.transform(classes, instantiator), + Predicates.notNull()); + } + + } + } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfig.java index 5734daa9..017ed0cc 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfig.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfig.java @@ -16,14 +16,17 @@ package com.google.api.server.spi.config.annotationreader; import com.google.api.server.spi.config.AnnotationBoolean; +import com.google.api.server.spi.config.ApiLimitMetric; import com.google.api.server.spi.config.AuthLevel; import com.google.api.server.spi.config.Authenticator; import com.google.api.server.spi.config.PeerAuthenticator; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.ApiIssuerAudienceConfig; import com.google.api.server.spi.config.model.ApiIssuerConfigs; +import com.google.api.server.spi.config.model.ApiLimitMetricConfig; import com.google.api.server.spi.config.scope.AuthScopeExpressions; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; import java.util.Arrays; @@ -186,4 +189,18 @@ public void setApiKeyRequiredIfSpecified(AnnotationBoolean apiKeyRequired) { config.setApiKeyRequired(false); } } + + public void setApiLimitMetrics(ApiLimitMetric[] apiLimitMetrics) { + ImmutableList.Builder metricConfigs = ImmutableList.builder(); + if (apiLimitMetrics != null && apiLimitMetrics.length > 0) { + for (ApiLimitMetric metric : apiLimitMetrics) { + metricConfigs.add(ApiLimitMetricConfig.builder() + .setName(metric.name()) + .setDisplayName(metric.displayName()) + .setLimit(metric.limit()) + .build()); + } + } + config.setApiLimitMetrics(metricConfigs.build()); + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationIntrospector.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationIntrospector.java index f4ad41b3..ea06c968 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationIntrospector.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationIntrospector.java @@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.reflect.TypeToken; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; @@ -40,6 +41,7 @@ import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector; +import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import java.io.IOException; import java.lang.reflect.ParameterizedType; @@ -81,11 +83,19 @@ public PropertyName findNameForSerialization(Annotated a) { @Override public PropertyName findNameForDeserialization(Annotated a) { - ApiResourceProperty apiName = a.getAnnotation(ApiResourceProperty.class); - if (apiName != null && apiName.ignored() != AnnotationBoolean.TRUE) { - return PropertyName.construct(apiName.name()); - } - return null; + ApiResourceProperty annotation = findAnnotation(a); + return annotation != null ? PropertyName.construct(annotation.name()) : null; + } + + @Override + public String findPropertyDescription(Annotated a) { + ApiResourceProperty annotation = findAnnotation(a); + return annotation != null ? annotation.description() : null; + } + + private ApiResourceProperty findAnnotation(Annotated a) { + ApiResourceProperty annotation = a.getAnnotation(ApiResourceProperty.class); + return annotation != null && annotation.ignored() != AnnotationBoolean.TRUE ? annotation : null; } @Override @@ -118,6 +128,12 @@ public JsonDeserializer findDeserializer(Annotated a) { return getJsonDeserializer(findSerializerInstance(a)); } + @Override + public VisibilityChecker findAutoDetectVisibility( + AnnotatedClass ac, VisibilityChecker checker) { + return checker.withSetterVisibility(Visibility.PUBLIC_ONLY); + } + private static JsonDeserializer getJsonDeserializer( @Nullable final Transformer serializer) { if (serializer == null) { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReader.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReader.java index b9880c4c..27c6541f 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReader.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReader.java @@ -24,6 +24,8 @@ import com.google.api.server.spi.config.ApiConfigSource; import com.google.api.server.spi.config.ApiIssuer; import com.google.api.server.spi.config.ApiIssuerAudience; +import com.google.api.server.spi.config.ApiLimitMetric; +import com.google.api.server.spi.config.ApiMetricCost; import com.google.api.server.spi.config.AuthLevel; import com.google.api.server.spi.config.Authenticator; import com.google.api.server.spi.config.PeerAuthenticator; @@ -208,6 +210,8 @@ private void readApi(ApiAnnotationConfig config, Annotation api) .[]>getAnnotationProperty(api, "peerAuthenticators")); config.setApiKeyRequiredIfSpecified( (AnnotationBoolean) this.getAnnotationProperty(api, "apiKeyRequired")); + config.setApiLimitMetrics( + (ApiLimitMetric[]) this.getAnnotationProperty(api, "limitDefinitions")); } private ApiIssuerConfigs getIssuerConfigs(Annotation annotation) @@ -356,6 +360,8 @@ private void readApiMethodInstance(ApiMethodAnnotationConfig config, Annotation config.setIgnoredIfSpecified((AnnotationBoolean) getAnnotationProperty(apiMethod, "ignored")); config.setApiKeyRequiredIfSpecified( (AnnotationBoolean) this.getAnnotationProperty(apiMethod, "apiKeyRequired")); + config.setMetricCosts( + (ApiMetricCost[]) getAnnotationProperty(apiMethod, "metricCosts")); } private void readMethodRequestParameters(EndpointMethod endpointMethod, diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiMethodAnnotationConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiMethodAnnotationConfig.java index 7dabdba4..590857ec 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiMethodAnnotationConfig.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/annotationreader/ApiMethodAnnotationConfig.java @@ -16,12 +16,15 @@ package com.google.api.server.spi.config.annotationreader; import com.google.api.server.spi.config.AnnotationBoolean; +import com.google.api.server.spi.config.ApiMetricCost; import com.google.api.server.spi.config.AuthLevel; import com.google.api.server.spi.config.Authenticator; import com.google.api.server.spi.config.PeerAuthenticator; import com.google.api.server.spi.config.model.ApiIssuerAudienceConfig; import com.google.api.server.spi.config.model.ApiMethodConfig; +import com.google.api.server.spi.config.model.ApiMetricCostConfig; import com.google.api.server.spi.config.scope.AuthScopeExpressions; +import com.google.common.collect.ImmutableList; import java.util.Arrays; @@ -124,4 +127,17 @@ public void setApiKeyRequiredIfSpecified(AnnotationBoolean apiKeyRequired) { config.setApiKeyRequired(false); } } + + public void setMetricCosts(ApiMetricCost[] metricCosts) { + ImmutableList.Builder costs = ImmutableList.builder(); + if (metricCosts != null && metricCosts.length > 0) { + for (ApiMetricCost cost : metricCosts) { + costs.add(ApiMetricCostConfig.builder() + .setName(cost.name()) + .setCost(cost.cost()) + .build()); + } + } + config.setMetricCosts(costs.build()); + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/datastore/ApiConfigDatastoreReader.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/datastore/ApiConfigDatastoreReader.java deleted file mode 100644 index 8e9f5ff0..00000000 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/datastore/ApiConfigDatastoreReader.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.config.datastore; - -import com.google.api.server.spi.ServiceContext; -import com.google.api.server.spi.config.ApiConfigException; -import com.google.api.server.spi.config.ApiConfigSource; -import com.google.api.server.spi.config.model.ApiClassConfig; -import com.google.api.server.spi.config.model.ApiClassConfig.MethodConfigMap; -import com.google.api.server.spi.config.model.ApiConfig; -import com.google.api.server.spi.config.scope.AuthScopeExpressions; -import com.google.appengine.api.datastore.DatastoreService; -import com.google.appengine.api.datastore.DatastoreServiceFactory; -import com.google.appengine.api.datastore.Entity; -import com.google.appengine.api.datastore.EntityNotFoundException; -import com.google.appengine.api.datastore.Key; -import com.google.appengine.api.datastore.KeyFactory; -import com.google.appengine.api.memcache.AsyncMemcacheService; -import com.google.appengine.api.memcache.MemcacheService; -import com.google.appengine.api.memcache.MemcacheServiceFactory; -import com.google.common.collect.ImmutableList; - -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Configuration source for configuration data stored in appengine datastore. - * - * @author Eric Orth - */ -public final class ApiConfigDatastoreReader implements ApiConfigSource { - private static final Logger logger = Logger.getLogger(ApiConfigDatastoreReader.class.getName()); - - private final DatastoreService datastoreService; - private final AsyncMemcacheService memcacheService; - - public static final String ENDPOINT_CONFIGURATION_KIND = "GoogleCloudEndpointConfiguration"; - public static final String METHOD_CONFIGURATION_KIND = "GoogleCloudEndpointMethodConfiguration"; - - public ApiConfigDatastoreReader(DatastoreService datastoreService, - AsyncMemcacheService memcacheService) { - this.datastoreService = datastoreService; - this.memcacheService = memcacheService; - } - - public ApiConfigDatastoreReader() { - this(DatastoreServiceFactory.getDatastoreService(), - MemcacheServiceFactory.getAsyncMemcacheService()); - } - - @Override - public void loadEndpointClass(ServiceContext serviceContext, Class endpointClass, - ApiConfig config) throws ApiConfigException { - ApiClassConfig classConfig = config.getApiClassConfig(); - Entity endpointEntity = - classConfig.getUseDatastore() ? getEndpointEntityOrNull(endpointClass) : null; - if (endpointEntity != null) { - processEndpointEntity(endpointEntity, classConfig); - } - } - - private Entity getEndpointEntityOrNull(Class endpointClass) { - Entity entity = getMemcacheEntityOrNull(endpointClass); - if (entity != null) { - return entity; - } - - entity = getDatastoreEntityOrNull(endpointClass); - if (entity == null) { - return null; - } - - // We got the value from datastore, so now write it to memcache. Don't wait for completion as - // we don't actually care, except in unittests for confirmation. - memcacheService.put(getEndpointMemcacheKey(endpointClass.getName()), entity, null, - MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT); - return entity; - } - - private Entity getMemcacheEntityOrNull(Class endpointClass) { - try { - // Check for the entity keyed by either full or simple java names as we allow external devs - // to use either. - Object memcacheValue = - memcacheService.get(getEndpointMemcacheKey(endpointClass.getName())).get(); - if (memcacheValue == null || !(memcacheValue instanceof Entity)) { - memcacheValue = - memcacheService.get(getEndpointMemcacheKey(endpointClass.getSimpleName())).get(); - } - return (Entity) memcacheValue; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.log(Level.WARNING, "Error while retrieving memcached endpoint configuration.", e); - return null; - } catch (ExecutionException e) { - logger.log(Level.WARNING, "Error while retrieving memcached endpoint configuration.", e); - return null; - } - } - - private Entity getDatastoreEntityOrNull(Class endpointClass) { - // Check for the entity keyed by either full or simple java names as we allow external devs - // to use either. - try { - return datastoreService.get(getEndpointDatastoreKey(endpointClass.getName())); - } catch (EntityNotFoundException e) { - try { - return datastoreService.get(getEndpointDatastoreKey(endpointClass.getSimpleName())); - } catch (EntityNotFoundException ex) { - return null; - } - } - } - - private void processEndpointEntity(Entity endpointEntity, ApiClassConfig config) - throws ApiConfigException { - List scopes = processStringListProperty(endpointEntity, "scopes"); - if (scopes != null) { - config.setScopeExpression(AuthScopeExpressions.interpret(scopes)); - } - - List audiences = processStringListProperty(endpointEntity, "audiences"); - if (audiences != null) { - config.setAudiences(audiences); - } - - List clientIds = processStringListProperty(endpointEntity, "clientIds"); - if (clientIds != null) { - config.setClientIds(clientIds); - } - } - - private List processStringListProperty(Entity endpointEntity, String propertyName) - throws ApiConfigException { - if (!endpointEntity.hasProperty(propertyName)) { - return null; - } - - Object property = endpointEntity.getProperty(propertyName); - - if (property instanceof String) { - return ImmutableList.of((String) property); - } - - if (property instanceof List) { - List propertyList = safeCast((List) property); - if (propertyList != null) { - return propertyList; - } - } - - throw new ApiConfigException( - endpointEntity + "." + propertyName + " was not of type String or List."); - } - - /** - * Checks if the given list contains only String (or is empty) and casts to {@code List} - * if so. - * - * @return {@code null} iff the given list contains any non-String elements. - */ - @SuppressWarnings("unchecked") - private static List safeCast(List list) { - for (Object o : list) { - if (!(o instanceof String)) { - return null; - } - } - - return (List) list; - } - - @Override - public void loadEndpointMethods(ServiceContext serviceContext, Class endpointClass, - MethodConfigMap methodConfigMap) { - // Noop. Currently no method configuration is allowed through datastore. - } - - @Override - public boolean isStaticConfig(ApiConfig config) { - return !config.getApiClassConfig().getUseDatastore(); - } - - private Key getEndpointDatastoreKey(String endpointClassName) { - return KeyFactory.createKey(ENDPOINT_CONFIGURATION_KIND, endpointClassName); - } - - private Object getEndpointMemcacheKey(String endpointClassName) { - return ENDPOINT_CONFIGURATION_KIND + "." + endpointClassName; - } -} - diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JacksonResourceSchemaProvider.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JacksonResourceSchemaProvider.java index 0efb72c2..df06c115 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JacksonResourceSchemaProvider.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JacksonResourceSchemaProvider.java @@ -23,6 +23,7 @@ import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.Types; import com.google.common.collect.ImmutableSet; +import com.google.common.flogger.FluentLogger; import com.google.common.reflect.TypeToken; import com.fasterxml.jackson.databind.BeanDescription; @@ -36,7 +37,6 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Set; -import java.util.logging.Logger; import javax.annotation.Nullable; @@ -45,8 +45,7 @@ */ public class JacksonResourceSchemaProvider extends AbstractResourceSchemaProvider { - private static final Logger logger = - Logger.getLogger(JacksonResourceSchemaProvider.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override public ResourceSchema getResourceSchema(TypeToken type, ApiConfig config) { @@ -66,17 +65,20 @@ public ResourceSchema getResourceSchema(TypeToken type, ApiConfig config) { String name = definition.getName(); if (genericDataFieldNames == null || genericDataFieldNames.contains(name)) { if (hasUnresolvedType(propertyType)) { - logger.warning("skipping field '" + name + "' of type '" + propertyType - + "' because it is unresolved."); + logger.atWarning().log("skipping field '%s' of type '%s' because it is unresolved.", name, + propertyType); continue; } if (propertyType != null) { - schemaBuilder.addProperty(name, ResourcePropertySchema.of(propertyType)); + ResourcePropertySchema propertySchema = ResourcePropertySchema.of(propertyType); + propertySchema.setDescription(definition.getMetadata().getDescription()); + schemaBuilder.addProperty(name, propertySchema); } else { - logger.warning("No type found for property '" + name + "' on class '" + type + "'."); + logger.atWarning().log("No type found for property '%s' on class '%s'.", name, type); } } else { - logger.fine("skipping field '" + name + "' because it's not a Java client model field."); + logger.atFine() + .log("skipping field '%s' because it's not a Java client model field.", name); } } return schemaBuilder.build(); @@ -95,7 +97,7 @@ private static boolean hasUnresolvedType(TypeToken type) { ParameterizedType p = (ParameterizedType) javaType; for (Type t : p.getActualTypeArguments()) { if (Types.isWildcardType(type.resolveType(t))) { - logger.warning("skipping field of type " + type + " because it is unresolved"); + logger.atWarning().log("skipping field of type '%s' because it is unresolved", type); return true; } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriter.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriter.java index 1ac7dfb0..25980885 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriter.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriter.java @@ -32,11 +32,10 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.model.ApiNamespaceConfig; import com.google.api.server.spi.config.model.ApiParameterConfig; +import com.google.api.server.spi.config.model.SchemaRepository; import com.google.api.server.spi.config.model.Types; import com.google.api.server.spi.config.scope.AuthScopeExpressions; import com.google.api.server.spi.config.validation.ApiConfigValidator; -import com.google.api.server.spi.config.validation.InvalidReturnTypeException; -import com.google.api.server.spi.config.validation.PropertyParameterNameConflictException; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.collect.Iterables; @@ -80,13 +79,13 @@ public class JsonConfigWriter implements ApiConfigWriter { private final ResourceSchemaProvider resourceSchemaProvider = new JacksonResourceSchemaProvider(); public JsonConfigWriter() throws ClassNotFoundException { - this(JsonConfigWriter.class.getClassLoader(), new ApiConfigValidator()); + this.typeLoader = new TypeLoader(JsonConfigWriter.class.getClassLoader()); + this.validator = new ApiConfigValidator(typeLoader, new SchemaRepository(typeLoader)); } - public JsonConfigWriter(ClassLoader classLoader, ApiConfigValidator validator) + public JsonConfigWriter(TypeLoader typeLoader, ApiConfigValidator validator) throws ClassNotFoundException { - this.typeLoader = new TypeLoader(classLoader); - + this.typeLoader = typeLoader; this.validator = validator; } @@ -463,12 +462,6 @@ private ObjectNode convertMethodResponseType(ObjectNode descriptorSchemasNode, addTypeToNode(descriptorSchemasNode, returnType, null, returnTypeNode, config.getApiClassConfig().getApiConfig(), null); - // TODO: Move to ApiConfigValidator once return type parsing is pulled out of the - // writer. - if (typeLoader.isSchemaType(returnType) || Types.isEnumType(returnType)) { - throw new InvalidReturnTypeException(config, returnType); - } - if (Types.isArrayType(returnType)) { ObjectNode propertiesNode = objectMapper.createObjectNode(); propertiesNode.set("items", returnTypeNode); @@ -578,7 +571,6 @@ private void addBeanProperties(ObjectNode schemasNode, ObjectNode node, TypeToke ResourceSchema schema = resourceSchemaProvider.getResourceSchema(beanType, apiConfig); for (Entry entry : schema.getProperties().entrySet()) { String propertyName = entry.getKey(); - validatePropertyName(propertyName, parameterConfigs); ObjectNode propertyNode = objectMapper.createObjectNode(); TypeToken propertyType = entry.getValue().getType(); if (propertyType != null) { @@ -589,25 +581,6 @@ private void addBeanProperties(ObjectNode schemasNode, ObjectNode node, TypeToke } } - // TODO: When resource parsing is refactored out of the config writer, move this to the - // validator. - private static void validatePropertyName(String propertyName, - List parameterConfigs) throws ApiConfigException { - // Special case to allow id as it is a common scenario for REST for the id parameter to be the - // same id as the id property. Thus conflict is unlikely. - if (propertyName.equals("id")) { - return; - } - - if (parameterConfigs != null) { - for (ApiParameterConfig parameter : parameterConfigs) { - if (propertyName.equals(parameter.getName())) { - throw new PropertyParameterNameConflictException(parameter); - } - } - } - } - /** * Adds a schema for a type into an output node. For arrays, this generates nested schemas inline * for however many dimensions are necessary. diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiConfig.java index 3b31123b..a76b26bc 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiConfig.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiConfig.java @@ -84,6 +84,7 @@ public class ApiConfig { private final ApiNamespaceConfig namespaceConfig; private final ApiClassConfig apiClassConfig; + private List apiLimitMetrics; /** * Simple factory to create {@link ApiConfig} instances. @@ -142,6 +143,7 @@ protected ApiConfig(ApiConfig original) { this.authenticators = original.authenticators; this.peerAuthenticators = original.peerAuthenticators; this.apiKeyRequired = original.apiKeyRequired; + this.apiLimitMetrics = original.apiLimitMetrics; this.authConfig = new ApiAuthConfig(original.authConfig); this.cacheControlConfig = new ApiCacheControlConfig(original.cacheControlConfig); this.frontendLimitsConfig = new ApiFrontendLimitsConfig(original.frontendLimitsConfig); @@ -193,6 +195,7 @@ public Iterable> getConfigurationInconsistencies( .addIfInconsistent("authenticators", authenticators, config.authenticators) .addIfInconsistent("peerAuthenticators", peerAuthenticators, config.peerAuthenticators) .addIfInconsistent("apiKeyRequired", apiKeyRequired, config.apiKeyRequired) + .addIfInconsistent("apiLimitMetrics", apiLimitMetrics, config.apiLimitMetrics) .addAll(authConfig.getConfigurationInconsistencies(config.authConfig)) .addAll(cacheControlConfig.getConfigurationInconsistencies(config.cacheControlConfig)) .addAll(frontendLimitsConfig.getConfigurationInconsistencies(config.frontendLimitsConfig)) @@ -207,7 +210,8 @@ public int hashCode() { documentationLink, backendRoot, isAbstract, defaultVersion, discoverable, useDatastore, resource, authLevel, scopeExpression, audiences, clientIds, authenticators, peerAuthenticators, authConfig, cacheControlConfig, frontendLimitsConfig, - serializationConfig, apiClassConfig, issuers, issuerAudiences, apiKeyRequired); + serializationConfig, apiClassConfig, issuers, issuerAudiences, apiKeyRequired, + apiLimitMetrics); } /** @@ -255,15 +259,15 @@ protected ApiClassConfig createApiClassConfig(TypeLoader typeLoader, Class ap */ protected void setDefaults(ServiceContext serviceContext) { root = - serviceContext.getTransferProtocol() + "://" + serviceContext.getAppHostName() + "/_ah/api"; + serviceContext.getTransferProtocol() + "://" + serviceContext.getAppHostname() + "/_ah/api"; name = serviceContext.getDefaultApiName(); canonicalName = null; version = "v1"; description = null; backendRoot = - serviceContext.getTransferProtocol() + "://" + serviceContext.getAppHostName() + "/_ah/spi"; + serviceContext.getTransferProtocol() + "://" + serviceContext.getAppHostname() + "/_ah/spi"; isAbstract = false; - defaultVersion = false; + defaultVersion = true; discoverable = true; useDatastore = false; resource = null; @@ -277,6 +281,7 @@ protected void setDefaults(ServiceContext serviceContext) { authenticators = null; peerAuthenticators = null; apiKeyRequired = false; + apiLimitMetrics = ImmutableList.of(); } public ApiKey getApiKey() { @@ -499,4 +504,12 @@ private String toHttps(String url) { public ApiClassConfig getApiClassConfig() { return apiClassConfig; } + + public void setApiLimitMetrics(List apiLimitMetrics) { + this.apiLimitMetrics = apiLimitMetrics; + } + + public List getApiLimitMetrics() { + return apiLimitMetrics; + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfig.java index 2b7e17a5..a1aab9d1 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfig.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfig.java @@ -18,6 +18,8 @@ import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSetMultimap; import java.util.Collection; import java.util.Objects; @@ -31,7 +33,7 @@ public class ApiIssuerAudienceConfig { .addIssuerAudiences(UNSPECIFIED_NAME, UNSPECIFIED_AUDIENCE) .build(); public static final ApiIssuerAudienceConfig EMPTY = builder().build(); - private final ImmutableListMultimap issuerAudiences; + private final ImmutableSetMultimap issuerAudiences; private ApiIssuerAudienceConfig(ApiIssuerAudienceConfig.Builder builder) { this.issuerAudiences = builder.issuerAudiences.build(); @@ -53,6 +55,14 @@ public boolean hasIssuer(String issuer) { return issuerAudiences.containsKey(issuer); } + public ImmutableSet getIssuerNames() { + return issuerAudiences.keySet(); + } + + public ImmutableSet getAudiences(String issuer) { + return issuerAudiences.get(issuer); + } + @Override public boolean equals(Object o) { return o != null && o instanceof ApiIssuerAudienceConfig @@ -69,8 +79,8 @@ public static Builder builder() { } public static class Builder { - private final ImmutableListMultimap.Builder issuerAudiences = - ImmutableListMultimap.builder(); + private final ImmutableSetMultimap.Builder issuerAudiences = + ImmutableSetMultimap.builder(); public Builder addIssuerAudiences(String issuer, String... audiences) { issuerAudiences.putAll(issuer, audiences); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerConfigs.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerConfigs.java index 64d280b5..296ad793 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerConfigs.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiIssuerConfigs.java @@ -34,6 +34,10 @@ public boolean hasIssuer(String issuer) { return issuerConfigs.containsKey(issuer); } + public IssuerConfig getIssuer(String issuer) { + return issuerConfigs.get(issuer); + } + public boolean isSpecified() { return !this.equals(UNSPECIFIED); } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiLimitMetricConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiLimitMetricConfig.java new file mode 100644 index 00000000..b0a75e71 --- /dev/null +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiLimitMetricConfig.java @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.config.model; + +import com.google.auto.value.AutoValue; + +@AutoValue +public abstract class ApiLimitMetricConfig { + public abstract String name(); + public abstract String displayName(); + public abstract int limit(); + + public static Builder builder() { + return new AutoValue_ApiLimitMetricConfig.Builder(); + } + + @AutoValue.Builder + public static abstract class Builder { + public abstract Builder setName(String name); + public abstract Builder setDisplayName(String displayName); + public abstract Builder setLimit(int limit); + public abstract ApiLimitMetricConfig build(); + } +} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMethodConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMethodConfig.java index 7865316f..be1e6adf 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMethodConfig.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMethodConfig.java @@ -24,13 +24,13 @@ import com.google.api.server.spi.config.model.ApiParameterConfig.Classification; import com.google.api.server.spi.config.scope.AuthScopeExpression; import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; import com.google.common.reflect.TypeToken; - import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -44,6 +44,7 @@ * @author Eric Orth */ public class ApiMethodConfig { + private enum RestMethod { LIST("list", "GET") { @Override @@ -142,6 +143,7 @@ public String guessResourceName( private String name; private String description; private String path; + private String canonicalPath; private String httpMethod; // If null, get a default from apiConfig. @@ -156,6 +158,7 @@ public String guessResourceName( private boolean ignored = false; private Boolean apiKeyRequired; private TypeToken returnType; + private List metricCosts; private final TypeLoader typeLoader; @@ -173,6 +176,7 @@ public ApiMethodConfig(ApiMethodConfig original, ApiClassConfig apiClassConfig) this.apiClassConfig = apiClassConfig; this.name = original.name; this.path = original.path; + this.canonicalPath = original.canonicalPath; this.description = original.description; this.httpMethod = original.httpMethod; this.scopeExpression = original.scopeExpression; @@ -187,6 +191,7 @@ public ApiMethodConfig(ApiMethodConfig original, ApiClassConfig apiClassConfig) this.apiKeyRequired = original.apiKeyRequired; this.returnType = original.returnType; this.typeLoader = original.typeLoader; + this.metricCosts = original.metricCosts; // Parameter configs are mutable, so we need to do a deep copy. this.parameterConfigs = new ArrayList<>(original.parameterConfigs.size()); @@ -213,8 +218,8 @@ protected void setDefaults(EndpointMethod endpointMethod, TypeLoader typeLoader, name = null; httpMethod = Preconditions.checkNotNull(restMethod.getHttpMethod(), "httpMethod"); - path = Preconditions.checkNotNull( - resourceTypeName == null ? method.getName() : resourceTypeName.toLowerCase(), "path"); + setPath(Preconditions.checkNotNull( + resourceTypeName == null ? method.getName() : resourceTypeName.toLowerCase(), "path")); authLevel = AuthLevel.UNSPECIFIED; scopeExpression = null; audiences = null; @@ -225,6 +230,7 @@ protected void setDefaults(EndpointMethod endpointMethod, TypeLoader typeLoader, ignored = false; apiKeyRequired = null; returnType = endpointMethod.getReturnType(); + metricCosts = ImmutableList.of(); } private RestMethod getRestMethod(Method method) { @@ -255,7 +261,8 @@ public boolean equals(Object o) { Objects.equals(typeLoader, config.typeLoader) && ignored == config.ignored && apiKeyRequired == config.apiKeyRequired && - Objects.equals(returnType, config.returnType); + Objects.equals(returnType, config.returnType) && + Objects.equals(metricCosts, config.metricCosts); } else { return false; } @@ -265,7 +272,7 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(endpointMethodName, parameterConfigs, name, path, httpMethod, scopeExpression, audiences, clientIds, authenticators, peerAuthenticators, typeLoader, - ignored, issuerAudiences, apiKeyRequired, returnType); + ignored, issuerAudiences, apiKeyRequired, returnType, metricCosts); } public ApiClassConfig getApiClassConfig() { @@ -305,7 +312,10 @@ public ApiParameterConfig addParameter(String name, String description, boolean if (config.getClassification() != Classification.INJECTED && name != null && !nullable && defaultValue == null) { - path += "/{" + name + "}"; + String pathFragment = "{" + name + "}"; + if (!path.contains(pathFragment)) { + setPath(path + "/" + pathFragment); + } } return config; @@ -371,12 +381,21 @@ public void setDescription(String description) { public void setPath(String path) { this.path = path; + if (path.startsWith("/")) { + canonicalPath = path.substring(1); + } else { + canonicalPath = getApiConfig().getName() + "/" + getApiConfig().getVersion() + "/" + path; + } } public String getPath() { return path; } + public String getCanonicalPath() { + return canonicalPath; + } + public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } @@ -479,7 +498,7 @@ public Collection getPathParameters() { Pattern pathPattern = java.util.regex.Pattern.compile("\\{([^\\}]*)\\}"); Matcher pathMatcher = pathPattern.matcher(path); - Collection pathParameters = new HashSet<>(); + Collection pathParameters = new LinkedHashSet<>(); while (pathMatcher.find()) { pathParameters.add(pathMatcher.group(1)); } @@ -498,4 +517,12 @@ public boolean hasResourceInResponse() { Type returnType = getReturnType().getRawType(); return returnType != Void.TYPE && returnType != Void.class; } + + public void setMetricCosts(List metricCosts) { + this.metricCosts = metricCosts; + } + + public List getMetricCosts() { + return metricCosts; + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMetricCostConfig.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMetricCostConfig.java new file mode 100644 index 00000000..6e20fd5b --- /dev/null +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/ApiMetricCostConfig.java @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.config.model; + +import com.google.auto.value.AutoValue; + +@AutoValue +public abstract class ApiMetricCostConfig { + public abstract String name(); + public abstract int cost(); + + public static Builder builder() { + return new AutoValue_ApiMetricCostConfig.Builder(); + } + + @AutoValue.Builder + public static abstract class Builder { + public abstract Builder setName(String name); + public abstract Builder setCost(int cost); + public abstract ApiMetricCostConfig build(); + } +} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/AuthScopeRepository.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/AuthScopeRepository.java new file mode 100644 index 00000000..73a4eea3 --- /dev/null +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/AuthScopeRepository.java @@ -0,0 +1,64 @@ +package com.google.api.server.spi.config.model; + +import com.google.api.server.spi.Constant; +import com.google.api.server.spi.config.scope.AuthScopeExpression; +import com.google.api.server.spi.config.scope.AuthScopeExpressions; +import com.google.api.server.spi.discovery.DiscoveryGenerator; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.io.Resources; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Properties; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * Stores a list of OAuth2 scopes with their corresponding descriptions. + * Loads Google scopes from file googleScopeDescriptions.properties in same package. + */ +public class AuthScopeRepository { + + private static final ImmutableMap GOOGLE_SCOPE_DESCRIPTIONS + = loadScopeDescriptions("googleScopeDescriptions.properties"); + + private static ImmutableMap loadScopeDescriptions(String fileName) { + try { + Properties properties = new Properties(); + URL resourceFile = Resources.getResource(DiscoveryGenerator.class, fileName); + InputStream inputStream = resourceFile.openStream(); + properties.load(inputStream); + inputStream.close(); + return Maps.fromProperties(properties); + } catch (IOException e) { + throw new IllegalStateException("Cannot load scope descriptions from " + fileName, e); + } + } + + private final SortedMap descriptionsByScope = new TreeMap<>(); + + public AuthScopeRepository() { + //userinfo.email should always be requested, as it is required for authentication + add(AuthScopeExpressions.interpret(Constant.API_EMAIL_SCOPE)); + } + + public void add(AuthScopeExpression scopeExpression) { + for (String scope : scopeExpression.getAllScopes()) { + String description = MoreObjects.firstNonNull(GOOGLE_SCOPE_DESCRIPTIONS.get(scope), scope); + descriptionsByScope.put(scope, description); + } + } + + /** + * Returns the added scopes and their descriptions. + * Unknown scopes will have the scope itself as description. + * + * @return a sorted map containing scopes as key, descriptions as value + */ + public SortedMap getDescriptionsByScope() { + return descriptionsByScope; + } + +} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/EndpointsFlag.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/EndpointsFlag.java new file mode 100644 index 00000000..fac55442 --- /dev/null +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/EndpointsFlag.java @@ -0,0 +1,96 @@ +/* + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.config.model; + +import com.google.common.annotations.VisibleForTesting; + +/** + * These flags control various Endpoints behavior.
+ *
+ * To set one of these enum flags, you can either: + *

+ *
+ * Notes: + *
    + *
  • System properties are evaluated before env variables.
  • + *
  • falsy is defined as a case-insensitive equality with "false".
  • + *
+ */ +public enum EndpointsFlag { + + /** + * Enables the previous behavior of Cloud Endpoints, using untyped "JsonMap" for all Map types. + * By default, schema generation uses "additionalProperties" in JsonSchema to describe Map types + * (both for Discovery and OpenAPI), with a proper description of the value types. Defaults to + * false. + */ + MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA("mapSchema.forceJsonMapSchema", false), + + /** + * When enabled, schema generation will not throw an error when handling Map types with keys that + * are not serializable from / to string (previous Cloud Endpoints behavior). It will still + * probably generate an error when serializing / deserializing these types at runtime. {@link + * #MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA} must be disabled for this to take effect. Defaults to false. + */ + MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES("mapSchema.ignoreUnsupportedKeyTypes", false), + + /** + * Array values in "additionalProperties" are supported by the API Explorer, but not by the Java + * client generation. This flag can be enabled when deploying an API to the server, but should + * always be disabled when generating Java clients. {@link #MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA} must + * be disabled for this to take effect. Defaults to false. + */ + MAP_SCHEMA_SUPPORT_ARRAYS_VALUES("mapSchema.supportArrayValues", false), + + /** + * When enabled, allows use of Jackson serialization annotations. Previously, the Jackson + * annotation introspector was unused because Jackson was a vendored dependency. Now that Jackson + * is an explicit dependency, this can cause conflict with apps that use Jackson annotations for + * reasons outside of using this framework. Defaults to true. + */ + JSON_USE_JACKSON_ANNOTATIONS("json.useJacksonAnnotations", true); + + private static final String ENV_VARIABLE_PREFIX = "ENDPOINTS_"; + private static final String SYSTEM_PROPERTY_PREFIX = "endpoints."; + + @VisibleForTesting + public String envVarName; + @VisibleForTesting + public String systemPropertyName; + private boolean defaultValue; + + EndpointsFlag(String systemPropertySuffix, boolean defaultValue) { + this.envVarName = ENV_VARIABLE_PREFIX + name(); + this.systemPropertyName = SYSTEM_PROPERTY_PREFIX + systemPropertySuffix; + this.defaultValue = defaultValue; + } + + public boolean isEnabled() { + String envVar = System.getenv(envVarName); + String systemProperty = System.getProperty(systemPropertyName); + if (systemProperty != null) { + return !"false".equalsIgnoreCase(systemProperty); + } else if (envVar != null) { + return !"false".equalsIgnoreCase(envVar); + } + return defaultValue; + } +} diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/FieldType.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/FieldType.java index 37d1b380..b96f10b4 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/FieldType.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/FieldType.java @@ -2,7 +2,6 @@ import com.google.api.server.spi.types.DateAndTime; import com.google.api.server.spi.types.SimpleDate; -import com.google.appengine.api.datastore.Blob; import com.google.common.collect.ImmutableMap; import com.google.common.reflect.TypeToken; @@ -19,7 +18,7 @@ public enum FieldType { INT32("integer", "int32", "Integer"), INT64("string", "int64", "Long"), FLOAT("number", "float", "Float"), - DOUBLE("number", null, "Double"), + DOUBLE("number", "double", "Double"), DATE("string", "date", "Date"), DATE_TIME("string", "date-time", "DateTime"), BOOLEAN("boolean", null, "Boolean"), @@ -50,31 +49,40 @@ public String getCollectionName() { return collectionName; } - private static final ImmutableMap TYPE_MAP = - ImmutableMap.builder() - .put(String.class, STRING) - .put(Short.class, INT16) - .put(Short.TYPE, INT16) - .put(Byte.class, INT8) - .put(Byte.TYPE, INT8) - .put(Character.class, STRING) - .put(Character.TYPE, STRING) - .put(Integer.class, INT32) - .put(Integer.TYPE, INT32) - .put(Long.class, STRING) - .put(Long.TYPE, STRING) - .put(Float.class, FLOAT) - .put(Float.TYPE, FLOAT) - .put(Double.class, DOUBLE) - .put(Double.TYPE, DOUBLE) - .put(Boolean.class, BOOLEAN) - .put(Boolean.TYPE, BOOLEAN) - .put(Date.class, DATE_TIME) - .put(DateAndTime.class, DATE_TIME) - .put(SimpleDate.class, DATE) - .put(byte[].class, BYTE_STRING) - .put(Blob.class, BYTE_STRING) - .build(); + private static final ImmutableMap TYPE_MAP; + + static { + ImmutableMap.Builder builder = ImmutableMap.builder() + .put(String.class, STRING) + .put(Short.class, INT16) + .put(Short.TYPE, INT16) + .put(Byte.class, INT8) + .put(Byte.TYPE, INT8) + .put(Character.class, STRING) + .put(Character.TYPE, STRING) + .put(Integer.class, INT32) + .put(Integer.TYPE, INT32) + .put(Long.class, INT64) + .put(Long.TYPE, INT64) + .put(Float.class, FLOAT) + .put(Float.TYPE, FLOAT) + .put(Double.class, DOUBLE) + .put(Double.TYPE, DOUBLE) + .put(Boolean.class, BOOLEAN) + .put(Boolean.TYPE, BOOLEAN) + .put(Date.class, DATE_TIME) + .put(DateAndTime.class, DATE_TIME) + .put(SimpleDate.class, DATE) + .put(byte[].class, BYTE_STRING); + try { + builder.put( + FieldType.class.getClassLoader().loadClass("com.google.appengine.api.datastore.Blob"), + BYTE_STRING); + } catch (ClassNotFoundException e) { + // Do nothing; if we're on Flex, this class won't exist. + } + TYPE_MAP = builder.build(); + } public static FieldType fromType(TypeToken type) { FieldType ft = TYPE_MAP.get(type.getRawType()); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Schema.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Schema.java index 1fbeca12..6658e566 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Schema.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Schema.java @@ -16,10 +16,14 @@ public abstract class Schema { /** The name of the schema. */ public abstract String name(); public abstract String type(); + @Nullable public abstract String description(); /** A map from field names to fields for the schema. */ public abstract ImmutableSortedMap fields(); + /** If the schema is a map, a reference to the map value type. */ + @Nullable public abstract Field mapValueSchema(); + /** * If the schema is an enum, a list of possible enum values in their string representation. */ @@ -44,7 +48,9 @@ public abstract static class Builder { public abstract Builder setName(String name); public abstract Builder setType(String type); + public abstract Builder setDescription(String description); public abstract Builder setFields(ImmutableSortedMap fields); + public abstract Builder setMapValueSchema(Field mapValueSchema); public Builder addField(String name, Field field) { fieldsBuilder.put(name, field); return this; @@ -76,6 +82,8 @@ public static abstract class Field { /** The type classification of the field. */ public abstract FieldType type(); + @Nullable public abstract String description(); + /** * If {@link #type()} is {@link FieldType#OBJECT}, a reference to the schema type that the field * refers to. @@ -97,6 +105,7 @@ public static Builder builder() { public abstract static class Builder { public abstract Builder setName(String name); public abstract Builder setType(FieldType type); + public abstract Builder setDescription(String description); public abstract Builder setSchemaReference(SchemaReference ref); public abstract Builder setArrayItemSchema(Field schema); public abstract Field build(); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/SchemaRepository.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/SchemaRepository.java index 21832bc8..56dc21cd 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/SchemaRepository.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/SchemaRepository.java @@ -2,6 +2,7 @@ import com.google.api.client.util.Maps; import com.google.api.server.spi.TypeLoader; +import com.google.api.server.spi.config.Description; import com.google.api.server.spi.config.ResourcePropertySchema; import com.google.api.server.spi.config.ResourceSchema; import com.google.api.server.spi.config.annotationreader.ApiAnnotationIntrospector; @@ -10,11 +11,13 @@ import com.google.api.server.spi.config.model.Schema.Field; import com.google.api.server.spi.config.model.Schema.SchemaReference; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.reflect.TypeToken; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -40,11 +43,23 @@ public class SchemaRepository { .setType("object") .build(); + private static final EnumSet SUPPORTED_MAP_KEY_TYPES = EnumSet.of( + FieldType.STRING, + FieldType.ENUM, + FieldType.BOOLEAN, + FieldType.INT8, FieldType.INT16, FieldType.INT32, FieldType.INT64, + FieldType.FLOAT, FieldType.DOUBLE, + FieldType.DATE, FieldType.DATE_TIME + ); + @VisibleForTesting static final String ARRAY_UNUSED_MSG = "unused for array items"; + @VisibleForTesting + static final String MAP_UNUSED_MSG = "unused for map values"; private final Multimap schemaByApiKeys = LinkedHashMultimap.create(); - private final Map, Schema>> types = Maps.newHashMap(); + private final Map, Schema>> types + = Maps.newLinkedHashMap(); private final ResourceSchemaProvider resourceSchemaProvider = new JacksonResourceSchemaProvider(); private final TypeLoader typeLoader; @@ -88,20 +103,20 @@ public Schema getOrAdd(TypeToken type, ApiConfig config) { /** * Gets all schema for an API key. */ - public List getAllSchemaForApi(ApiKey apiKey) { + public ImmutableList getAllSchemaForApi(ApiKey apiKey) { return ImmutableList.copyOf(schemaByApiKeys.get(apiKey.withoutRoot())); } /** * Gets all schema for an API config. * - * @return a {@link Map} from {@link TypeToken} to {@link Schema}. If there are no schema for - * this config, an empty map is returned. + * @return a {@link Map} from {@link TypeToken} to {@link Schema}. If there are no schema for this + * config, an empty map is returned. */ private Map, Schema> getAllTypesForConfig(ApiConfig config) { Map, Schema> typesForConfig = types.get(config.getSerializationConfig()); if (typesForConfig == null) { - typesForConfig = Maps.newHashMap(); + typesForConfig = Maps.newLinkedHashMap(); types.put(config.getSerializationConfig(), typesForConfig); } return typesForConfig; @@ -116,7 +131,7 @@ private Schema getOrCreateTypeForConfig( // If the schema is a placeholder, it's currently being constructed and will be added when // the type construction is complete. if (schema != PLACEHOLDER_SCHEMA) { - schemaByApiKeys.put(key, schema); + addSchemaToApi(key, schema); } return schema; } @@ -128,7 +143,7 @@ private Schema getOrCreateTypeForConfig( throw new IllegalArgumentException("Can't add a primitive type as a resource"); } else if (arrayItemType != null) { Field.Builder arrayItemSchema = Field.builder().setName(ARRAY_UNUSED_MSG); - fillInFieldInformation(arrayItemSchema, arrayItemType, typesForConfig, config); + fillInFieldInformation(arrayItemSchema, arrayItemType, null, typesForConfig, config); schema = Schema.builder() .setName(Types.getSimpleName(type, config.getSerializationConfig())) .setType("object") @@ -146,16 +161,26 @@ private Schema getOrCreateTypeForConfig( schemaByApiKeys.put(key, ANY_SCHEMA); return ANY_SCHEMA; } else if (Types.isMapType(type)) { - typesForConfig.put(type, MAP_SCHEMA); - schemaByApiKeys.put(key, MAP_SCHEMA); - return MAP_SCHEMA; + schema = MAP_SCHEMA; + final TypeToken> mapSupertype = type.getSupertype(Map.class); + final boolean hasConcreteKeyValue = Types.isConcreteType(mapSupertype.getType()); + boolean forceJsonMapSchema = EndpointsFlag.MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.isEnabled(); + if (hasConcreteKeyValue && !forceJsonMapSchema) { + schema = createMapSchema(mapSupertype, typesForConfig, config).or(schema); + } + typesForConfig.put(type, schema); + schemaByApiKeys.put(key, schema); + return schema; } else if (Types.isEnumType(type)) { Schema.Builder builder = Schema.builder() .setName(Types.getSimpleName(type, config.getSerializationConfig())) .setType("string"); - for (Object enumConstant : type.getRawType().getEnumConstants()) { - builder.addEnumValue(enumConstant.toString()); - builder.addEnumDescription(""); + for (java.lang.reflect.Field field : type.getRawType().getFields()) { + if (field.isEnumConstant()) { + builder.addEnumValue(field.getName()); + Description description = field.getAnnotation(Description.class); + builder.addEnumDescription(description == null ? "" : description.value()); + } } schema = builder.build(); typesForConfig.put(type, schema); @@ -169,6 +194,57 @@ private Schema getOrCreateTypeForConfig( } } + private void addSchemaToApi(ApiKey key, Schema schema) { + if (schemaByApiKeys.containsEntry(key, schema)) { + return; + } + schemaByApiKeys.put(key, schema); + for (Field f : schema.fields().values()) { + while (f.type() == FieldType.ARRAY) { + f = f.arrayItemSchema(); + } + if (f.type() == FieldType.OBJECT || f.type() == FieldType.ENUM) { + addSchemaToApi(key, f.schemaReference().get()); + } + } + Field mapValueSchema = schema.mapValueSchema(); + if (mapValueSchema != null && mapValueSchema.schemaReference() != null) { + addSchemaToApi(key, mapValueSchema.schemaReference().get()); + } + } + + private Optional createMapSchema( + TypeToken> mapType, Map, Schema> typesForConfig, ApiConfig config) { + FieldType keyFieldType = FieldType.fromType(Types.getTypeParameter(mapType, 0)); + boolean supportedKeyType = SUPPORTED_MAP_KEY_TYPES.contains(keyFieldType); + if (!supportedKeyType) { + String message = "Map field type '" + mapType + "' has a key type not serializable to String"; + if (EndpointsFlag.MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.isEnabled()) { + System.err.println(message + ", its schema will be JsonMap"); + } else { + throw new IllegalArgumentException(message); + } + } + TypeToken valueTypeToken = Types.getTypeParameter(mapType, 1); + FieldType valueFieldType = FieldType.fromType(valueTypeToken); + boolean supportArrayValues = EndpointsFlag.MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.isEnabled(); + boolean supportedValueType = supportArrayValues || valueFieldType != FieldType.ARRAY; + if (!supportedValueType) { + System.err.println("Map field type '" + mapType + "' " + + "has an array-like value type, its schema will be JsonMap"); + } + if (!supportedKeyType || !supportedValueType) { + return Optional.absent(); + } + TypeToken valueSchemaType = ApiAnnotationIntrospector.getSchemaType(valueTypeToken, config); + Schema.Builder builder = Schema.builder() + .setName(Types.getSimpleName(mapType, config.getSerializationConfig())) + .setType("object"); + Field.Builder fieldBuilder = Field.builder().setName(MAP_UNUSED_MSG); + fillInFieldInformation(fieldBuilder, valueSchemaType, null, typesForConfig, config); + return Optional.of(builder.setMapValueSchema(fieldBuilder.build()).build()); + } + private Schema createBeanSchema( TypeToken type, Map, Schema> typesForConfig, ApiConfig config) { Schema.Builder builder = Schema.builder() @@ -177,10 +253,12 @@ private Schema createBeanSchema( ResourceSchema schema = resourceSchemaProvider.getResourceSchema(type, config); for (Entry entry : schema.getProperties().entrySet()) { String propertyName = entry.getKey(); - TypeToken propertyType = entry.getValue().getType(); + ResourcePropertySchema propertySchema = entry.getValue(); + TypeToken propertyType = propertySchema.getType(); if (propertyType != null) { Field.Builder fieldBuilder = Field.builder().setName(propertyName); - fillInFieldInformation(fieldBuilder, propertyType, typesForConfig, config); + fillInFieldInformation(fieldBuilder, propertyType, propertySchema.getDescription(), + typesForConfig, config); builder.addField(propertyName, fieldBuilder.build()); } } @@ -188,16 +266,21 @@ private Schema createBeanSchema( } private void fillInFieldInformation(Field.Builder builder, TypeToken fieldType, - Map, Schema> typesForConfig, ApiConfig config) { + String description, Map, Schema> typesForConfig, ApiConfig config) { FieldType ft = FieldType.fromType(fieldType); builder.setType(ft); + builder.setDescription(description); if (ft == FieldType.OBJECT || ft == FieldType.ENUM) { getOrCreateTypeForConfig(fieldType, typesForConfig, config); builder.setSchemaReference(SchemaReference.create(this, config, fieldType)); } else if (ft == FieldType.ARRAY) { Field.Builder arrayItemBuilder = Field.builder().setName(ARRAY_UNUSED_MSG); - fillInFieldInformation(arrayItemBuilder, Types.getArrayItemType(fieldType), - typesForConfig, config); + fillInFieldInformation( + arrayItemBuilder, + ApiAnnotationIntrospector.getSchemaType(Types.getArrayItemType(fieldType), config), + null, + typesForConfig, + config); builder.setArrayItemSchema(arrayItemBuilder.build()); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/StandardParameters.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/StandardParameters.java index 119b4ef2..b73bd5ee 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/StandardParameters.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/StandardParameters.java @@ -15,6 +15,7 @@ */ package com.google.api.server.spi.config.model; +import com.google.api.server.spi.EndpointsContext; import com.google.common.collect.ImmutableSet; import javax.servlet.http.HttpServletRequest; @@ -45,8 +46,12 @@ public static boolean isStandardParamName(String paramName) { return STANDARD_PARAM_NAMES.contains(paramName); } - public static boolean shouldPrettyPrint(HttpServletRequest request) { + public static boolean shouldPrettyPrint(EndpointsContext context) { + HttpServletRequest request = context.getRequest(); String prettyPrintStr = request.getParameter("prettyPrint"); - return prettyPrintStr == null || "true".equals(prettyPrintStr.toLowerCase()); + if (prettyPrintStr == null) { + return context.isPrettyPrintEnabled(); + } + return "true".equals(prettyPrintStr.toLowerCase()); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Types.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Types.java index b2eb3a0b..1a3d80d2 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Types.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/model/Types.java @@ -21,16 +21,21 @@ import com.google.api.server.spi.config.ResourceTransformer; import com.google.api.server.spi.config.Transformer; import com.google.api.server.spi.response.CollectionResponse; +import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.reflect.TypeToken; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; +import java.util.Arrays; import java.util.Collection; import java.util.Map; +import javax.annotation.Nullable; + /** * Utilities for dealing with type information. */ @@ -59,6 +64,30 @@ public static boolean isMapType(TypeToken type) { return type.isSubtypeOf(Map.class) && !isJavaClientEntity(type); } + /** + * Returns true if this type is not parameterized, or has only concrete type variables (checked + * recursively on parameterized type variables). + */ + public static boolean isConcreteType(Type type) { + if (type instanceof ParameterizedType) { + Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments(); + return Iterables.all(Arrays.asList(typeArguments), new Predicate() { + @Override + public boolean apply(@Nullable Type input) { + return isConcreteType(input); + } + }); + } + if (type instanceof GenericArrayType) { + return isConcreteType(((GenericArrayType) type).getGenericComponentType()); + } + if (type instanceof Class) { + return true; + } + //matches instanceof TypeVariable and WildcardType + return false; + } + /** * Returns whether or not this type is a Google Java client library entity. */ diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/config/validation/ApiConfigValidator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/config/validation/ApiConfigValidator.java index 241902c4..e605420b 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/config/validation/ApiConfigValidator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/config/validation/ApiConfigValidator.java @@ -16,6 +16,7 @@ package com.google.api.server.spi.config.validation; import com.google.api.client.util.Strings; +import com.google.api.server.spi.TypeLoader; import com.google.api.server.spi.config.ApiConfigInconsistency; import com.google.api.server.spi.config.Transformer; import com.google.api.server.spi.config.model.ApiClassConfig; @@ -26,13 +27,16 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.model.ApiNamespaceConfig; import com.google.api.server.spi.config.model.ApiParameterConfig; +import com.google.api.server.spi.config.model.ApiParameterConfig.Classification; +import com.google.api.server.spi.config.model.Schema; +import com.google.api.server.spi.config.model.SchemaRepository; import com.google.api.server.spi.config.model.Serializers; import com.google.api.server.spi.config.model.Types; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import com.google.common.flogger.FluentLogger; import com.google.common.reflect.TypeToken; - import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Collection; @@ -50,12 +54,23 @@ * @author Eric Orth */ public class ApiConfigValidator { + private static final FluentLogger log = FluentLogger.forEnclosingClass(); + // The underscore is allowed in the API name because of very old legacy reasons, despite the + // annotation documentation stating otherwise. private static final Pattern API_NAME_PATTERN = Pattern.compile( - "^[a-z]+[A-Za-z0-9]*$"); + "^[a-z]+[A-Za-z0-9_]*$"); private static final Pattern API_METHOD_NAME_PATTERN = Pattern.compile( "^\\w+(\\.\\w+)*$"); + private final TypeLoader typeLoader; + private final SchemaRepository schemaRepository; + + public ApiConfigValidator(TypeLoader typeLoader, SchemaRepository schemaRepository) { + this.typeLoader = typeLoader; + this.schemaRepository = schemaRepository; + } + /** * Validates all configurations for a single API. Makes sure the API-level configuration matches * for all classes and that the contained configuration is valid and can be turned into a *.api @@ -170,6 +185,7 @@ private void validateMethods(ApiClassConfig.MethodConfigMap configMap, validateRestSignatureUnique(methodConfig, restfulSignatures); validateBackendMethodNameUnique(methodConfig, javaMethodNames); validateMethod(methodConfig); + validateResourceAndFieldNames(methodConfig); } } } @@ -198,6 +214,24 @@ private void validateBackendMethodNameUnique(ApiMethodConfig methodConfig, } } + private void validateResourceAndFieldNames(ApiMethodConfig methodConfig) + throws PropertyParameterNameConflictException { + for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) { + if (parameterConfig.getClassification() == Classification.RESOURCE) { + Schema schema = schemaRepository.getOrAdd( + parameterConfig.getSchemaBaseType(), methodConfig.getApiConfig()); + Set fieldNames = schema.fields().keySet(); + for (ApiParameterConfig parameter : methodConfig.getParameterConfigs()) { + if (parameter.getClassification() == Classification.API_PARAMETER && + !"id".equals(parameter.getName()) && fieldNames.contains(parameter.getName())) { + log.atWarning().log("Parameter %s conflicts with a resource field name. This may " + + "result in unexpected values in the request.", parameter.getName()); + } + } + } + } + } + private void validateMethod(ApiMethodConfig config) throws ApiMethodConfigInvalidException, ApiParameterConfigInvalidException { if (!API_METHOD_NAME_PATTERN.matcher(config.getName()).matches()) { @@ -212,6 +246,11 @@ private void validateMethod(ApiMethodConfig config) throws ApiMethodConfigInvali validateParameter(parameter, parameterNames, config.getPathParameters()); } validateThirdPartyAuth(config); + + TypeToken returnType = config.getReturnType(); + if (typeLoader.isSchemaType(returnType) || Types.isEnumType(returnType)) { + throw new InvalidReturnTypeException(config, returnType); + } } private void validateThirdPartyAuth(ApiMethodConfig config) diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/AbstractDiscoveryProvider.java b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/AbstractDiscoveryProvider.java index 750219ee..87117cde 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/AbstractDiscoveryProvider.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/AbstractDiscoveryProvider.java @@ -7,15 +7,13 @@ import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; - -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; /** * Base class for providing discovery data. */ abstract class AbstractDiscoveryProvider implements DiscoveryProvider { - protected static final Logger logger = - Logger.getLogger(AbstractDiscoveryProvider.class.getName()); + protected static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Function CONFIG_TO_ROOTLESS_KEY = new Function() { @Override public ApiKey apply(ApiConfig config) { @@ -39,7 +37,7 @@ ImmutableList getApiConfigs(String name, String version) ApiKey key = new ApiKey(name, version, null /* root */); ImmutableList configs = configsByKey.get(key); if (configs.isEmpty()) { - logger.info("No configuration found for name: " + name + ", version: " + version); + logger.atInfo().log("No configuration found for name: %s, version: %s", name, version); throw new NotFoundException("Not Found"); } return configs; diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/CachingDiscoveryProvider.java b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/CachingDiscoveryProvider.java index 045e126c..47ffa6d3 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/CachingDiscoveryProvider.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/CachingDiscoveryProvider.java @@ -24,6 +24,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; +import com.google.common.flogger.FluentLogger; import com.google.common.util.concurrent.UncheckedExecutionException; import java.util.concurrent.Callable; @@ -36,7 +37,7 @@ * A {@link DiscoveryProvider} that caches results and delegates computation to another provider. */ public class CachingDiscoveryProvider implements DiscoveryProvider { - private static final Logger logger = Logger.getLogger(CachingDiscoveryProvider.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int CACHE_EXPIRY_MINS = 10; @@ -99,7 +100,7 @@ public DirectoryList call() throws Exception { if (e.getCause() instanceof InternalServerErrorException) { throw (InternalServerErrorException) e.getCause(); } else { - logger.log(Level.SEVERE, "Could not generate or cache directory", e.getCause()); + logger.atSevere().withCause(e.getCause()).log("Could not generate or cache directory"); throw new InternalServerErrorException("Internal Server Error", e.getCause()); } } @@ -124,7 +125,7 @@ private T getDiscoveryDoc(Cache cache, String root, String name, } else if (e.getCause() instanceof InternalServerErrorException) { throw (InternalServerErrorException) e.getCause(); } else { - logger.log(Level.SEVERE, "Could not generate or cache discovery doc", e.getCause()); + logger.atSevere().withCause(e.getCause()).log("Could not generate or cache discovery doc"); throw new InternalServerErrorException("Internal Server Error", e.getCause()); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/DiscoveryGenerator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/DiscoveryGenerator.java index 5e77baab..4e741acf 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/DiscoveryGenerator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/DiscoveryGenerator.java @@ -15,11 +15,12 @@ */ package com.google.api.server.spi.discovery; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.api.client.util.Preconditions; -import com.google.api.server.spi.Constant; import com.google.api.server.spi.ObjectMapperUtil; import com.google.api.server.spi.Strings; import com.google.api.server.spi.TypeLoader; +import com.google.api.server.spi.config.Description; import com.google.api.server.spi.config.annotationreader.ApiAnnotationIntrospector; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.ApiKey; @@ -31,7 +32,9 @@ import com.google.api.server.spi.config.model.Schema; import com.google.api.server.spi.config.model.Schema.Field; import com.google.api.server.spi.config.model.SchemaRepository; +import com.google.api.server.spi.config.model.AuthScopeRepository; import com.google.api.server.spi.config.model.StandardParameters; +import com.google.api.server.spi.config.scope.AuthScopeExpression; import com.google.api.server.spi.config.scope.AuthScopeExpressions; import com.google.api.services.discovery.model.DirectoryList; import com.google.api.services.discovery.model.DirectoryList.Items; @@ -48,24 +51,26 @@ import com.google.auto.value.AutoValue; import com.google.common.base.Function; import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSortedSet; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import com.google.common.reflect.TypeToken; - -import com.fasterxml.jackson.databind.ObjectMapper; - import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.TreeMap; -import io.swagger.models.Scheme; - /** * Generates discovery documents without contacting the discovery generator service. */ @@ -73,18 +78,12 @@ public class DiscoveryGenerator { private static final Splitter DOT_SPLITTER = Splitter.on('.'); private static final ObjectMapper objectMapper = ObjectMapperUtil.createStandardObjectMapper(); private static final RestDescription REST_SKELETON = new RestDescription() - .setAuth(new Auth() - .setOauth2(new Oauth2() - .setScopes(Maps.newHashMap(ImmutableMap.of( - Constant.API_EMAIL_SCOPE, - new ScopesElement() - .setDescription("View your email address")))))) .setBatchPath("batch") .setDescription("This is an API") .setDiscoveryVersion("v1") .setIcons(new RestDescription.Icons() - .setX16("http://www.google.com/images/icons/product/search-16.gif") - .setX32("http://www.google.com/images/icons/product/search-32.gif")) + .setX16("https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png") + .setX32("https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png")) .setKind("discovery#restDescription") .setParameters(createStandardParameters()) .setProtocol("rest"); @@ -108,22 +107,32 @@ public Result writeDiscovery( } }); ImmutableMap.Builder builder = ImmutableMap.builder(); + // "Default" API versions were determined automagically in legacy endpoints. + // This version only allows to remove an API from default ones by adding + // defaultVersion = AnnotationBoolean.FALSE to @Api + ImmutableSet.Builder preferred = ImmutableSet.builder(); for (ApiKey apiKey : configsByKey.keySet()) { - builder.put(apiKey, writeApi(apiKey, configsByKey.get(apiKey), context, schemaRepository)); + ImmutableList apiConfigs = configsByKey.get(apiKey); + if (context.generateAll || apiConfigs.get(0).getIsDiscoverable()) { + builder.put(apiKey, writeApi(apiKey, apiConfigs, context, schemaRepository)); + // last config takes precedence (same as writeApi) + if (Iterables.getLast(apiConfigs).getIsDefaultVersion()) { + preferred.add(apiKey); + } + } } ImmutableMap discoveryDocs = builder.build(); return Result.builder() .setDiscoveryDocs(discoveryDocs) - .setDirectory(generateDirectory(discoveryDocs, context)) + .setDirectory(generateDirectory(discoveryDocs, preferred.build(), context)) .build(); } private RestDescription writeApi(ApiKey apiKey, Iterable apiConfigs, - DiscoveryContext context, SchemaRepository repo) { + DiscoveryContext context, SchemaRepository schemaRepo) { // The first step is to scan all methods and try to extract a base path, aka a common prefix // for all methods. This prefix must end in a slash and can't contain any path parameters. - String sharedApiPath = computeApiBasePath(apiConfigs); - String servicePath = apiKey.getName() + "/" + apiKey.getVersion() + "/" + sharedApiPath; + String servicePath = computeApiServicePath(apiConfigs); String basePath = context.basePath + "/" + servicePath; RestDescription doc = REST_SKELETON.clone() .setBasePath(basePath) @@ -134,12 +143,20 @@ private RestDescription writeApi(ApiKey apiKey, Iterable apiConfigs, .setServicePath(servicePath) .setVersion(apiKey.getVersion()); + final AuthScopeRepository scopeRepo = new AuthScopeRepository(); + for (ApiConfig config : apiConfigs) { // API descriptions should be identical across all configs, but the last one will take // precedence here if there happens to be divergence. if (config.getDescription() != null) { doc.setDescription(config.getDescription()); } + if (config.getTitle() != null) { + doc.setTitle(config.getTitle()); + } + if (config.getDocumentationLink() != null) { + doc.setDocumentationLink(config.getDocumentationLink()); + } if (config.getNamespaceConfig() != null) { ApiNamespaceConfig namespaceConfig = config.getNamespaceConfig(); if (!Strings.isEmptyOrWhitespace(namespaceConfig.getOwnerName())) { @@ -152,14 +169,24 @@ private RestDescription writeApi(ApiKey apiKey, Iterable apiConfigs, doc.setPackagePath(namespaceConfig.getPackagePath()); } } + if (config.getCanonicalName() != null) { + doc.setCanonicalName(config.getCanonicalName()); + } + scopeRepo.add(config.getScopeExpression()); for (ApiMethodConfig methodConfig : config.getApiClassConfig().getMethods().values()) { if (!methodConfig.isIgnored()) { - writeApiMethod(config, sharedApiPath, doc, methodConfig, repo); + writeApiMethod(config, servicePath, doc, methodConfig, schemaRepo, scopeRepo); } } } - List schemas = repo.getAllSchemaForApi(apiKey); + Map scopeElements = new LinkedHashMap<>(); + for (Entry entry : scopeRepo.getDescriptionsByScope().entrySet()) { + scopeElements.put(entry.getKey(), new ScopesElement().setDescription(entry.getValue())); + } + doc.setAuth(new Auth().setOauth2(new Oauth2().setScopes(scopeElements))); + + List schemas = schemaRepo.getAllSchemaForApi(apiKey); if (!schemas.isEmpty()) { Map docSchemas = Maps.newTreeMap(); for (Schema schema : schemas) { @@ -170,19 +197,22 @@ private RestDescription writeApi(ApiKey apiKey, Iterable apiConfigs, return doc; } - private void writeApiMethod(ApiConfig config, String sharedApiPath, RestDescription doc, - ApiMethodConfig methodConfig, SchemaRepository repo) { + private void writeApiMethod(ApiConfig config, String servicePath, RestDescription doc, + ApiMethodConfig methodConfig, SchemaRepository schemaRepo, AuthScopeRepository scopeRepo) { List parts = DOT_SPLITTER.splitToList(methodConfig.getFullMethodName()); Map methods = getMethodMapFromDoc(doc, parts); Map parameters = convertMethodParameters(methodConfig); + AuthScopeExpression scopeExpression = methodConfig.getScopeExpression(); RestMethod method = new RestMethod() .setDescription(methodConfig.getDescription()) .setHttpMethod(methodConfig.getHttpMethod()) .setId(methodConfig.getFullMethodName()) - .setPath(methodConfig.getPath().substring(sharedApiPath.length())) - .setScopes(AuthScopeExpressions.encodeMutable(methodConfig.getScopeExpression())); - if (!methodConfig.getPathParameters().isEmpty()) { - method.setParameterOrder(Lists.newArrayList(parameters.keySet())); + .setPath(methodConfig.getCanonicalPath().substring(servicePath.length())) + .setScopes(AuthScopeExpressions.encodeMutable(scopeExpression)); + scopeRepo.add(scopeExpression); + List parameterOrder = computeParameterOrder(methodConfig); + if (!parameterOrder.isEmpty()) { + method.setParameterOrder(parameterOrder); } if (!parameters.isEmpty()) { method.setParameters(parameters); @@ -190,18 +220,33 @@ private void writeApiMethod(ApiConfig config, String sharedApiPath, RestDescript ApiParameterConfig requestParamConfig = getAndCheckMethodRequestResource(methodConfig); if (requestParamConfig != null) { TypeToken requestType = requestParamConfig.getSchemaBaseType(); - Schema schema = repo.getOrAdd(requestType, config); + Schema schema = schemaRepo.getOrAdd(requestType, config); method.setRequest(new Request().set$ref(schema.name()).setParameterName("resource")); } if (methodConfig.hasResourceInResponse()) { TypeToken returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), config); - Schema schema = repo.getOrAdd(returnType, config); + Schema schema = schemaRepo.getOrAdd(returnType, config); method.setResponse(new Response().set$ref(schema.name())); } methods.put(parts.get(parts.size() - 1), method); } + private List computeParameterOrder(ApiMethodConfig methodConfig) { + ImmutableSortedSet.Builder queryParamBuilder = ImmutableSortedSet.naturalOrder(); + Collection pathParameters = methodConfig.getPathParameters(); + for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) { + if (parameterConfig.getClassification() == Classification.API_PARAMETER + && !pathParameters.contains(parameterConfig.getName()) + && !parameterConfig.getNullable()) { + queryParamBuilder.add(parameterConfig.getName()); + } + } + List order = new ArrayList<>(pathParameters); + order.addAll(queryParamBuilder.build()); + return order; + } + private JsonSchema convertToDiscoverySchema(Schema schema) { JsonSchema docSchema = new JsonSchema() .setId(schema.name()) @@ -213,6 +258,10 @@ private JsonSchema convertToDiscoverySchema(Schema schema) { } docSchema.setProperties(fields); } + if (schema.mapValueSchema() != null) { + docSchema.setAdditionalProperties(convertToDiscoverySchema(schema.mapValueSchema())); + } + docSchema.setDescription(schema.description()); if (!schema.enumValues().isEmpty()) { docSchema.setEnum(new ArrayList<>(schema.enumValues())); docSchema.setEnumDescriptions(new ArrayList<>(schema.enumDescriptions())); @@ -222,10 +271,13 @@ private JsonSchema convertToDiscoverySchema(Schema schema) { private JsonSchema convertToDiscoverySchema(Field f) { if (f.schemaReference() != null) { - return new JsonSchema().set$ref(f.schemaReference().get().name()); + return new JsonSchema() + .setDescription(f.description()) + .set$ref(f.schemaReference().get().name()); } JsonSchema fieldSchema = new JsonSchema() .setType(f.type().getDiscoveryType()) + .setDescription(f.description()) .setFormat(f.type().getDiscoveryFormat()); if (f.type() == FieldType.ARRAY) { fieldSchema.setItems(convertToDiscoverySchema(f.arrayItemSchema())); @@ -286,17 +338,21 @@ private Map getMethodMapFromDoc(RestDescription doc, List convertMethodParameters(ApiMethodConfig methodConfig) { Map parameters = Maps.newLinkedHashMap(); + Collection pathParameters = methodConfig.getPathParameters(); for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) { if (parameterConfig.getClassification() == Classification.API_PARAMETER) { parameters.put( - parameterConfig.getName(), convertMethodParameter(methodConfig, parameterConfig)); + parameterConfig.getName(), + convertMethodParameter( + parameterConfig, + pathParameters.contains(parameterConfig.getName()))); } } return parameters; } private JsonSchema convertMethodParameter( - ApiMethodConfig methodConfig, ApiParameterConfig parameterConfig) { + ApiParameterConfig parameterConfig, boolean isPathParameter) { JsonSchema schema = new JsonSchema(); TypeToken type; if (parameterConfig.isRepeated()) { @@ -309,9 +365,12 @@ private JsonSchema convertMethodParameter( if (parameterConfig.isEnum()) { List enumValues = Lists.newArrayList(); List enumDescriptions = Lists.newArrayList(); - for (Object enumConstant : type.getRawType().getEnumConstants()) { - enumValues.add(enumConstant.toString()); - enumDescriptions.add(""); // not current supported in annotations + for (java.lang.reflect.Field field : type.getRawType().getFields()) { + if (field.isEnumConstant()) { + enumValues.add(field.getName()); + Description description = field.getAnnotation(Description.class); + enumDescriptions.add(description == null ? "" : description.value()); + } } schema.setEnum(enumValues); schema.setEnumDescriptions(enumDescriptions); @@ -338,7 +397,7 @@ private JsonSchema convertMethodParameter( schema.setDefault(defaultValue); } - if (methodConfig.getPathParameters().contains(parameterConfig.getName())) { + if (isPathParameter) { schema.setLocation("path"); } else { schema.setLocation("query"); @@ -349,18 +408,18 @@ private JsonSchema convertMethodParameter( return schema; } - private String computeApiBasePath(Iterable apiConfigs) { + private String computeApiServicePath(Iterable apiConfigs) { CommonPathPrefixBuilder builder = new CommonPathPrefixBuilder(); for (ApiConfig apiConfig : apiConfigs) { for (ApiMethodConfig methodConfig : apiConfig.getApiClassConfig().getMethods().values()) { - builder.addPath(methodConfig.getPath()); + builder.addPath(methodConfig.getCanonicalPath()); } } return builder.getCommonPrefix(); } private DirectoryList generateDirectory(Map discoveryDocs, - DiscoveryContext context) { + ImmutableSet preferred, DiscoveryContext context) { DirectoryList directory = new DirectoryList() .setDiscoveryVersion("v1") .setKind("discovery#directoryList"); @@ -373,14 +432,15 @@ private DirectoryList generateDirectory(Map discoveryDo .setDiscoveryLink("." + relativePath) .setDiscoveryRestUrl(context.getApiRoot() + "/discovery/v1" + relativePath) .setIcons(new Icons() - .setX16("http://www.google.com/images/icons/product/search-16.gif") - .setX32("http://www.google.com/images/icons/product/search-32.gif")) + .setX16("https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png") + .setX32("https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png")) .setId(doc.getName() + ":" + doc.getVersion()) .setKind("discovery#directoryItem") .setName(doc.getName()) - .setPreferred(true) + .setPreferred(preferred.contains(entry.getKey())) .setTitle(doc.getTitle()) - .setVersion(doc.getVersion())); + .setVersion(doc.getVersion()) + .setDocumentationLink(doc.getDocumentationLink())); } return directory.setItems(items); } @@ -406,6 +466,7 @@ public static class DiscoveryContext { private String scheme = "https"; private String hostname = "myapi.appspot.com"; private String basePath = "/_ah/api"; + private boolean generateAll = true; public String getApiRoot() { return scheme + "://" + hostname + basePath; @@ -443,6 +504,14 @@ public DiscoveryContext setBasePath(String basePath) { this.basePath = Strings.stripTrailingSlash(basePath); return this; } + + /** + * Returns whether or not APIs with discoverable set to false should be generated. + */ + public DiscoveryContext setGenerateAll(boolean generateAll) { + this.generateAll = generateAll; + return this; + } } private static Map createStandardParameters() { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/LocalDiscoveryProvider.java b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/LocalDiscoveryProvider.java index 339b062d..5f949932 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/LocalDiscoveryProvider.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/LocalDiscoveryProvider.java @@ -58,7 +58,11 @@ public DirectoryList getDirectory(String root) { private synchronized void ensureDiscoveryResult() { if (discoveryDocs == null) { DiscoveryGenerator.Result result = generator.writeDiscovery( - getAllApiConfigs(), new DiscoveryContext().setApiRoot(PLACEHOLDER_ROOT), repository); + getAllApiConfigs(), + new DiscoveryContext() + .setApiRoot(PLACEHOLDER_ROOT) + .setGenerateAll(false), + repository); directoryList = result.directory(); ImmutableMap.Builder builder = ImmutableMap.builder(); for (Map.Entry entry : result.discoveryDocs().entrySet()) { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryProvider.java b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryProvider.java index 3bd9d3a2..3fb84c77 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryProvider.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryProvider.java @@ -33,7 +33,6 @@ import java.io.IOException; import java.util.Map; -import java.util.logging.Level; /** * Provides discovery information by proxying to the v1.0 discovery service. @@ -63,7 +62,7 @@ public RestDescription getRestDocument(String root, String name, String version) .generateRest(new com.google.api.services.discovery.model.ApiConfig().setConfig( getApiConfigStringWithRoot(getApiConfigs(name, version), root))).execute(); } catch (IOException | ApiConfigException e) { - logger.log(Level.SEVERE, "Could not generate or cache discovery doc", e); + logger.atSevere().withCause(e).log("Could not generate or cache discovery doc"); throw new InternalServerErrorException("Internal Server Error", e); } } @@ -76,7 +75,7 @@ public RpcDescription getRpcDocument(String root, String name, String version) .generateRpc(new com.google.api.services.discovery.model.ApiConfig().setConfig( getApiConfigStringWithRoot(getApiConfigs(name, version), root))).execute(); } catch (IOException | ApiConfigException e) { - logger.log(Level.SEVERE, "Could not generate or cache discovery doc", e); + logger.atSevere().withCause(e).log("Could not generate or cache discovery doc"); throw new InternalServerErrorException("Internal Server Error", e); } } @@ -90,7 +89,7 @@ public DirectoryList getDirectory(String root) throws InternalServerErrorExcepti configs.setConfigs(Lists.newArrayList(configStrings.values())); return discovery.apis().generateDirectory(configs).execute(); } catch (IOException | ApiConfigException e) { - logger.log(Level.SEVERE, "Could not generate or cache directory", e); + logger.atSevere().withCause(e).log("Could not generate or cache directory"); throw new InternalServerErrorException("Internal Server Error", e); } } @@ -99,7 +98,7 @@ private String getApiConfigStringWithRoot(ImmutableList configs, fina throws InternalServerErrorException, ApiConfigException { Map configMap = configWriter.writeConfig(rewriteConfigsWithRoot(configs, root)); if (configMap.size() != 1) { - logger.severe("config generation yielded more than one API"); + logger.atSevere().log("config generation yielded more than one API"); throw new InternalServerErrorException("Internal Server Error"); } return Iterables.getFirst(configMap.values(), null); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryService.java b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryService.java index 964d83dd..1923a90f 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryService.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/discovery/ProxyingDiscoveryService.java @@ -25,9 +25,7 @@ import com.google.api.services.discovery.model.RestDescription; import com.google.api.services.discovery.model.RpcDescription; import com.google.common.annotations.VisibleForTesting; - -import java.util.logging.Logger; - +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletRequest; /** @@ -43,7 +41,7 @@ + "available, the resource and method details for each API" ) public class ProxyingDiscoveryService { - private static final Logger logger = Logger.getLogger(ProxyingDiscoveryService.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private DiscoveryProvider discoveryProvider; private boolean initialized = false; @@ -87,7 +85,7 @@ public DirectoryList getApiList(HttpServletRequest request) throws InternalServe private void checkIsInitialized() throws InternalServerErrorException { if (!initialized) { - logger.warning("Tried to call discovery before initialization!"); + logger.atWarning().log("Tried to call discovery before initialization!"); throw new InternalServerErrorException("Internal Server Error"); } } @@ -98,7 +96,8 @@ static String getActualRoot(HttpServletRequest request) String uri = request.getRequestURI(); int index = uri.indexOf("discovery/v1/apis"); if (index == -1) { - logger.severe("Could not compute discovery root from url: " + request.getRequestURI()); + logger.atSevere() + .log("Could not compute discovery root from url: %s", request.getRequestURI()); throw new InternalServerErrorException("Internal Server Error"); } StringBuffer url = request.getRequestURL(); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/DispatcherContext.java b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/DispatcherContext.java index e1b3b0a4..d6d392a2 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/DispatcherContext.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/DispatcherContext.java @@ -26,7 +26,7 @@ public class DispatcherContext { private final String httpMethod; private final String path; - private ImmutableMap rawPathParameters; + private ImmutableMap rawPathParameters = ImmutableMap.of(); public DispatcherContext(String httpMethod, String path) { this.httpMethod = Preconditions.checkNotNull(httpMethod, "httpMethod").toUpperCase(); diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/HttpMethod.java b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/HttpMethod.java index ddd1f6c3..53c12f4c 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/HttpMethod.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/HttpMethod.java @@ -15,6 +15,9 @@ */ package com.google.api.server.spi.dispatcher; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; + /** * Possible HTTP methods for use in the dispatcher. */ @@ -23,5 +26,22 @@ enum HttpMethod { POST, PUT, DELETE, - PATCH + PATCH; + + private static final ImmutableMap STRING_TO_ENUM = + ImmutableMap.builder() + .put("GET", GET) + .put("POST", POST) + .put("PUT", PUT) + .put("DELETE", DELETE) + .put("PATCH", PATCH) + .build(); + + /** + * Returns an {@link HttpMethod} corresponding to a string value, or null if it doesn't exist. + */ + public static HttpMethod fromString(String method) { + Preconditions.checkNotNull(method, "method"); + return STRING_TO_ENUM.get(method.toUpperCase()); + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathDispatcher.java b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathDispatcher.java index ce2a7309..01431a0e 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathDispatcher.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathDispatcher.java @@ -42,12 +42,14 @@ private PathDispatcher(Builder builder) { public boolean dispatch(String httpMethod, String path, ContextT context) throws IOException { Preconditions.checkNotNull(httpMethod, "httpMethod"); Preconditions.checkNotNull(path, "path"); - Result> result = - trie.resolve(HttpMethod.valueOf(httpMethod.toUpperCase()), path); - if (result != null) { - context.setRawPathParameters(result.getRawParameters()); - result.getResult().handle(context); - return true; + HttpMethod method = HttpMethod.fromString(httpMethod); + if (method != null) { + Result> result = trie.resolve(method, path); + if (result != null) { + context.setRawPathParameters(result.getRawParameters()); + result.getResult().handle(context); + return true; + } } return false; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathTrie.java b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathTrie.java index c33b1486..563bf519 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathTrie.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/dispatcher/PathTrie.java @@ -22,6 +22,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; +import com.google.common.flogger.FluentLogger; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; @@ -44,7 +45,7 @@ * alphanumeric characters or underscores, and cannot start with a numeric. */ public class PathTrie { - private static final Logger log = Logger.getLogger(PathTrie.class.getName()); + private static final FluentLogger log = FluentLogger.forEnclosingClass(); private static final Splitter PATH_SPLITTER = Splitter.on('/'); private static final String PARAMETER_PATH_SEGMENT = "{}"; private static final Pattern PARAMETER_NAME_PATTERN = Pattern.compile("[a-zA-Z_][a-zA-Z_\\d]*"); @@ -207,7 +208,7 @@ private void add(HttpMethod method, String path, Iterator pathSegments, throw new IllegalArgumentException(String.format("Path '%s' is already mapped", path)); } if (pathExists) { - log.warning(String.format("Path '%s' is already mapped, but overwriting it", path)); + log.atWarning().log("Path '%s' is already mapped, but overwriting it", path); } httpMethodMap.put(method, new MethodInfo<>(parameterNames, value)); } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ApiProxyHandler.java b/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ApiProxyHandler.java index a8adf57f..d362a129 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ApiProxyHandler.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ApiProxyHandler.java @@ -25,19 +25,17 @@ * Serves the API proxy source with the correct API path. */ public class ApiProxyHandler implements DispatcherHandler { - public static final String DEFAULT_API_PATH = "/_ah/api"; - private volatile String cachedProxyHtml; @Override public void handle(EndpointsContext context) throws IOException { if (cachedProxyHtml == null) { - String defaultProxyHtml = IoUtil.readResourceFile(ApiProxyHandler.class, "proxy.html"); - String apiPath = context.getRequest().getServletPath(); - cachedProxyHtml = DEFAULT_API_PATH.equals(apiPath) ? defaultProxyHtml - : defaultProxyHtml.replace(DEFAULT_API_PATH, apiPath); + cachedProxyHtml = IoUtil.readResourceFile(ApiProxyHandler.class, "proxy.html"); } context.getResponse().setContentType("text/html"); + // This is a nonstandard value, but it seems sometimes X-Frame-Options can be injected by + // a proxy. We set this explicitly in hopes that the proxy won't override a set value. + context.getResponse().addHeader("X-Frame-Options", "ALLOWALL"); context.getResponse().getWriter().write(cachedProxyHtml); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/EndpointsMethodHandler.java b/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/EndpointsMethodHandler.java index b1668870..4f7d222d 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/EndpointsMethodHandler.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/EndpointsMethodHandler.java @@ -18,6 +18,7 @@ import com.google.api.server.spi.EndpointMethod; import com.google.api.server.spi.EndpointsContext; import com.google.api.server.spi.Headers; +import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.ServletInitializationParameters; import com.google.api.server.spi.SystemService; import com.google.api.server.spi.config.model.ApiConfig; @@ -32,11 +33,8 @@ import com.google.api.server.spi.response.RestResponseResultWriter; import com.google.api.server.spi.response.ResultWriter; import com.google.common.annotations.VisibleForTesting; - +import com.google.common.flogger.FluentLogger; import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -46,7 +44,7 @@ * (eventually) JSON-RPC dispatching. */ public class EndpointsMethodHandler { - private static final Logger logger = Logger.getLogger(EndpointsMethodHandler.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final ServletInitializationParameters initParameters; private final ServletContext servletContext; private final EndpointMethod endpointMethod; @@ -56,15 +54,15 @@ public class EndpointsMethodHandler { private final String restPath; public EndpointsMethodHandler(ServletInitializationParameters initParameters, - ServletContext servletContext, EndpointMethod endpointMethod, ApiConfig apiConfig, - ApiMethodConfig methodConfig, SystemService systemService) { + ServletContext servletContext, EndpointMethod endpointMethod, ApiMethodConfig methodConfig, + SystemService systemService) { this.initParameters = initParameters; this.servletContext = servletContext; this.endpointMethod = endpointMethod; this.methodConfig = methodConfig; this.systemService = systemService; this.restHandler = new RestHandler(); - this.restPath = createRestPath(apiConfig, methodConfig); + this.restPath = createRestPath(methodConfig); } public String getRestMethod() { @@ -82,23 +80,33 @@ public DispatcherHandler getRestHandler() { @VisibleForTesting protected ParamReader createRestParamReader(EndpointsContext context, ApiSerializationConfig serializationConfig) { - return new RestServletRequestParamReader(endpointMethod, context.getRequest(), - servletContext, serializationConfig, methodConfig, context.getRawPathParameters()); + return new RestServletRequestParamReader(endpointMethod, context, + servletContext, serializationConfig, methodConfig); } - @VisibleForTesting + /** + * Override to customize the serialization of the response body + * + * @return a result writer + * @throws ServiceException if the result writer customization fails + */ protected ResultWriter createResultWriter(EndpointsContext context, + ApiSerializationConfig serializationConfig) throws ServiceException { + return _createResultWriter(context, serializationConfig); + } + + private void writeError(EndpointsContext context, ServiceException error) throws IOException { + _createResultWriter(context, null).writeError(error); + } + + private ResultWriter _createResultWriter(EndpointsContext context, ApiSerializationConfig serializationConfig) { return new RestResponseResultWriter(context.getResponse(), serializationConfig, - StandardParameters.shouldPrettyPrint(context.getRequest()), + StandardParameters.shouldPrettyPrint(context), + initParameters.isAddContentLength(), initParameters.isExceptionCompatibilityEnabled()); } - private ResultWriter createErrorResultWriter(EndpointsContext context) { - // TODO: Convert this to RESTful errors. - return createResultWriter(context, null); - } - private class RestHandler implements DispatcherHandler { @Override public void handle(EndpointsContext context) throws IOException { @@ -111,28 +119,30 @@ public void handle(EndpointsContext context) throws IOException { serviceName); ParamReader reader = createRestParamReader(context, serializationConfig); ResultWriter writer = createResultWriter(context, serializationConfig); - systemService.invokeServiceMethod(service, endpointMethod.getMethod(), reader, writer); if (request.getHeader(Headers.ORIGIN) != null) { HttpServletResponse response = context.getResponse(); CorsHandler.allowOrigin(request, response); CorsHandler.setAccessControlAllowCredentials(response); } + systemService.invokeServiceMethod(service, endpointMethod.getMethod(), reader, writer); + } catch (ServiceException e) { + writeError(context, e); } catch (Exception e) { // All exceptions here are unexpected, including the ServiceException that may be thrown by // the findService call. We return an internal server error and leave the details in the // backend log. - logger.log(Level.WARNING, "exception occurred while invoking backend method", e); - createErrorResultWriter(context) - .writeError(new InternalServerErrorException("backend error")); + logger.atWarning().withCause(e).log("exception occurred while invoking backend method"); + writeError(context, new InternalServerErrorException("backend error")); } } } - private static String createRestPath(ApiConfig apiConfig, ApiMethodConfig methodConfig) { + private static String createRestPath(ApiMethodConfig methodConfig) { // Don't include the api name or version if the path starts with a slash. if (methodConfig.getPath().startsWith("/")) { return methodConfig.getPath().substring(1); } + ApiConfig apiConfig = methodConfig.getApiConfig(); return String.format( "%s/%s/%s", apiConfig.getName(), apiConfig.getVersion(), methodConfig.getPath()); } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ExplorerHandler.java b/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ExplorerHandler.java index 7bf243f5..e961a908 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ExplorerHandler.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/handlers/ExplorerHandler.java @@ -35,7 +35,7 @@ public void handle(EndpointsContext context) throws IOException { } private String getExplorerUrl(HttpServletRequest req, String path) { - String url = Strings.stripTrailingSlash(req.getRequestURL().toString()); + String url = stripRedundantPorts(Strings.stripTrailingSlash(req.getRequestURL().toString())); // This will convert http://localhost:8080/_ah/api/explorer to // http://apis-explorer.appspot.com/apis-explorer/?base=http://localhost:8080/_ah/api& // root=http://localhost:8080/_ah/api @@ -45,4 +45,15 @@ private String getExplorerUrl(HttpServletRequest req, String path) { String apiRoot = url.substring(0, url.length() - path.length() - 1); return EXPLORER_URL + "?base=" + apiRoot + "&root=" + apiRoot; } + + private static String stripRedundantPorts(String url) { + if (url == null) { + return null; + } else if (url.startsWith("http:") && url.contains(":80/")) { + return url.replace(":80/", "/"); + } else if (url.startsWith("https:") && url.contains(":443/")) { + return url.replace(":443/", "/"); + } + return url; + } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/request/Attribute.java b/endpoints-framework/src/main/java/com/google/api/server/spi/request/Attribute.java index c70f0f64..e56b4965 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/request/Attribute.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/request/Attribute.java @@ -26,15 +26,54 @@ * Defines attribute constants passed in Request. */ public class Attribute { + /** + * A {@link com.google.appengine.api.users.User} with the currently authenticated App Engine user. + * + */ public static final String AUTHENTICATED_APPENGINE_USER = "endpoints:Authenticated-AppEngine-User"; + /** + * A {@link com.google.api.server.spi.config.model.ApiMethodConfig} with the current API method's + * configuration. + */ public static final String API_METHOD_CONFIG = "endpoints:Api-Method-Config"; + /** + * A {@link Boolean} indicating if client id whitelist should be checked. + */ public static final String ENABLE_CLIENT_ID_WHITELIST = "endpoints:Enable-Client-Id-Whitelist"; + /** + * @deprecated + */ public static final String RESTRICT_SERVLET = "endpoints:Restrict-Servlet"; + /** + * A {@link Boolean} indicating if the App Engine user should be populated. + */ public static final String REQUIRE_APPENGINE_USER = "endpoints:Require-AppEngine-User"; + /** + * A {@link Boolean} indicating if token-based authentications (OAuth2 and JWT) should be skipped. + */ public static final String SKIP_TOKEN_AUTH = "endpoints:Skip-Token-Auth"; + /** + * A {@link String} with the current request's auth token. + */ public static final String AUTH_TOKEN = "endpoints:Auth-Token"; + /** + * If set, contains a cached OAuth2 {@link com.google.api.server.spi.auth.GoogleAuth.TokenInfo} + * corresponding to the String token in the {@link Attribute#AUTH_TOKEN} {@value AUTH_TOKEN} + * attribute. + * The authentication from {@link com.google.api.server.spi.auth.GoogleOAuth2Authenticator} might + * have failed anyway because of unauthorized client id or scopes. + */ + public static final String TOKEN_INFO = "endpoints:Token-Info"; + /** + * If set, contains a cached instance of a parsed and valid JWT + * {@link com.google.api.client.googleapis.auth.oauth2.GoogleIdToken} corresponding to the String + * token in the {@link Attribute#AUTH_TOKEN} {@value AUTH_TOKEN} attribute. + * The authentication from {@link com.google.api.server.spi.auth.GoogleJwtAuthenticator} might + * have failed anyway because of unauthorized client id or audience. + */ + public static final String ID_TOKEN = "endpoints:Id-Token"; private final HttpServletRequest request; @@ -47,8 +86,8 @@ public static Attribute from(HttpServletRequest request) { return new Attribute(request); } - public Object get(String attr) { - return request.getAttribute(attr); + public T get(String attr) { + return (T) request.getAttribute(attr); } public void set(String attr, Object value) { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/request/Auth.java b/endpoints-framework/src/main/java/com/google/api/server/spi/request/Auth.java index 50b57bb4..a98121e6 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/request/Auth.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/request/Auth.java @@ -16,22 +16,13 @@ package com.google.api.server.spi.request; import com.google.api.server.spi.EnvUtil; +import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.auth.EndpointsAuthenticator; import com.google.api.server.spi.auth.common.User; import com.google.api.server.spi.config.Authenticator; import com.google.api.server.spi.config.Singleton; import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; @@ -39,32 +30,19 @@ * Utilities for end user authentication. */ public class Auth { - private static final Logger logger = Logger.getLogger(Auth.class.getName()); - - private static volatile Map, Authenticator> - authenticatorInstances = new HashMap, Authenticator>(); + private static final Singleton.Instantiator INSTANTIATOR + = new Singleton.Instantiator(new EndpointsAuthenticator()); - private static final Authenticator DEFAULT_AUTHENTICATOR = new EndpointsAuthenticator(); - - private static final Function, Authenticator> - INSTANTIATE_AUTHENTICATOR = new Function, Authenticator>() { - @Override - public Authenticator apply(Class clazz) { - try { - if (clazz.getAnnotation(Singleton.class) != null) { - if (!authenticatorInstances.containsKey(clazz)) { - authenticatorInstances.put(clazz, clazz.newInstance()); - } - return authenticatorInstances.get(clazz); - } else { - return clazz.newInstance(); - } - } catch (IllegalAccessException | InstantiationException e) { - logger.log(Level.WARNING, "Could not instantiate authenticator: " + clazz.getName()); - return null; - } - } - }; + /** + * Must be used to instantiate new {@link Authenticator}s to honor + * {@link com.google.api.server.spi.config.Singleton} contract. + * + * @return a new instance of clazz, or an existing one if clazz is annotated with @{@link + * com.google.api.server.spi.config.Singleton} + */ + public static Authenticator instantiateAuthenticator(Class clazz) { + return INSTANTIATOR.getInstanceOrDefault(clazz); + } private final HttpServletRequest request; private final Attribute attr; @@ -74,7 +52,7 @@ public Authenticator apply(Class clazz) { Auth(HttpServletRequest request) { this.request = request; attr = Attribute.from(request); - config = (ApiMethodConfig) attr.get(Attribute.API_METHOD_CONFIG); + config = attr.get(Attribute.API_METHOD_CONFIG); } static Auth from(HttpServletRequest request) { @@ -83,16 +61,13 @@ static Auth from(HttpServletRequest request) { @VisibleForTesting Iterable getAuthenticatorInstances() { - List> classes = config.getAuthenticators(); - return classes == null ? ImmutableList.of(DEFAULT_AUTHENTICATOR) - : Iterables.filter(Iterables.transform(classes, INSTANTIATE_AUTHENTICATOR), - Predicates.notNull()); + return INSTANTIATOR.getInstancesOrDefault(config.getAuthenticators()); } /** * Authenticate the request and retrieve a {@code User}. Should only run once per request. */ - User authenticate() { + User authenticate() throws ServiceException { Iterable authenticators = getAuthenticatorInstances(); User user = null; if (authenticators != null) { @@ -110,7 +85,7 @@ User authenticate() { * Authenticate the request and retrieve an {@code com.google.appengine.api.users.User}. Should * only run once per request. */ - com.google.appengine.api.users.User authenticateAppEngineUser() { + com.google.appengine.api.users.User authenticateAppEngineUser() throws ServiceException { if (!EnvUtil.isRunningOnAppEngine()) { return null; } @@ -121,7 +96,7 @@ com.google.appengine.api.users.User authenticateAppEngineUser() { return null; } com.google.appengine.api.users.User appEngineUser = - (com.google.appengine.api.users.User) attr.get(Attribute.AUTHENTICATED_APPENGINE_USER); + attr.get(Attribute.AUTHENTICATED_APPENGINE_USER); if (appEngineUser != null) { return appEngineUser; } else { diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/request/ParamReader.java b/endpoints-framework/src/main/java/com/google/api/server/spi/request/ParamReader.java index cf0ab557..526b142c 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/request/ParamReader.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/request/ParamReader.java @@ -15,7 +15,7 @@ */ package com.google.api.server.spi.request; -import com.google.api.server.spi.response.BadRequestException; +import com.google.api.server.spi.ServiceException; /** * Reads a request and returns an array of parameter values. @@ -24,8 +24,8 @@ public interface ParamReader { /** * Reads parameters in JSON into an Object array to be used to invoke an Endpoint method. - * @throws BadRequestException when reading of input stream failed, input JSON is invalid, - * or cannot be mapped into parameter objects. + * @throws ServiceException when reading of input stream failed, input JSON is invalid, + * or cannot be mapped into parameter objects, or user authentication fails. */ - Object[] read() throws BadRequestException; + Object[] read() throws ServiceException; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/request/RestServletRequestParamReader.java b/endpoints-framework/src/main/java/com/google/api/server/spi/request/RestServletRequestParamReader.java index 7df72772..02d2e5e6 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/request/RestServletRequestParamReader.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/request/RestServletRequestParamReader.java @@ -16,18 +16,27 @@ package com.google.api.server.spi.request; import com.google.api.server.spi.EndpointMethod; +import com.google.api.server.spi.EndpointsContext; import com.google.api.server.spi.IoUtil; +import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.Strings; import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.model.ApiParameterConfig; import com.google.api.server.spi.config.model.ApiSerializationConfig; import com.google.api.server.spi.response.BadRequestException; +import com.google.common.base.Splitter; import com.google.common.collect.ImmutableMap; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.flogger.FluentLogger; +import org.apache.commons.fileupload.FileItemIterator; +import org.apache.commons.fileupload.FileItemStream; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.servlet.ServletFileUpload; + import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Enumeration; @@ -47,18 +56,18 @@ * by stuffing path and query parameters into the main request body. */ public class RestServletRequestParamReader extends ServletRequestParamReader { - private static final Logger logger = Logger - .getLogger(RestServletRequestParamReader.class.getName()); + + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final Splitter COMPOSITE_PATH_SPLITTER = Splitter.on(','); private final Map rawPathParameters; private final Map parameterConfigMap; public RestServletRequestParamReader(EndpointMethod method, - HttpServletRequest servletRequest, ServletContext servletContext, - ApiSerializationConfig serializationConfig, ApiMethodConfig methodConfig, - Map rawPathParameters) { - super(method, servletRequest, servletContext, serializationConfig); - this.rawPathParameters = rawPathParameters; + EndpointsContext endpointsContext, ServletContext servletContext, + ApiSerializationConfig serializationConfig, ApiMethodConfig methodConfig) { + super(method, endpointsContext, servletContext, serializationConfig, methodConfig); + this.rawPathParameters = endpointsContext.getRawPathParameters(); ImmutableMap.Builder builder = ImmutableMap.builder(); for (ApiParameterConfig config : methodConfig.getParameterConfigs()) { if (config.getName() != null) { @@ -69,7 +78,7 @@ public RestServletRequestParamReader(EndpointMethod method, } @Override - public Object[] read() throws BadRequestException { + public Object[] read() throws ServiceException { // Assumes input stream to be encoded in UTF-8 // TODO: Take charset from content-type as encoding try { @@ -77,13 +86,36 @@ public Object[] read() throws BadRequestException { if (method.getParameterClasses().length == 0) { return new Object[0]; } - String requestBody = IoUtil.readRequestBody(servletRequest); - logger.log(Level.FINE, "requestBody=" + requestBody); - // Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to - // path and query parameters being injected into the body), bodies are optional here, so we - // create an empty body and inject named parameters to make deserialize work. - JsonNode node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() - : objectReader.readTree(requestBody); + HttpServletRequest servletRequest = endpointsContext.getRequest(); + JsonNode node; + // multipart/form-data requests can be used for requests which have no resource body. In + // this case, each part represents a named parameter instead. + if (ServletFileUpload.isMultipartContent(servletRequest)) { + try { + ServletFileUpload upload = new ServletFileUpload(); + FileItemIterator iter = upload.getItemIterator(servletRequest); + ObjectNode obj = (ObjectNode) objectReader.createObjectNode(); + while (iter.hasNext()) { + FileItemStream item = iter.next(); + if (item.isFormField()) { + obj.put(item.getFieldName(), IoUtil.readStream(item.openStream())); + } else { + throw new BadRequestException("unable to parse multipart form field"); + } + } + node = obj; + } catch (FileUploadException e) { + throw new BadRequestException("unable to parse multipart request", e); + } + } else { + String requestBody = IoUtil.readRequestBody(servletRequest); + logger.atFine().log("requestBody=%s", requestBody); + // Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to + // path and query parameters being injected into the body), bodies are optional here, so we + // create an empty body and inject named parameters to make deserialize work. + node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() + : objectReader.readTree(requestBody); + } if (!node.isObject()) { throw new BadRequestException("expected a JSON object body"); } @@ -98,11 +130,10 @@ public Object[] read() throws BadRequestException { Class parameterClass = parameterMap.get(parameterName); ApiParameterConfig parameterConfig = parameterConfigMap.get(parameterName); if (parameterClass != null && parameterConfig.isRepeated()) { - ArrayNode values = (ArrayNode) objectReader.createArrayNode(); + ArrayNode values = body.putArray(parameterName); for (String value : servletRequest.getParameterValues(parameterName)) { values.add(value); } - body.set(parameterName, values); } else { body.put(parameterName, servletRequest.getParameterValues(parameterName)[0]); } @@ -112,7 +143,14 @@ public Object[] read() throws BadRequestException { String parameterName = entry.getKey(); Class parameterClass = parameterMap.get(parameterName); if (parameterClass != null && !body.has(parameterName)) { - body.put(parameterName, entry.getValue()); + if (parameterConfigMap.get(parameterName).isRepeated()) { + ArrayNode values = body.putArray(parameterName); + for (String value : COMPOSITE_PATH_SPLITTER.split(entry.getValue())) { + values.add(value); + } + } else { + body.put(parameterName, entry.getValue()); + } } } for (Entry entry : parameterConfigMap.entrySet()) { @@ -123,7 +161,7 @@ public Object[] read() throws BadRequestException { return deserializeParams(body); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) { - e.printStackTrace(); + logger.atInfo().withCause(e).log("Unable to read request parameter(s)"); throw new BadRequestException(e); } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/request/ServletRequestParamReader.java b/endpoints-framework/src/main/java/com/google/api/server/spi/request/ServletRequestParamReader.java index 13f10bf1..69ff31d4 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/request/ServletRequestParamReader.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/request/ServletRequestParamReader.java @@ -17,18 +17,25 @@ import com.google.api.server.spi.ConfiguredObjectMapper; import com.google.api.server.spi.EndpointMethod; +import com.google.api.server.spi.EndpointsContext; import com.google.api.server.spi.IoUtil; +import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.auth.common.User; +import com.google.api.server.spi.config.AuthLevel; import com.google.api.server.spi.config.Named; +import com.google.api.server.spi.config.Nullable; import com.google.api.server.spi.config.annotationreader.AnnotationUtil; +import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.model.ApiSerializationConfig; import com.google.api.server.spi.config.model.StandardParameters; import com.google.api.server.spi.response.BadRequestException; +import com.google.api.server.spi.response.UnauthorizedException; import com.google.api.server.spi.types.DateAndTime; import com.google.api.server.spi.types.SimpleDate; import com.google.appengine.api.datastore.Blob; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; +import com.google.common.flogger.FluentLogger; import com.google.common.reflect.TypeToken; import com.fasterxml.jackson.core.JsonParser; @@ -66,9 +73,9 @@ */ public class ServletRequestParamReader extends AbstractParamReader { - private static final Logger logger = Logger.getLogger(ServletRequestParamReader.class.getName()); - + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final Set READER_MODULES; + private static final String APPENGINE_USER_CLASS_NAME = "com.google.appengine.api.users.User"; static { Set modules = new LinkedHashSet<>(); @@ -87,10 +94,17 @@ public class ServletRequestParamReader extends AbstractParamReader { dateAndTimeModule.addDeserializer(DateAndTime.class, new DateAndTimeDeserializer()); modules.add(dateAndTimeModule); - SimpleModule blobModule = - new SimpleModule("blobModule", new Version(1, 0, 0, null, null, null)); - blobModule.addDeserializer(Blob.class, new BlobDeserializer()); - modules.add(blobModule); + try { + // Attempt to load the Blob class, which may not exist outside of App Engine Standard. + ServletRequestParamReader.class.getClassLoader() + .loadClass("com.google.appengine.api.datastore.Blob"); + SimpleModule blobModule = + new SimpleModule("blobModule", new Version(1, 0, 0, null, null, null)); + blobModule.addDeserializer(Blob.class, new BlobDeserializer()); + modules.add(blobModule); + } catch (ClassNotFoundException e) { + // Ignore this error, since we can function without the Blob deserializer. + } READER_MODULES = Collections.unmodifiableSet(modules); } @@ -115,7 +129,7 @@ protected static List getParameterNames(EndpointMethod endpointMethod) } protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalAccessException, - InvocationTargetException, NoSuchMethodException { + InvocationTargetException, NoSuchMethodException, ServiceException { EndpointMethod method = getMethod(); Class[] paramClasses = method.getParameterClasses(); TypeToken[] paramTypes = method.getParameterTypes(); @@ -124,29 +138,45 @@ protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalA for (int i = 0; i < paramClasses.length; i++) { TypeToken type = paramTypes[i]; Class clazz = paramClasses[i]; - if (clazz == User.class) { + if (User.class.isAssignableFrom(clazz)) { // User type parameter requires no Named annotation (ignored if present) - params[i] = getUser(); - logger.log(Level.FINE, "deserialize: User injected into param[{0}]", i); - } else if (clazz == com.google.appengine.api.users.User.class) { + User user = getUser(); + if (user == null && methodConfig != null + && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) { + throw new UnauthorizedException("Valid user credentials are required."); + } + if (user == null || clazz.isAssignableFrom(user.getClass())) { + params[i] = user; + logger.atFine().log("deserialize: User injected into param[%d]", i); + } else { + logger.atWarning().log( + "deserialize: User object of type %s is not assignable to %s. User will be null.", + user.getClass().getName(), clazz.getName()); + } + } else if (APPENGINE_USER_CLASS_NAME.equals(clazz.getName())) { // User type parameter requires no Named annotation (ignored if present) - params[i] = getAppEngineUser(); - logger.log(Level.FINE, "deserialize: App Engine User injected into param[{0}]", i); + com.google.appengine.api.users.User appEngineUser = getAppEngineUser(); + if (appEngineUser == null && methodConfig != null + && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) { + throw new UnauthorizedException("Valid user credentials are required."); + } + params[i] = appEngineUser; + logger.atFine().log("deserialize: App Engine User injected into param[%d]", i); } else if (clazz == HttpServletRequest.class) { // HttpServletRequest type parameter requires no Named annotation (ignored if present) - params[i] = servletRequest; - logger.log(Level.FINE, "deserialize: HttpServletRequest injected into param[{0}]", i); + params[i] = endpointsContext.getRequest(); + logger.atFine().log("deserialize: HttpServletRequest injected into param[%d]", i); } else if (clazz == ServletContext.class) { // ServletContext type parameter requires no Named annotation (ignored if present) params[i] = servletContext; - logger.log(Level.FINE, "deserialize: ServletContext {0} injected into param[{1}]", - new Object[] {params[i], i}); + logger.atFine().log("deserialize: ServletContext %s injected into param[%d]", + params[i], i); } else { String name = parameterNames.get(i); if (Strings.isNullOrEmpty(name)) { params[i] = (node == null) ? null : objectReader.forType(clazz).readValue(node); - logger.log(Level.FINE, "deserialize: {0} {1} injected into unnamed param[{2}]", - new Object[]{clazz, params[i], i}); + logger.atFine().log("deserialize: %s %s injected into unnamed param[%d]", + clazz, params[i], i); } else if (StandardParameters.isStandardParamName(name)) { params[i] = getStandardParamValue(node, name); } else { @@ -163,31 +193,39 @@ protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalA params[i] = objectReader.forType(clazz).readValue(nodeValue); } } - logger.log(Level.FINE, "deserialize: {0} {1} injected into param[{2}] named {3}", - new Object[] {clazz, params[i], i, name}); + if (params[i] == null && isRequiredParameter(method, i)) { + throw new BadRequestException("null value for parameter '" + name + "' not allowed"); + } + logger.atFine().log("deserialize: %s %s injected into param[%d] named {%s}", + clazz, params[i], i, name); } } } return params; } + private boolean isRequiredParameter(EndpointMethod method, int i) { + return AnnotationUtil.getNullableParameter(method.getMethod(), i, Nullable.class) == null + || method.getParameterTypes()[i].isPrimitive(); + } + @VisibleForTesting - User getUser() { - return Auth.from(servletRequest).authenticate(); + User getUser() throws ServiceException { + return Auth.from(endpointsContext.getRequest()).authenticate(); } @VisibleForTesting - com.google.appengine.api.users.User getAppEngineUser() { - return Auth.from(servletRequest).authenticateAppEngineUser(); + com.google.appengine.api.users.User getAppEngineUser() throws ServiceException { + return Auth.from(endpointsContext.getRequest()).authenticateAppEngineUser(); } private Object getStandardParamValue(JsonNode body, String paramName) { if (!StandardParameters.isStandardParamName(paramName)) { throw new IllegalArgumentException("paramName"); } else if (StandardParameters.USER_IP.equals(paramName)) { - return servletRequest.getRemoteAddr(); + return endpointsContext.getRequest().getRemoteAddr(); } else if (StandardParameters.PRETTY_PRINT.equals(paramName)) { - return StandardParameters.shouldPrettyPrint(servletRequest); + return StandardParameters.shouldPrettyPrint(endpointsContext); } JsonNode value = body.get(paramName); if (value == null && StandardParameters.ALT.equals(paramName)) { @@ -260,15 +298,21 @@ public Blob deserialize(JsonParser jsonParser, DeserializationContext context) } } - protected final HttpServletRequest servletRequest; + protected final EndpointsContext endpointsContext; private final ServletContext servletContext; protected final ObjectReader objectReader; + protected final ApiMethodConfig methodConfig; - public ServletRequestParamReader(EndpointMethod method, HttpServletRequest servletRequest, - ServletContext servletContext, ApiSerializationConfig serializationConfig) { + public ServletRequestParamReader( + EndpointMethod method, + EndpointsContext endpointsContext, + ServletContext servletContext, + ApiSerializationConfig serializationConfig, + ApiMethodConfig methodConfig) { super(method); - this.servletRequest = servletRequest; + this.methodConfig = methodConfig; + this.endpointsContext = endpointsContext; this.servletContext = servletContext; LinkedHashSet modules = new LinkedHashSet<>(); @@ -282,12 +326,12 @@ public ServletRequestParamReader(EndpointMethod method, HttpServletRequest servl } @Override - public Object[] read() throws BadRequestException { + public Object[] read() throws ServiceException { // Assumes input stream to be encoded in UTF-8 // TODO: Take charset from content-type as encoding try { - String requestBody = IoUtil.readStream(servletRequest.getInputStream()); - logger.log(Level.FINE, "requestBody=" + requestBody); + String requestBody = IoUtil.readStream(endpointsContext.getRequest().getInputStream()); + logger.atFine().log("requestBody=%s", requestBody); if (requestBody == null || requestBody.trim().isEmpty()) { return new Object[0]; } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/response/RestResponseResultWriter.java b/endpoints-framework/src/main/java/com/google/api/server/spi/response/RestResponseResultWriter.java index cbdfd0bd..5fb1732f 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/response/RestResponseResultWriter.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/response/RestResponseResultWriter.java @@ -15,11 +15,12 @@ */ package com.google.api.server.spi.response; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.api.server.spi.ObjectMapperUtil; import com.google.api.server.spi.ServiceException; import com.google.api.server.spi.config.model.ApiSerializationConfig; import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import java.io.IOException; @@ -31,12 +32,14 @@ */ public class RestResponseResultWriter extends ServletResponseResultWriter { private final boolean enableExceptionCompatibility; + private final ObjectMapper objectMapper; public RestResponseResultWriter( HttpServletResponse servletResponse, ApiSerializationConfig serializationConfig, - boolean prettyPrint, boolean enableExceptionCompatibility) { - super(servletResponse, serializationConfig, prettyPrint); + boolean prettyPrint, boolean addContentLength, boolean enableExceptionCompatibility) { + super(servletResponse, serializationConfig, prettyPrint, addContentLength); this.enableExceptionCompatibility = enableExceptionCompatibility; + this.objectMapper = ObjectMapperUtil.createStandardObjectMapper(serializationConfig); } /** @@ -64,20 +67,20 @@ public void writeError(ServiceException e) throws IOException { e.getReason() : errorMap.getReason(e.getStatusCode()); String domain = !Strings.isNullOrEmpty(e.getDomain()) ? e.getDomain() : errorMap.getDomain(e.getStatusCode()); - write(code, e.getHeaders(), - writeValueAsString(createError(code, reason, domain, e.getMessage()))); + write(code, e.getHeaders(), createError(code, reason, domain, e.getMessage())); } private Object createError(int code, String reason, String domain, String message) { - return ImmutableMap.of( - "error", ImmutableMap.of( - "errors", ImmutableList.of(ImmutableMap.of( - "domain", domain, - "reason", reason, - "message", message - )), - "code", code, - "message", message - )); + ObjectNode topLevel = objectMapper.createObjectNode(); + ObjectNode topError = objectMapper.createObjectNode(); + ObjectNode error = objectMapper.createObjectNode(); + error.put("domain", domain); + error.put("reason", reason); + error.put("message", message); + topError.set("errors", objectMapper.createArrayNode().add(error)); + topError.put("code", code); + topError.put("message", message); + topLevel.set("error", topError); + return topLevel; } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/response/ServletResponseResultWriter.java b/endpoints-framework/src/main/java/com/google/api/server/spi/response/ServletResponseResultWriter.java index e07b215e..783a7256 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/response/ServletResponseResultWriter.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/response/ServletResponseResultWriter.java @@ -23,9 +23,10 @@ import com.google.api.server.spi.types.DateAndTime; import com.google.api.server.spi.types.SimpleDate; import com.google.appengine.api.datastore.Blob; +import com.google.common.io.ByteStreams; +import com.google.common.io.CountingOutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectWriter; @@ -55,21 +56,29 @@ public class ServletResponseResultWriter implements ResultWriter { modules.add(getWriteDateAsStringModule()); modules.add(getWriteDateAndTimeAsStringModule()); modules.add(getWriteSimpleDateAsStringModule()); - modules.add(getWriteBlobAsBase64Module()); + try { + // Attempt to load the Blob class, which may not exist outside of App Engine Standard. + ServletResponseResultWriter.class.getClassLoader() + .loadClass("com.google.appengine.api.datastore.Blob"); + modules.add(getWriteBlobAsBase64Module()); + } catch (ClassNotFoundException e) { + // Ignore this error, since we can function without the Blob deserializer. + } WRITER_MODULES = Collections.unmodifiableSet(modules); } private final HttpServletResponse servletResponse; private final ObjectWriter objectWriter; + private final boolean addContentLength; public ServletResponseResultWriter( HttpServletResponse servletResponse, ApiSerializationConfig serializationConfig) { - this(servletResponse, serializationConfig, false /* prettyPrint */); + this(servletResponse, serializationConfig, false /* prettyPrint */, false /* addContentLength */); } public ServletResponseResultWriter( HttpServletResponse servletResponse, ApiSerializationConfig serializationConfig, - boolean prettyPrint) { + boolean prettyPrint, boolean addContentLength) { this.servletResponse = servletResponse; Set modules = new LinkedHashSet<>(); modules.addAll(WRITER_MODULES); @@ -82,7 +91,18 @@ public ServletResponseResultWriter( if (prettyPrint) { objectWriter = objectWriter.with(new EndpointsPrettyPrinter()); } - this.objectWriter = objectWriter; + this.objectWriter = configureWriter(objectWriter); + this.addContentLength = addContentLength; + } + + /** + * Override to add additional behavior, like partial response, etc. + * + * @param objectWriter the standard object writer + * @return a configured writer (might be wrapped) + */ + protected ObjectWriter configureWriter(ObjectWriter objectWriter) { + return objectWriter; } @Override @@ -90,8 +110,7 @@ public void write(Object response) throws IOException { if (response == null) { write(HttpServletResponse.SC_NO_CONTENT, null, null); } else { - write(HttpServletResponse.SC_OK, null, - writeValueAsString(ResponseUtil.wrapCollection(response))); + write(HttpServletResponse.SC_OK, null, ResponseUtil.wrapCollection(response)); } } @@ -99,11 +118,10 @@ public void write(Object response) throws IOException { public void writeError(ServiceException e) throws IOException { Map errors = new HashMap<>(); errors.put(Constant.ERROR_MESSAGE, e.getMessage()); - write(e.getStatusCode(), e.getHeaders(), - writeValueAsString(errors)); + write(e.getStatusCode(), e.getHeaders(), errors); } - protected void write(int status, Map headers, String content) throws IOException { + protected void write(int status, Map headers, Object content) throws IOException { // write response status code servletResponse.setStatus(status); @@ -117,8 +135,12 @@ protected void write(int status, Map headers, String content) th // write response body if (content != null) { servletResponse.setContentType(SystemService.MIME_JSON); - servletResponse.setContentLength(content.getBytes("UTF-8").length); - servletResponse.getWriter().write(content); + if (addContentLength) { + CountingOutputStream counter = new CountingOutputStream(ByteStreams.nullOutputStream()); + objectWriter.writeValue(counter, content); + servletResponse.setContentLength((int) counter.getCount()); + } + objectWriter.writeValue(servletResponse.getOutputStream(), content); } } @@ -196,13 +218,4 @@ public void serialize(Blob value, JsonGenerator jgen, SerializerProvider provide return writeBlobAsBase64Module; } - // Writes a value as a JSON string and translates Jackson exceptions into IOException. - protected String writeValueAsString(Object value) - throws IOException { - try { - return objectWriter.writeValueAsString(value); - } catch (JsonProcessingException e) { - throw new IOException(e); - } - } } diff --git a/endpoints-framework/src/main/java/com/google/api/server/spi/swagger/SwaggerGenerator.java b/endpoints-framework/src/main/java/com/google/api/server/spi/swagger/SwaggerGenerator.java index 64be4fcf..948fdba4 100644 --- a/endpoints-framework/src/main/java/com/google/api/server/spi/swagger/SwaggerGenerator.java +++ b/endpoints-framework/src/main/java/com/google/api/server/spi/swagger/SwaggerGenerator.java @@ -15,7 +15,6 @@ */ package com.google.api.server.spi.swagger; -import com.google.api.server.spi.Constant; import com.google.api.server.spi.EndpointMethod; import com.google.api.server.spi.Strings; import com.google.api.server.spi.TypeLoader; @@ -26,7 +25,9 @@ import com.google.api.server.spi.config.model.ApiIssuerConfigs; import com.google.api.server.spi.config.model.ApiIssuerConfigs.IssuerConfig; import com.google.api.server.spi.config.model.ApiKey; +import com.google.api.server.spi.config.model.ApiLimitMetricConfig; import com.google.api.server.spi.config.model.ApiMethodConfig; +import com.google.api.server.spi.config.model.ApiMetricCostConfig; import com.google.api.server.spi.config.model.ApiParameterConfig; import com.google.api.server.spi.config.model.FieldType; import com.google.api.server.spi.config.model.Schema; @@ -38,10 +39,12 @@ import com.google.common.base.CaseFormat; import com.google.common.base.Converter; import com.google.common.base.Function; +import com.google.common.base.Joiner; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.reflect.TypeToken; @@ -49,11 +52,14 @@ import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; +import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.TreeMap; import io.swagger.models.Info; import io.swagger.models.Model; @@ -89,10 +95,28 @@ * Generates a {@link Swagger} object representing a set of {@link ApiConfig} objects. */ public class SwaggerGenerator { + private static final Joiner COMMA_JOINER = Joiner.on(','); private static final String API_KEY = "api_key"; private static final String API_KEY_PARAM = "key"; + private static final String MANAGEMENT_DEFINITIONS_KEY = "x-google-management"; + private static final String LIMITS_KEY = "limits"; + private static final String LIMIT_NAME_KEY = "name"; + private static final String LIMIT_METRIC_KEY = "metric"; + private static final String LIMIT_DISPLAY_NAME_KEY = "displayName"; + private static final String LIMIT_DEFAULT_LIMIT_KEY = "values"; + private static final String LIMIT_UNIT_KEY = "unit"; + private static final String LIMIT_PER_MINUTE_PER_PROJECT = "1/min/{project}"; + private static final String METRIC_NAME_KEY = "name"; + private static final String METRIC_VALUE_TYPE_KEY = "valueType"; + private static final String METRIC_VALUE_TYPE = "INT64"; + private static final String METRIC_KIND_KEY = "metricKind"; + private static final String METRIC_KIND = "GAUGE"; + private static final String METRICS_KEY = "metrics"; + private static final String QUOTA_KEY = "quota"; + private static final Converter CONVERTER = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL); + private static final Joiner JOINER = Joiner.on("").skipNulls(); private static final ImmutableMap TYPE_TO_STRING_MAP = ImmutableMap.builder() .put(String.class, "string") @@ -126,19 +150,19 @@ public class SwaggerGenerator { .put(DateAndTime.class, "date-time") .put(Date.class, "date-time") .build(); - private static final ImmutableMap FIELD_TYPE_TO_PROPERTY_MAP = - ImmutableMap.builder() - .put(FieldType.BOOLEAN, new BooleanProperty()) - .put(FieldType.BYTE_STRING, new ByteArrayProperty()) - .put(FieldType.DATE, new DateProperty()) - .put(FieldType.DATE_TIME, new DateTimeProperty()) - .put(FieldType.DOUBLE, new DoubleProperty()) - .put(FieldType.FLOAT, new FloatProperty()) - .put(FieldType.INT8, new IntegerProperty()) - .put(FieldType.INT16, new IntegerProperty()) - .put(FieldType.INT32, new IntegerProperty()) - .put(FieldType.INT64, new LongProperty()) - .put(FieldType.STRING, new StringProperty()) + private static final ImmutableMap> FIELD_TYPE_TO_PROPERTY_CLASS_MAP = + ImmutableMap.>builder() + .put(FieldType.BOOLEAN, BooleanProperty.class) + .put(FieldType.BYTE_STRING, ByteArrayProperty.class) + .put(FieldType.DATE, DateProperty.class) + .put(FieldType.DATE_TIME, DateTimeProperty.class) + .put(FieldType.DOUBLE, DoubleProperty.class) + .put(FieldType.FLOAT, FloatProperty.class) + .put(FieldType.INT8, IntegerProperty.class) + .put(FieldType.INT16, IntegerProperty.class) + .put(FieldType.INT32, IntegerProperty.class) + .put(FieldType.INT64, LongProperty.class) + .put(FieldType.STRING, StringProperty.class) .build(); private static final Function CONFIG_TO_ROOTLESS_KEY = @@ -152,15 +176,21 @@ public ApiKey apply(ApiConfig config) { public Swagger writeSwagger(Iterable configs, boolean writeInternal, SwaggerContext context) throws ApiConfigException { try { - return writeSwagger(configs, writeInternal, context, - new SchemaRepository(new TypeLoader(SwaggerGenerator.class.getClassLoader()))); + TypeLoader typeLoader = new TypeLoader(SwaggerGenerator.class.getClassLoader()); + SchemaRepository repo = new SchemaRepository(typeLoader); + GenerationContext genCtx = new GenerationContext(); + genCtx.validator = new ApiConfigValidator(typeLoader, repo); + genCtx.writeInternal = writeInternal; + genCtx.schemata = new SchemaRepository(typeLoader); + return writeSwagger(configs, context, genCtx); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } - public Swagger writeSwagger(Iterable configs, boolean writeInternal, - SwaggerContext context, SchemaRepository repo) throws ApiConfigException { + private Swagger writeSwagger(Iterable configs, SwaggerContext context, + GenerationContext genCtx) + throws ApiConfigException { ImmutableListMultimap configsByKey = FluentIterable.from(configs) .index(CONFIG_TO_ROOTLESS_KEY); Swagger swagger = new Swagger() @@ -173,52 +203,85 @@ public Swagger writeSwagger(Iterable configs, boolean writeInternal, .title(context.hostname) .version(context.docVersion)); for (ApiKey apiKey : configsByKey.keySet()) { - writeApi(apiKey, configsByKey.get(apiKey), swagger, context, writeInternal, repo); + writeApi(apiKey, configsByKey.get(apiKey), swagger, genCtx); } + writeQuotaDefinitions(swagger, genCtx); return swagger; } + private void writeQuotaDefinitions(Swagger swagger, GenerationContext genCtx) { + if (!genCtx.limitMetrics.isEmpty()) { + Map>> quotaDefinitions = new HashMap<>(); + List> limits = new ArrayList<>(); + List> metrics = new ArrayList<>(); + for (ApiLimitMetricConfig limitMetric : genCtx.limitMetrics.values()) { + metrics.add(ImmutableMap.builder() + .put(METRIC_NAME_KEY, limitMetric.name()) + .put(METRIC_VALUE_TYPE_KEY, METRIC_VALUE_TYPE) + .put(METRIC_KIND_KEY, METRIC_KIND) + .build()); + ImmutableMap.Builder limitBuilder = ImmutableMap.builder() + .put(LIMIT_NAME_KEY, limitMetric.name()) + .put(LIMIT_METRIC_KEY, limitMetric.name()) + .put(LIMIT_DEFAULT_LIMIT_KEY, ImmutableMap.of("STANDARD", limitMetric.limit())) + .put(LIMIT_UNIT_KEY, LIMIT_PER_MINUTE_PER_PROJECT); + if (limitMetric.displayName() != null && !"".equals(limitMetric.displayName())) { + limitBuilder.put(LIMIT_DISPLAY_NAME_KEY, limitMetric.displayName()); + } + limits.add(limitBuilder.build()); + } + quotaDefinitions.put(LIMITS_KEY, limits); + swagger.setVendorExtension(MANAGEMENT_DEFINITIONS_KEY, + ImmutableMap.of(METRICS_KEY, metrics, QUOTA_KEY, quotaDefinitions)); + } + } + private void writeApi(ApiKey apiKey, ImmutableList apiConfigs, - Swagger swagger, SwaggerContext context, boolean writeInternal, SchemaRepository repo) + Swagger swagger, GenerationContext genCtx) throws ApiConfigException { - ApiConfigValidator validator = new ApiConfigValidator(); + // TODO: This may result in duplicate validations in the future if made available online + genCtx.validator.validate(apiConfigs); for (ApiConfig apiConfig : apiConfigs) { - validator.validate(apiConfig); - for (IssuerConfig issuerConfig : apiConfig.getIssuers().asMap().values()) { - addNonConflictingSecurityDefinition(swagger, issuerConfig); + for (ApiLimitMetricConfig limitMetric : apiConfig.getApiLimitMetrics()) { + addNonConflictingApiLimitMetric(genCtx.limitMetrics, limitMetric); } - List legacyAudiences = apiConfig.getApiClassConfig().getAudiences(); - if (legacyAudiences != null && !legacyAudiences.isEmpty()) { - addNonConflictingSecurityDefinition(swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER); - addNonConflictingSecurityDefinition(swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER_ALT); - } - writeApiClass(apiConfig, swagger, context, writeInternal, repo); + writeApiClass(apiConfig, swagger, genCtx); } - List schemas = repo.getAllSchemaForApi(apiKey); - if (!schemas.isEmpty()) { - for (Schema schema : schemas) { - swagger.addDefinition(schema.name(), convertToSwaggerSchema(schema)); + List schemas = genCtx.schemata.getAllSchemaForApi(apiKey); + for (Schema schema : schemas) { + if (schema.enumValues().isEmpty()) { + getOrCreateDefinitionMap(swagger).put(schema.name(), convertToSwaggerSchema(schema)); } } } - private void writeApiClass(ApiConfig apiConfig, Swagger swagger, SwaggerContext context, - boolean writeInternal, SchemaRepository repo) throws ApiConfigException { + private void addNonConflictingApiLimitMetric( + Map limitMetrics, ApiLimitMetricConfig limitMetric) + throws ApiConfigException { + if (limitMetric.equals(limitMetrics.get(limitMetric.name()))) { + throw new ApiConfigException(String.format( + "Multiple limit metric definitions found for metric %s. Metric definitions must have " + + "unique names for all APIs included in the OpenAPI document, or they must have " + + "identical definitions.", limitMetric.name())); + } + limitMetrics.put(limitMetric.name(), limitMetric); + } + + private void writeApiClass(ApiConfig apiConfig, Swagger swagger, + GenerationContext genCtx) throws ApiConfigException { Map methodConfigs = apiConfig.getApiClassConfig().getMethods(); for (Map.Entry methodConfig : methodConfigs.entrySet()) { if (!methodConfig.getValue().isIgnored()) { - EndpointMethod endpointMethod = methodConfig.getKey(); ApiMethodConfig config = methodConfig.getValue(); - writeApiMethod( - config, endpointMethod, apiConfig, swagger, context, writeInternal, repo); + writeApiMethod(config, apiConfig, swagger, genCtx); } } } - private void writeApiMethod(ApiMethodConfig methodConfig, EndpointMethod endpointMethod, - ApiConfig apiConfig, Swagger swagger, SwaggerContext context, boolean writeInternal, - SchemaRepository repo) throws ApiConfigException { - Path path = getOrCreatePath(swagger, apiConfig, methodConfig); + private void writeApiMethod( + ApiMethodConfig methodConfig, ApiConfig apiConfig, Swagger swagger, GenerationContext genCtx) + throws ApiConfigException { + Path path = getOrCreatePath(swagger, methodConfig); Operation operation = new Operation(); operation.setOperationId(getOperationId(apiConfig, methodConfig)); operation.setDescription(methodConfig.getDescription()); @@ -256,7 +319,7 @@ private void writeApiMethod(ApiMethodConfig methodConfig, EndpointMethod endpoin break; case RESOURCE: TypeToken requestType = parameterConfig.getSchemaBaseType(); - Schema schema = repo.getOrAdd(requestType, apiConfig); + Schema schema = genCtx.schemata.getOrAdd(requestType, apiConfig); BodyParameter bodyParameter = new BodyParameter(); bodyParameter.setName("body"); bodyParameter.setSchema(new RefModel(schema.name())); @@ -272,23 +335,34 @@ private void writeApiMethod(ApiMethodConfig methodConfig, EndpointMethod endpoin if (methodConfig.hasResourceInResponse()) { TypeToken returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), apiConfig); - Schema schema = repo.getOrAdd(returnType, apiConfig); + Schema schema = genCtx.schemata.getOrAdd(returnType, apiConfig); response.setSchema(new RefProperty(schema.name())); } operation.response(200, response); - writeAudiences(swagger, methodConfig, writeInternal, operation); + writeAuthConfig(swagger, methodConfig, operation); if (methodConfig.isApiKeyRequired()) { - operation.addSecurity(API_KEY, ImmutableList.of()); + List>> security = operation.getSecurity(); + // Loop through each existing security requirement for this method, which is currently just a + // JWT config id, and add an API key requirement to it. If there are currently no new + // security requirements, add a new one for just the API key. + if (security != null) { + for (Map> securityEntry : security) { + securityEntry.put(API_KEY, ImmutableList.of()); + } + } else { + operation.addSecurity(API_KEY, ImmutableList.of()); + } Map definitions = swagger.getSecurityDefinitions(); if (definitions == null || !definitions.containsKey(API_KEY)) { swagger.securityDefinition(API_KEY, new ApiKeyAuthDefinition(API_KEY_PARAM, In.QUERY)); } } path.set(methodConfig.getHttpMethod().toLowerCase(), operation); + addDefinedMetricCosts(genCtx.limitMetrics, operation, methodConfig.getMetricCosts()); } - private void writeAudiences(Swagger swagger, ApiMethodConfig methodConfig, boolean writeInternal, - Operation operation) throws ApiConfigException { + private void writeAuthConfig(Swagger swagger, ApiMethodConfig methodConfig, Operation operation) + throws ApiConfigException { ApiIssuerAudienceConfig issuerAudiences = methodConfig.getIssuerAudiences(); boolean issuerAudiencesIsEmpty = !issuerAudiences.isSpecified() || issuerAudiences.isEmpty(); List legacyAudiences = methodConfig.getAudiences(); @@ -296,40 +370,43 @@ private void writeAudiences(Swagger swagger, ApiMethodConfig methodConfig, boole if (issuerAudiencesIsEmpty && legacyAudiencesIsEmpty) { return; } - ImmutableMap> audiences = issuerAudiences.asMap(); - // For reversability purposes, we can't use helper data structures here. When Swagger reads - // the document back in, it uses primitive data structures. - ImmutableList.Builder>>> xSecurity = - ImmutableList.builder(); if (!issuerAudiencesIsEmpty) { - for (Map.Entry> entry : audiences.entrySet()) { - operation.addSecurity(entry.getKey(), ImmutableList.of()); - if (writeInternal) { - xSecurity.add(ImmutableMap.of(entry.getKey(), createAudiences(entry.getValue()))); - } + for (String issuer : issuerAudiences.getIssuerNames()) { + ImmutableSet audiences = issuerAudiences.getAudiences(issuer); + IssuerConfig issuerConfig = methodConfig.getApiConfig().getIssuers().getIssuer(issuer); + String fullIssuer = addNonConflictingSecurityDefinition(swagger, issuerConfig, audiences); + operation.addSecurity(fullIssuer, ImmutableList.of()); } } if (!legacyAudiencesIsEmpty) { - addNonConflictingSecurityDefinition(swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER); - addNonConflictingSecurityDefinition(swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER_ALT); - operation.addSecurity(Constant.GOOGLE_ID_TOKEN_NAME, ImmutableList.of()); - operation.addSecurity(Constant.GOOGLE_ID_TOKEN_NAME_HTTPS, ImmutableList.of()); - if (writeInternal) { - ImmutableMap> legacySwaggerAudiences = - createAudiences(legacyAudiences); - xSecurity.add( - ImmutableMap.of(Constant.GOOGLE_ID_TOKEN_NAME, legacySwaggerAudiences)); - xSecurity.add( - ImmutableMap.of(Constant.GOOGLE_ID_TOKEN_NAME_HTTPS, legacySwaggerAudiences)); - } + ImmutableSet legacyAudienceSet = ImmutableSet.copyOf(legacyAudiences); + String fullIssuer = addNonConflictingSecurityDefinition( + swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER, legacyAudienceSet); + String fullAltIssuer = addNonConflictingSecurityDefinition( + swagger, ApiIssuerConfigs.GOOGLE_ID_TOKEN_ISSUER_ALT, legacyAudienceSet); + operation.addSecurity(fullIssuer, ImmutableList.of()); + operation.addSecurity(fullAltIssuer, ImmutableList.of()); } - if (writeInternal) { - operation.setVendorExtension("x-security", xSecurity.build()); + } + + private void addDefinedMetricCosts(Map limitMetrics, + Operation operation, List metricCosts) throws ApiConfigException { + if (!metricCosts.isEmpty()) { + Map costs = new HashMap<>(); + for (ApiMetricCostConfig cost : metricCosts) { + if (!limitMetrics.containsKey(cost.name())) { + throw new ApiConfigException(String.format( + "Could not add a metric cost for metric '%s'. The limit metric must be " + + "defined at the API level.", cost.name())); + } + costs.put(cost.name(), cost.cost()); + } + operation.setVendorExtension("x-google-quota", ImmutableMap.of("metricCosts", costs)); } } private Model convertToSwaggerSchema(Schema schema) { - ModelImpl docSchema = new ModelImpl(); + ModelImpl docSchema = new ModelImpl().type("object"); Map fields = Maps.newLinkedHashMap(); if (!schema.fields().isEmpty()) { for (Field f : schema.fields().values()) { @@ -337,27 +414,44 @@ private Model convertToSwaggerSchema(Schema schema) { } docSchema.setProperties(fields); } - if (!schema.enumValues().isEmpty()) { - docSchema._enum(schema.enumValues()); + if (schema.mapValueSchema() != null) { + docSchema.setAdditionalProperties(convertToSwaggerProperty(schema.mapValueSchema())); } return docSchema; } private Property convertToSwaggerProperty(Field f) { - Property p = FIELD_TYPE_TO_PROPERTY_MAP.get(f.type()); - if (p != null) { - return p; - } else if (f.type() == FieldType.OBJECT || f.type() == FieldType.ENUM) { - return new RefProperty(f.schemaReference().get().name()); - } else if (f.type() == FieldType.ARRAY) { - return new ArrayProperty(convertToSwaggerProperty(f.arrayItemSchema())); + Property p = null; + Class propertyClass = FIELD_TYPE_TO_PROPERTY_CLASS_MAP.get(f.type()); + if (propertyClass != null) { + try { + p = propertyClass.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + //cannot happen, as Property subclasses are guaranteed to have a default constructor + } + } else { + if (f.type() == FieldType.OBJECT) { + p = new RefProperty(f.schemaReference().get().name()); + } else if (f.type() == FieldType.ARRAY) { + p = new ArrayProperty(convertToSwaggerProperty(f.arrayItemSchema())); + } else if (f.type() == FieldType.ENUM) { + p = new StringProperty()._enum(getEnumValues(f.schemaReference().type())); + } + } + if (p == null) { + throw new IllegalArgumentException("could not convert field " + f); + } + //the spec explicitly disallows description on $ref + if (!(p instanceof RefProperty)) { + p.description(f.description()); } - throw new IllegalArgumentException("could not convert field " + f); + return p; } private static String getOperationId(ApiConfig apiConfig, ApiMethodConfig methodConfig) { - return CONVERTER.convert(apiConfig.getName()) + - CONVERTER.convert(methodConfig.getEndpointMethodName()); + return FluentIterable.of(apiConfig.getName(), apiConfig.getVersion(), + apiConfig.getResource(), apiConfig.getApiClassConfig().getResource(), + methodConfig.getEndpointMethodName()).transform(CONVERTER).join(JOINER); } private static Property getSwaggerArrayProperty(TypeToken typeToken) { @@ -382,9 +476,8 @@ private static Property getSwaggerArrayProperty(TypeToken typeToken) { throw new IllegalArgumentException("invalid property type"); } - private Path getOrCreatePath(Swagger swagger, ApiConfig apiConfig, ApiMethodConfig methodConfig) { - String pathStr = - "/" + apiConfig.getName() + "/" + apiConfig.getVersion() + "/" + methodConfig.getPath(); + private Path getOrCreatePath(Swagger swagger, ApiMethodConfig methodConfig) { + String pathStr = "/" + methodConfig.getCanonicalPath(); Path path = swagger.getPath(pathStr); if (path == null) { path = new Path(); @@ -401,6 +494,52 @@ private static List getEnumValues(TypeToken t) { return values; } + private static SecuritySchemeDefinition toScheme( + IssuerConfig issuerConfig, ImmutableSet audiences) { + OAuth2Definition tokenDef = new OAuth2Definition().implicit(""); + tokenDef.setVendorExtension("x-google-issuer", issuerConfig.getIssuer()); + if (!com.google.common.base.Strings.isNullOrEmpty(issuerConfig.getJwksUri())) { + tokenDef.setVendorExtension("x-google-jwks_uri", issuerConfig.getJwksUri()); + } + tokenDef.setVendorExtension("x-google-audiences", COMMA_JOINER.join(audiences)); + return tokenDef; + } + + private Map getOrCreateDefinitionMap(Swagger swagger) { + Map definitions = swagger.getDefinitions(); + if (definitions == null) { + definitions = new LinkedHashMap<>(); + swagger.setDefinitions(definitions); + } + return definitions; + } + + private static Map getOrCreateSecurityDefinitionMap( + Swagger swagger) { + Map securityDefinitions = swagger.getSecurityDefinitions(); + if (securityDefinitions == null) { + securityDefinitions = new LinkedHashMap<>(); + swagger.setSecurityDefinitions(securityDefinitions); + } + return securityDefinitions; + } + + private static String addNonConflictingSecurityDefinition( + Swagger swagger, IssuerConfig issuerConfig, ImmutableSet audiences) + throws ApiConfigException { + Map securityDefinitions = + getOrCreateSecurityDefinitionMap(swagger); + String issuerPlusHash = String.format("%s-%x", issuerConfig.getName(), audiences.hashCode()); + SecuritySchemeDefinition existingDef = securityDefinitions.get(issuerConfig.getName()); + SecuritySchemeDefinition newDef = toScheme(issuerConfig, audiences); + if (existingDef != null && !existingDef.equals(newDef)) { + throw new ApiConfigException( + "Multiple conflicting definitions found for issuer " + issuerConfig.getName()); + } + swagger.securityDefinition(issuerPlusHash, newDef); + return issuerPlusHash; + } + public static class SwaggerContext { private Scheme scheme = Scheme.HTTPS; private String hostname = "myapi.appspot.com"; @@ -444,39 +583,10 @@ public SwaggerContext setDocVersion(String docVersion) { } } - private static ImmutableMap> createAudiences(Iterable audiences) { - return ImmutableMap.>of("audiences", ImmutableList.copyOf(audiences)); - } - - private static SecuritySchemeDefinition toScheme(IssuerConfig issuerConfig) { - OAuth2Definition tokenDef = new OAuth2Definition().implicit(""); - tokenDef.setVendorExtension("x-issuer", issuerConfig.getIssuer()); - if (!com.google.common.base.Strings.isNullOrEmpty(issuerConfig.getJwksUri())) { - tokenDef.setVendorExtension("x-jwks_uri", issuerConfig.getJwksUri()); - } - return tokenDef; - } - - private static Map getOrCreateSecurityDefinitionMap( - Swagger swagger) { - Map securityDefinitions = swagger.getSecurityDefinitions(); - if (securityDefinitions == null) { - securityDefinitions = new HashMap<>(); - swagger.setSecurityDefinitions(securityDefinitions); - } - return securityDefinitions; - } - - private static void addNonConflictingSecurityDefinition( - Swagger swagger, IssuerConfig issuerConfig) throws ApiConfigException { - Map securityDefinitions = - getOrCreateSecurityDefinitionMap(swagger); - SecuritySchemeDefinition existingDef = securityDefinitions.get(issuerConfig.getName()); - SecuritySchemeDefinition newDef = toScheme(issuerConfig); - if (existingDef != null && !existingDef.equals(newDef)) { - throw new ApiConfigException( - "Multiple conflicting definitions found for issuer " + issuerConfig.getName()); - } - swagger.securityDefinition(issuerConfig.getName(), newDef); + private static class GenerationContext { + private final Map limitMetrics = new TreeMap<>(); + private ApiConfigValidator validator; + private boolean writeInternal; + private SchemaRepository schemata; } } diff --git a/endpoints-framework/src/main/resources/com/google/api/server/spi/discovery/googleScopeDescriptions.properties b/endpoints-framework/src/main/resources/com/google/api/server/spi/discovery/googleScopeDescriptions.properties new file mode 100644 index 00000000..4f31122d --- /dev/null +++ b/endpoints-framework/src/main/resources/com/google/api/server/spi/discovery/googleScopeDescriptions.properties @@ -0,0 +1,228 @@ +#Source: https://developers.google.com/identity/protocols/googlescopes +#Wed Aug 01 10:07:10 CEST 2018 +email=View your email address +openid=Authenticate using OpenID Connect +profile=View your basic profile info +https\://mail.google.com/=Read, send, delete, and manage your email +https\://www.google.com/calendar/feeds=Manage your calendars +https\://www.google.com/m8/feeds=Manage your contacts +https\://www.googleapis.com/auth/activity=View the activity history of your Google apps +https\://www.googleapis.com/auth/adexchange.buyer=Manage your Ad Exchange buyer account configuration +https\://www.googleapis.com/auth/adexchange.seller=View and manage your Ad Exchange data +https\://www.googleapis.com/auth/adexchange.seller.readonly=View your Ad Exchange data +https\://www.googleapis.com/auth/admin.datatransfer=View and manage data transfers between users in your organization +https\://www.googleapis.com/auth/admin.datatransfer.readonly=View data transfers between users in your organization +https\://www.googleapis.com/auth/admin.directory.customer=View and manage customer related information +https\://www.googleapis.com/auth/admin.directory.customer.readonly=View customer related information +https\://www.googleapis.com/auth/admin.directory.device.chromeos=View and manage your Chrome OS devices' metadata +https\://www.googleapis.com/auth/admin.directory.device.chromeos.readonly=View your Chrome OS devices' metadata +https\://www.googleapis.com/auth/admin.directory.device.mobile=View and manage your mobile devices' metadata +https\://www.googleapis.com/auth/admin.directory.device.mobile.action=Manage your mobile devices by performing administrative tasks +https\://www.googleapis.com/auth/admin.directory.device.mobile.readonly=View your mobile devices' metadata +https\://www.googleapis.com/auth/admin.directory.domain=View and manage the provisioning of domains for your customers +https\://www.googleapis.com/auth/admin.directory.domain.readonly=View domains related to your customers +https\://www.googleapis.com/auth/admin.directory.group=View and manage the provisioning of groups on your domain +https\://www.googleapis.com/auth/admin.directory.group.member=View and manage group subscriptions on your domain +https\://www.googleapis.com/auth/admin.directory.group.member.readonly=View group subscriptions on your domain +https\://www.googleapis.com/auth/admin.directory.group.readonly=View groups on your domain +https\://www.googleapis.com/auth/admin.directory.notifications=View and manage notifications received on your domain +https\://www.googleapis.com/auth/admin.directory.orgunit=View and manage organization units on your domain +https\://www.googleapis.com/auth/admin.directory.orgunit.readonly=View organization units on your domain +https\://www.googleapis.com/auth/admin.directory.resource.calendar=View and manage the provisioning of calendar resources on your domain +https\://www.googleapis.com/auth/admin.directory.resource.calendar.readonly=View calendar resources on your domain +https\://www.googleapis.com/auth/admin.directory.rolemanagement=Manage delegated admin roles for your domain +https\://www.googleapis.com/auth/admin.directory.rolemanagement.readonly=View delegated admin roles for your domain +https\://www.googleapis.com/auth/admin.directory.user=View and manage the provisioning of users on your domain +https\://www.googleapis.com/auth/admin.directory.user.alias=View and manage user aliases on your domain +https\://www.googleapis.com/auth/admin.directory.user.alias.readonly=View user aliases on your domain +https\://www.googleapis.com/auth/admin.directory.user.readonly=View users on your domain +https\://www.googleapis.com/auth/admin.directory.user.security=Manage data access permissions for users on your domain +https\://www.googleapis.com/auth/admin.directory.userschema=View and manage the provisioning of user schemas on your domain +https\://www.googleapis.com/auth/admin.directory.userschema.readonly=View user schemas on your domain +https\://www.googleapis.com/auth/admin.reports.audit.readonly=View audit reports for your G Suite domain +https\://www.googleapis.com/auth/admin.reports.usage.readonly=View usage reports for your G Suite domain +https\://www.googleapis.com/auth/adsense=View and manage your AdSense data +https\://www.googleapis.com/auth/adsense.readonly=View your AdSense data +https\://www.googleapis.com/auth/adsensehost=View and manage your AdSense host data and associated accounts +https\://www.googleapis.com/auth/analytics=View and manage your Google Analytics data +https\://www.googleapis.com/auth/analytics.edit=Edit Google Analytics management entities +https\://www.googleapis.com/auth/analytics.manage.users=Manage Google Analytics Account users by email address +https\://www.googleapis.com/auth/analytics.manage.users.readonly=View Google Analytics user permissions +https\://www.googleapis.com/auth/analytics.provision=Create a new Google Analytics account along with its default property and view +https\://www.googleapis.com/auth/analytics.readonly=View your Google Analytics data +https\://www.googleapis.com/auth/analytics.user.deletion=Manage Google Analytics user deletion requests +https\://www.googleapis.com/auth/androidenterprise=Manage corporate Android devices +https\://www.googleapis.com/auth/androidmanagement=Manage Android devices and apps for your customers +https\://www.googleapis.com/auth/androidpublisher=View and manage your Google Play Developer account +https\://www.googleapis.com/auth/appengine.admin=View and manage your applications deployed on Google App Engine +https\://www.googleapis.com/auth/apps.groups.migration=Manage messages in groups on your domain +https\://www.googleapis.com/auth/apps.groups.settings=View and manage the settings of a G Suite group +https\://www.googleapis.com/auth/apps.licensing=View and manage G Suite licenses for your domain +https\://www.googleapis.com/auth/apps.order=Manage users on your domain +https\://www.googleapis.com/auth/apps.order.readonly=Manage users on your domain +https\://www.googleapis.com/auth/appstate=View and manage your data for this application +https\://www.googleapis.com/auth/bigquery=View and manage your data in Google BigQuery +https\://www.googleapis.com/auth/bigquery.insertdata=Insert data into Google BigQuery +https\://www.googleapis.com/auth/blogger=Manage your Blogger account +https\://www.googleapis.com/auth/blogger.readonly=View your Blogger account +https\://www.googleapis.com/auth/books=Manage your books +https\://www.googleapis.com/auth/calendar=Manage your calendars +https\://www.googleapis.com/auth/calendar.readonly=View your calendars +https\://www.googleapis.com/auth/classroom.announcements=View and manage announcements in Google Classroom +https\://www.googleapis.com/auth/classroom.announcements.readonly=View announcements in Google Classroom +https\://www.googleapis.com/auth/classroom.courses=Manage your Google Classroom classes +https\://www.googleapis.com/auth/classroom.courses.readonly=View your Google Classroom classes +https\://www.googleapis.com/auth/classroom.coursework.me=Manage your course work and view your grades in Google Classroom +https\://www.googleapis.com/auth/classroom.coursework.me.readonly=View your course work and grades in Google Classroom +https\://www.googleapis.com/auth/classroom.coursework.students=Manage course work and grades for students in the Google Classroom classes you teach and view the course work and grades for classes you administer +https\://www.googleapis.com/auth/classroom.coursework.students.readonly=View course work and grades for students in the Google Classroom classes you teach or administer +https\://www.googleapis.com/auth/classroom.guardianlinks.me.readonly=View your Google Classroom guardians +https\://www.googleapis.com/auth/classroom.guardianlinks.students=View and manage guardians for students in your Google Classroom classes +https\://www.googleapis.com/auth/classroom.guardianlinks.students.readonly=View guardians for students in your Google Classroom classes +https\://www.googleapis.com/auth/classroom.profile.emails=View the email addresses of people in your classes +https\://www.googleapis.com/auth/classroom.profile.photos=View the profile photos of people in your classes +https\://www.googleapis.com/auth/classroom.push-notifications=Receive notifications about your Google Classroom data +https\://www.googleapis.com/auth/classroom.rosters=Manage your Google Classroom class rosters +https\://www.googleapis.com/auth/classroom.rosters.readonly=View your Google Classroom class rosters +https\://www.googleapis.com/auth/classroom.student-submissions.me.readonly=View your course work and grades in Google Classroom +https\://www.googleapis.com/auth/classroom.student-submissions.students.readonly=View course work and grades for students in the Google Classroom classes you teach or administer +https\://www.googleapis.com/auth/cloud-language=Apply machine learning models to reveal the structure and meaning of text +https\://www.googleapis.com/auth/cloud-platform=View and manage your data across Google Cloud Platform services +https\://www.googleapis.com/auth/cloud-platform.read-only=View your data across Google Cloud Platform services +https\://www.googleapis.com/auth/cloud-translation=Translate text from one language to another using Google Translate +https\://www.googleapis.com/auth/cloud-vision=Apply machine learning models to understand and label images +https\://www.googleapis.com/auth/cloud_debugger=Use Stackdriver Debugger +https\://www.googleapis.com/auth/cloudiot=Register and manage devices in the Google Cloud IoT service +https\://www.googleapis.com/auth/cloudruntimeconfig=Manage your Google Cloud Platform services' runtime configuration +https\://www.googleapis.com/auth/compute=View and manage your Google Compute Engine resources +https\://www.googleapis.com/auth/compute.readonly=View your Google Compute Engine resources +https\://www.googleapis.com/auth/contacts=Manage your contacts +https\://www.googleapis.com/auth/contacts.readonly=View your contacts +https\://www.googleapis.com/auth/content=Manage your product listings and accounts for Google Shopping +https\://www.googleapis.com/auth/datastore=View and manage your Google Cloud Datastore data +https\://www.googleapis.com/auth/ddmconversions=Manage DoubleClick Digital Marketing conversions +https\://www.googleapis.com/auth/devstorage.full_control=Manage your data and permissions in Google Cloud Storage +https\://www.googleapis.com/auth/devstorage.read_only=View your data in Google Cloud Storage +https\://www.googleapis.com/auth/devstorage.read_write=Manage your data in Google Cloud Storage +https\://www.googleapis.com/auth/dfareporting=View and manage DoubleClick for Advertisers reports +https\://www.googleapis.com/auth/dfatrafficking=View and manage your DoubleClick Campaign Manager's (DCM) display ad campaigns +https\://www.googleapis.com/auth/documents=View and manage your Google Docs documents +https\://www.googleapis.com/auth/doubleclickbidmanager=View and manage your reports in DoubleClick Bid Manager +https\://www.googleapis.com/auth/doubleclicksearch=View and manage your advertising data in DoubleClick Search +https\://www.googleapis.com/auth/drive=View and manage the files in your Google Drive +https\://www.googleapis.com/auth/drive.appdata=View and manage its own configuration data in your Google Drive +https\://www.googleapis.com/auth/drive.file=View and manage Google Drive files and folders that you have opened or created with this app +https\://www.googleapis.com/auth/drive.metadata=View and manage metadata of files in your Google Drive +https\://www.googleapis.com/auth/drive.metadata.readonly=View metadata for files in your Google Drive +https\://www.googleapis.com/auth/drive.photos.readonly=View the photos, videos and albums in your Google Photos +https\://www.googleapis.com/auth/drive.readonly=View the files in your Google Drive +https\://www.googleapis.com/auth/drive.scripts=Modify your Google Apps Script scripts' behavior +https\://www.googleapis.com/auth/ediscovery=Manage your eDiscovery data +https\://www.googleapis.com/auth/ediscovery.readonly=View your eDiscovery data +https\://www.googleapis.com/auth/firebase=View and administer all your Firebase data and settings +https\://www.googleapis.com/auth/firebase.readonly=View all your Firebase data and settings +https\://www.googleapis.com/auth/fitness.activity.read=View your activity information in Google Fit +https\://www.googleapis.com/auth/fitness.activity.write=View and store your activity information in Google Fit +https\://www.googleapis.com/auth/fitness.blood_glucose.read=View blood glucose data in Google Fit +https\://www.googleapis.com/auth/fitness.blood_glucose.write=View and store blood glucose data in Google Fit +https\://www.googleapis.com/auth/fitness.blood_pressure.read=View blood pressure data in Google Fit +https\://www.googleapis.com/auth/fitness.blood_pressure.write=View and store blood pressure data in Google Fit +https\://www.googleapis.com/auth/fitness.body.read=View body sensor information in Google Fit +https\://www.googleapis.com/auth/fitness.body.write=View and store body sensor data in Google Fit +https\://www.googleapis.com/auth/fitness.body_temperature.read=View body temperature data in Google Fit +https\://www.googleapis.com/auth/fitness.body_temperature.write=View and store body temperature data in Google Fit +https\://www.googleapis.com/auth/fitness.location.read=View your stored location data in Google Fit +https\://www.googleapis.com/auth/fitness.location.write=View and store your location data in Google Fit +https\://www.googleapis.com/auth/fitness.nutrition.read=View nutrition information in Google Fit +https\://www.googleapis.com/auth/fitness.nutrition.write=View and store nutrition information in Google Fit +https\://www.googleapis.com/auth/fitness.oxygen_saturation.read=View oxygen saturation data in Google Fit +https\://www.googleapis.com/auth/fitness.oxygen_saturation.write=View and store oxygen saturation data in Google Fit +https\://www.googleapis.com/auth/fitness.reproductive_health.read=View reproductive health data in Google Fit +https\://www.googleapis.com/auth/fitness.reproductive_health.write=View and store reproductive health data in Google Fit +https\://www.googleapis.com/auth/forms=View and manage your forms in Google Drive +https\://www.googleapis.com/auth/forms.currentonly=View and manage forms that this application has been installed in +https\://www.googleapis.com/auth/fusiontables=Manage your Fusion Tables +https\://www.googleapis.com/auth/fusiontables.readonly=View your Fusion Tables +https\://www.googleapis.com/auth/games=Share your Google+ profile information and view and manage your game activity +https\://www.googleapis.com/auth/genomics=View and manage Genomics data +https\://www.googleapis.com/auth/genomics.readonly=View Genomics data +https\://www.googleapis.com/auth/glass.location=View your location +https\://www.googleapis.com/auth/glass.timeline=View and manage your Glass timeline +https\://www.googleapis.com/auth/gmail.compose=Manage drafts and send emails +https\://www.googleapis.com/auth/gmail.insert=Insert mail into your mailbox +https\://www.googleapis.com/auth/gmail.labels=Manage mailbox labels +https\://www.googleapis.com/auth/gmail.metadata=View your email message metadata such as labels and headers, but not the email body +https\://www.googleapis.com/auth/gmail.modify=View and modify but not delete your email +https\://www.googleapis.com/auth/gmail.readonly=View your email messages and settings +https\://www.googleapis.com/auth/gmail.send=Send email on your behalf +https\://www.googleapis.com/auth/gmail.settings.basic=Manage your basic mail settings +https\://www.googleapis.com/auth/gmail.settings.sharing=Manage your sensitive mail settings, including who can manage your mail +https\://www.googleapis.com/auth/groups=View and manage your Google Groups +https\://www.googleapis.com/auth/jobs=Manage job postings +https\://www.googleapis.com/auth/logging.admin=Administrate log data for your projects +https\://www.googleapis.com/auth/logging.read=View log data for your projects +https\://www.googleapis.com/auth/logging.write=Submit log data for your projects +https\://www.googleapis.com/auth/manufacturercenter=Manage your product listings for Google Manufacturer Center +https\://www.googleapis.com/auth/monitoring=View and write monitoring data for all of your Google and third-party Cloud and API projects +https\://www.googleapis.com/auth/monitoring.read=View monitoring data for all of your Google Cloud and third-party projects +https\://www.googleapis.com/auth/monitoring.write=Publish metric data to your Google Cloud projects +https\://www.googleapis.com/auth/ndev.clouddns.readonly=View your DNS records hosted by Google Cloud DNS +https\://www.googleapis.com/auth/ndev.clouddns.readwrite=View and manage your DNS records hosted by Google Cloud DNS +https\://www.googleapis.com/auth/ndev.cloudman=View and manage your Google Cloud Platform management resources and deployment status information +https\://www.googleapis.com/auth/ndev.cloudman.readonly=View your Google Cloud Platform management resources and deployment status information +https\://www.googleapis.com/auth/plus.circles.read=View your circles and the people and pages in them +https\://www.googleapis.com/auth/plus.circles.write=Manage your circles and add people and pages. People and pages you add to your circles will be notified. Others may see this information publicly. People you add to circles can use Hangouts with you. +https\://www.googleapis.com/auth/plus.login=Know the list of people in your circles, your age range, and language +https\://www.googleapis.com/auth/plus.me=Know who you are on Google +https\://www.googleapis.com/auth/plus.media.upload=Send your photos and videos to Google+ +https\://www.googleapis.com/auth/plus.profiles.read=View your own Google+ profile and profiles visible to you +https\://www.googleapis.com/auth/plus.stream.read=View your Google+ posts, comments, and stream +https\://www.googleapis.com/auth/plus.stream.write=Manage your Google+ posts, comments, and stream +https\://www.googleapis.com/auth/presentations=View and manage your Google Slides presentations +https\://www.googleapis.com/auth/presentations.readonly=View your Google Slides presentations +https\://www.googleapis.com/auth/pubsub=View and manage Pub/Sub topics and subscriptions +https\://www.googleapis.com/auth/replicapool=View and manage replica pools +https\://www.googleapis.com/auth/replicapool.readonly=View replica pools +https\://www.googleapis.com/auth/service.management=Manage your Google API service configuration +https\://www.googleapis.com/auth/service.management.readonly=View your Google API service configuration +https\://www.googleapis.com/auth/servicecontrol=Manage your Google Service Control data +https\://www.googleapis.com/auth/siteverification=Manage the list of sites and domains you control +https\://www.googleapis.com/auth/siteverification.verify_only=Manage your new site verifications with Google +https\://www.googleapis.com/auth/source.full_control=Manage your source code repositories +https\://www.googleapis.com/auth/source.read_only=View the contents of your source code repositories +https\://www.googleapis.com/auth/source.read_write=Manage the contents of your source code repositories +https\://www.googleapis.com/auth/spanner.admin=Administer your Spanner databases +https\://www.googleapis.com/auth/spanner.data=View and manage the contents of your Spanner databases +https\://www.googleapis.com/auth/spreadsheets=View and manage your spreadsheets in Google Drive +https\://www.googleapis.com/auth/spreadsheets.readonly=View your Google Spreadsheets +https\://www.googleapis.com/auth/sqlservice.admin=Manage your Google SQL Service instances +https\://www.googleapis.com/auth/streetviewpublish=Publish and manage your 360 photos on Google Street View +https\://www.googleapis.com/auth/tagmanager.delete.containers=Delete your Google Tag Manager containers +https\://www.googleapis.com/auth/tagmanager.edit.containers=Manage your Google Tag Manager container and its subcomponents, excluding versioning and publishing +https\://www.googleapis.com/auth/tagmanager.edit.containerversions=Manage your Google Tag Manager container versions +https\://www.googleapis.com/auth/tagmanager.manage.accounts=View and manage your Google Tag Manager accounts +https\://www.googleapis.com/auth/tagmanager.manage.users=Manage user permissions of your Google Tag Manager account and container +https\://www.googleapis.com/auth/tagmanager.publish=Publish your Google Tag Manager container versions +https\://www.googleapis.com/auth/tagmanager.readonly=View your Google Tag Manager container and its subcomponents +https\://www.googleapis.com/auth/tasks=Manage your tasks +https\://www.googleapis.com/auth/tasks.readonly=View your tasks +https\://www.googleapis.com/auth/trace.append=Write Trace data for a project or application +https\://www.googleapis.com/auth/urlshortener=Manage your goo.gl short URLs +https\://www.googleapis.com/auth/user.addresses.read=View your street addresses +https\://www.googleapis.com/auth/user.birthday.read=View your complete date of birth +https\://www.googleapis.com/auth/user.emails.read=View your email addresses +https\://www.googleapis.com/auth/user.phonenumbers.read=View your phone numbers +https\://www.googleapis.com/auth/userinfo.email=View your email address +https\://www.googleapis.com/auth/userinfo.profile=View your basic profile info +https\://www.googleapis.com/auth/userlocation.beacon.registry=View and modify your beacons +https\://www.googleapis.com/auth/webmasters=View and manage Search Console data for your verified sites +https\://www.googleapis.com/auth/webmasters.readonly=View Search Console data for your verified sites +https\://www.googleapis.com/auth/xapi.zoo=Test scope for access to the Zoo service +https\://www.googleapis.com/auth/youtube=Manage your YouTube account +https\://www.googleapis.com/auth/youtube.force-ssl=Manage your YouTube account +https\://www.googleapis.com/auth/youtube.readonly=View your YouTube account +https\://www.googleapis.com/auth/youtube.upload=Manage your YouTube videos +https\://www.googleapis.com/auth/youtubepartner=View and manage your assets and associated content on YouTube +https\://www.googleapis.com/auth/youtubepartner-channel-audit=View private information of your YouTube channel relevant during the audit process with a YouTube partner +https\://www.googleapis.com/auth/yt-analytics-monetary.readonly=View monetary and non-monetary YouTube Analytics reports for your YouTube content +https\://www.googleapis.com/auth/yt-analytics.readonly=View YouTube Analytics reports for your YouTube content diff --git a/endpoints-framework/src/main/resources/com/google/api/server/spi/handlers/proxy.html b/endpoints-framework/src/main/resources/com/google/api/server/spi/handlers/proxy.html index 7ea68054..cb9d96f0 100644 --- a/endpoints-framework/src/main/resources/com/google/api/server/spi/handlers/proxy.html +++ b/endpoints-framework/src/main/resources/com/google/api/server/spi/handlers/proxy.html @@ -1,3 +1,8 @@ + + + + + - - - - -
diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/BackendPropertiesTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/BackendPropertiesTest.java index 72dd7802..69b1e925 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/BackendPropertiesTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/BackendPropertiesTest.java @@ -18,8 +18,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import com.google.appengine.api.utils.SystemProperty; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -46,7 +44,7 @@ public void setUp() { this.appEngineProperties = new BackendProperties(true, envReader); this.properties = new BackendProperties(false, envReader); - SystemProperty.applicationId.set(APPLICATION_ID); + System.setProperty(BackendProperties.APP_ID_PROPERTY, APPLICATION_ID); Mockito.when(envReader.getenv(BackendProperties.PROJECT_NUMBER_PROPERTY)) .thenReturn(PROJECT_NUMBER_STR); @@ -97,7 +95,10 @@ public void testGetApplicationId_appEngine() { } @Test - public void testGetApplicationId_tornado() { + public void testGetApplicationId_flex() { + System.clearProperty(BackendProperties.APP_ID_PROPERTY); + Mockito.when(envReader.getenv(BackendProperties.GCLOUD_PROJECT_PROPERTY)) + .thenReturn(APPLICATION_ID); assertNull(properties.getApplicationId()); } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/BackendServiceTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/BackendServiceTest.java deleted file mode 100644 index a72fa3df..00000000 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/BackendServiceTest.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.api.server.spi.BackendService.MessageEntry; -import com.google.api.server.spi.config.ApiConfigException; -import com.google.api.server.spi.config.model.ApiKey; -import com.google.api.server.spi.response.BadRequestException; -import com.google.api.server.spi.response.InternalServerErrorException; -import com.google.api.server.spi.response.ServiceUnavailableException; -import com.google.appengine.api.appidentity.AppIdentityService; -import com.google.appengine.api.appidentity.AppIdentityServiceFactory; -import com.google.appengine.api.urlfetch.HTTPHeader; -import com.google.appengine.api.urlfetch.HTTPMethod; -import com.google.appengine.api.urlfetch.HTTPRequest; -import com.google.appengine.api.urlfetch.HTTPResponse; -import com.google.appengine.api.urlfetch.URLFetchService; -import com.google.appengine.tools.development.testing.LocalAppIdentityServiceTestConfig; -import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig; -import com.google.appengine.tools.development.testing.LocalServiceTestHelper; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import java.net.URL; -import java.util.Collection; -import java.util.List; -import java.util.logging.Level; - -/** - * Tests for {@link BackendService}. - */ -@RunWith(MockitoJUnitRunner.class) -public class BackendServiceTest { - - private static final String API_CONFIG_0 = "apiConfig0"; - private static final String API_CONFIG_1 = "apiConfig1"; - - private final LocalServiceTestHelper helper = new LocalServiceTestHelper( - new LocalAppIdentityServiceTestConfig(), new LocalMemcacheServiceTestConfig()); - @Mock private SystemService systemService; - - private static class RequestMatcher extends ArgumentMatcher { - private final HTTPRequest request; - - public RequestMatcher(HTTPRequest request) { - this.request = request; - } - - public static HTTPRequest eq(HTTPRequest request) { - return argThat(new RequestMatcher(request)); - } - - @Override - public boolean matches(Object arg0) { - if (arg0 instanceof HTTPRequest) { - HTTPRequest otherRequest = (HTTPRequest) arg0; - return request.getURL().toString().equals(otherRequest.getURL().toString()) - && request.getMethod().equals(otherRequest.getMethod()) - && headerEquals(request.getHeaders(), otherRequest.getHeaders()); - } - return false; - } - - private boolean headerEquals(List headers, List headers2) { - for (HTTPHeader header : headers) { - for (HTTPHeader header2 : headers2) { - if (header.getName().equals(header2.getName()) - && !header.getValue().equals(header2.getValue())) { - return false; - } - } - } - return headers.size() == headers2.size(); - } - } - - @Before - public void setUp() throws Exception { - helper.setUp(); - } - - @After - public void tearDown() throws Exception { - helper.tearDown(); - } - - @Test - public void testGetApiConfigs() throws Exception { - ImmutableMap configs = ImmutableMap.of( - new ApiKey("api0", "v1"), API_CONFIG_0, new ApiKey("api1", "v1"), API_CONFIG_1); - - when(systemService.getApiConfigs()).thenReturn(configs); - - BackendService backendService = - new BackendService("1.2.3", systemService, new BackendProperties()); - - Collection apiConfigs = backendService.getApiConfigs("1.2.3"); - - assertEquals(2, apiConfigs.size()); - assertThat(apiConfigs).containsExactly(API_CONFIG_0, API_CONFIG_1); - } - - @Test - public void testErrorIfAppRevisionNotMatching() throws InternalServerErrorException { - BackendService endpoint = new BackendService("1.2.3", systemService, new BackendProperties()); - try { - endpoint.getApiConfigs("1.2.4"); - fail("Should have failed because expected app revision different"); - } catch (BadRequestException e) { - // expected - } - } - - @Test - public void testSystemServiceConfigLoadError() throws Exception { - when(systemService.getApiConfigs()).thenThrow(new ApiConfigException("bleh")); - - BackendService backendService = - new BackendService("1.2.3", systemService, new BackendProperties()); - try { - backendService.getApiConfigs("1.2.3"); - fail(); - } catch (InternalServerErrorException e) { - // Expected. - } - } - - @Test - public void testReloadApiConfigs() throws Exception { - URLFetchService fetcher = Mockito.mock(URLFetchService.class); - HTTPResponse response = Mockito.mock(HTTPResponse.class); - HTTPRequest request = new HTTPRequest(new URL( - "https://1.test/_ah/api/discovery/v1/apis/reload?appMinorVersion=2"), - HTTPMethod.POST); - AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); - request.addHeader(new HTTPHeader("Content-Type", "application/json")); - request.addHeader(new HTTPHeader("Authorization", "OAuth " + appIdentity.getAccessToken( - ImmutableList.of(BackendService.CONFIG_RELOAD_SCOPE)).getAccessToken())); - - when(fetcher.fetch(RequestMatcher.eq(request))).thenReturn(response); - when(response.getResponseCode()).thenReturn(200); - - BackendService.reloadApiConfigs("1.test", "2", fetcher); - verify(fetcher, atLeastOnce()).fetch(Mockito.any(HTTPRequest.class)); - verify(response, atLeastOnce()).getResponseCode(); - } - - @Test - public void testReloadApiConfigsFails() throws Exception { - URLFetchService fetcher = Mockito.mock(URLFetchService.class); - HTTPResponse response = Mockito.mock(HTTPResponse.class); - - when(fetcher.fetch(Mockito.any(HTTPRequest.class))).thenReturn(response); - when(response.getResponseCode()).thenReturn(403); - - try { - BackendService.reloadApiConfigs("1.test", "2", fetcher); - fail("expected exception"); - } catch (ServiceUnavailableException e) { - // expected - } - verify(fetcher, atLeastOnce()).fetch(Mockito.any(HTTPRequest.class)); - verify(response, atLeastOnce()).getResponseCode(); - } - - private int logMessagesCount = 0; - - @Test - public void testLogMessages() { - final MessageEntry[] messages = new MessageEntry[] { - createMessageEntry("info", "INFO message"), - createMessageEntry("warning", "WARNING message"), - createMessageEntry("error", "SEVERE message"), - createMessageEntry("abc", "INFO message") - }; - - BackendService backendService = - new BackendService("1.2.3", systemService, new BackendProperties()) { - - @Override - void log(Level level, String message) { - assertEquals(messages[logMessagesCount].getMessage(), level.toString() + " message"); - logMessagesCount++; - } - }; - backendService.logMessages(messages); - assertEquals(4, logMessagesCount); - } - - @Test - public void testGetHostnameWithMajorVersion() { - assertEquals("guestbook.appspot.com", - BackendService.getHostnameWithMajorVersion("guestbook.appspot.com", null)); - assertEquals("2-dot-guestbook.appspot.com", - BackendService.getHostnameWithMajorVersion("guestbook.appspot.com", "2")); - } - - @Test - public void testGetProperties() { - BackendProperties backendProperties = Mockito.mock(BackendProperties.class); - when(backendProperties.getProjectNumber()).thenReturn(8675309L); - when(backendProperties.getProjectId()).thenReturn("project"); - - BackendService backendService = new BackendService("1.2.3", systemService, backendProperties); - - BackendService.Properties properties = backendService.getProperties(); - assertNotNull(properties); - assertEquals(8675309L, properties.getProjectNumber()); - assertEquals("project", properties.getProjectId()); - } - - private MessageEntry createMessageEntry(String level, String message) { - MessageEntry e = new MessageEntry(); - e.setLevel(level); - e.setMessage(message); - return e; - } -} diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/EndpointsServletTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/EndpointsServletTest.java index 91531e92..86b36fa6 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/EndpointsServletTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/EndpointsServletTest.java @@ -113,6 +113,33 @@ public void echo() throws IOException { assertThat(actual.get("x").asInt()).isEqualTo(1); } + @Test + public void contentLengthHeaderNull() throws IOException { + req.setRequestURI("/_ah/api/test/v2/echo"); + req.setMethod("POST"); + req.setParameter("x", "1"); + + servlet.service(req, resp); + + assertThat(resp.getHeader("Content-Length")).isNull(); + } + + @Test + public void contentLengthHeaderPresent() throws IOException, ServletException { + MockServletConfig config = new MockServletConfig(); + config.addInitParameter("services", TestApi.class.getName()); + config.addInitParameter("addContentLength", "true"); + servlet.init(config); + + req.setRequestURI("/_ah/api/test/v2/echo"); + req.setMethod("POST"); + req.setParameter("x", "1"); + + servlet.service(req, resp); + + assertThat(resp.getHeader("Content-Length")).isNotNull(); + } + @Test public void methodOverride() throws IOException { req.setRequestURI("/_ah/api/test/v2/increment"); @@ -137,8 +164,7 @@ public void proxy() throws IOException { servlet.service(req, resp); assertThat(resp.getStatus()).isEqualTo(HttpServletResponse.SC_OK); - assertThat(resp.getContentAsString()).contains("/_ah/api"); - assertThat(resp.getContentAsString()).contains("https://apis.google.com/js/googleapis.proxy.js"); + assertThat(resp.getContentAsString()).contains("googleapis.server.init()"); } @Test diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/EnvUtilTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/EnvUtilTest.java index 6c0d4914..38c0b6fe 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/EnvUtilTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/EnvUtilTest.java @@ -15,7 +15,6 @@ */ package com.google.api.server.spi; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -46,10 +45,4 @@ public void testIsRunningOnAppEngineProd() { System.clearProperty(EnvUtil.ENV_APPENGINE_RUNTIME); assertFalse(EnvUtil.isRunningOnAppEngineProd()); } - - @Test - public void testGetAppHostName() { - System.clearProperty(EnvUtil.ENV_APPENGINE_RUNTIME); - assertEquals(null, EnvUtil.getAppHostName()); - } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/ObjectMapperUtilTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/ObjectMapperUtilTest.java new file mode 100644 index 00000000..399899c6 --- /dev/null +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/ObjectMapperUtilTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi; + +import static com.google.common.truth.Truth.assertThat; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.api.server.spi.config.model.EndpointsFlag; +import org.junit.Test; + +/** + * Tests for {@link ObjectMapperUtil} + */ +public class ObjectMapperUtilTest { + @Test + public void createStandardObjectMapper_base64Variant() throws Exception { + byte[] bytes = new byte[] {(byte) 0xff, (byte) 0xef}; + ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); + assertThat(mapper.writeValueAsString(bytes)).isEqualTo("\"_-8\""); + assertThat(mapper.readValue("\"_-8\"", byte[].class)).isEqualTo(bytes); + } + + @Test + public void createStandardObjectMapper_useJacksonAnnotations() throws Exception { + ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); + assertThat(mapper.writeValueAsString(new TestObject())).contains("test"); + } + + @Test + public void createStandardObjectMapper_disableJacksonAnnotations() throws Exception { + System.setProperty(EndpointsFlag.JSON_USE_JACKSON_ANNOTATIONS.systemPropertyName, "false"); + try { + ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); + assertThat(mapper.writeValueAsString(new TestObject())).contains("TEST"); + } finally { + System.clearProperty(EndpointsFlag.JSON_USE_JACKSON_ANNOTATIONS.systemPropertyName); + } + } + + private enum TestEnum { + @JsonProperty("test") TEST + } + + private class TestObject { + TestEnum test; + + TestObject() { + this.test = TestEnum.TEST; + } + + public void setTest(TestEnum test) { + this.test = test; + } + + public TestEnum getTest() { + return test; + } + } +} \ No newline at end of file diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceContextTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceContextTest.java index 8ee6ce51..aad89f29 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceContextTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceContextTest.java @@ -31,14 +31,14 @@ public class ServiceContextTest { @Test public void testAppspotHost() { ServiceContext c = ServiceContext.create("abc", "xyz"); - assertEquals("abc.appspot.com", c.getAppHostName()); + assertEquals("abc.appspot.com", c.getAppHostname()); assertEquals("xyz", c.getDefaultApiName()); } @Test public void testGoogleplexHost() { ServiceContext c = ServiceContext.create("google.com:abc", "xyz"); - assertEquals("abc.googleplex.com", c.getAppHostName()); + assertEquals("abc.googleplex.com", c.getAppHostname()); assertEquals("xyz", c.getDefaultApiName()); } @@ -55,7 +55,7 @@ public void testInvalidDomain() { @Test public void testEmptyAppId() { ServiceContext c = ServiceContext.create("", "xyz"); - assertEquals("myapp.appspot.com", c.getAppHostName()); + assertEquals("myapp.appspot.com", c.getAppHostname()); assertEquals("xyz", c.getDefaultApiName()); } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceExceptionTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceExceptionTest.java new file mode 100644 index 00000000..ccc19143 --- /dev/null +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/ServiceExceptionTest.java @@ -0,0 +1,20 @@ +package com.google.api.server.spi; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.api.server.spi.response.UnauthorizedException; +import java.util.logging.Level; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class ServiceExceptionTest { + @Test + public void testWithLogLevel() { + UnauthorizedException ex = new UnauthorizedException(""); + assertThat(ex.getLogLevel()).isEqualTo(Level.INFO); + assertThat(ServiceException.withLogLevel(ex, Level.WARNING).getLogLevel()) + .isEqualTo(Level.WARNING); + } +} \ No newline at end of file diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/ServletInitializationParametersTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/ServletInitializationParametersTest.java index 1bb3b592..b4cbb19a 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/ServletInitializationParametersTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/ServletInitializationParametersTest.java @@ -16,9 +16,6 @@ package com.google.api.server.spi; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableSet; @@ -46,11 +43,13 @@ public void testBuilder_defaults() { ServletInitializationParameters initParameters = ServletInitializationParameters.builder() .build(); assertThat(initParameters.getServiceClasses()).isEmpty(); - assertTrue(initParameters.isServletRestricted()); - assertTrue(initParameters.isClientIdWhitelistEnabled()); - assertFalse(initParameters.isIllegalArgumentBackendError()); - assertTrue(initParameters.isExceptionCompatibilityEnabled()); - verifyAsMap(initParameters, "", "true", "true", "false", "true"); + assertThat(initParameters.isServletRestricted()).isTrue(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isTrue(); + assertThat(initParameters.isIllegalArgumentBackendError()).isFalse(); + assertThat(initParameters.isExceptionCompatibilityEnabled()).isTrue(); + assertThat(initParameters.isPrettyPrintEnabled()).isTrue(); + assertThat(initParameters.isAddContentLength()).isFalse(); + verifyAsMap(initParameters, "", "true", "true", "false", "true", "true", "false"); } @Test @@ -59,15 +58,17 @@ public void testBuilder_emptySetsAndTrue() { .setClientIdWhitelistEnabled(true) .setRestricted(true) .addServiceClasses(ImmutableSet.>of()) - .setIllegalArgumentIsBackendError(true) + .setIllegalArgumentBackendError(true) .setExceptionCompatibilityEnabled(true) + .setPrettyPrintEnabled(true) + .setAddContentLength(true) .build(); assertThat(initParameters.getServiceClasses()).isEmpty(); - assertTrue(initParameters.isServletRestricted()); - assertTrue(initParameters.isClientIdWhitelistEnabled()); - assertTrue(initParameters.isIllegalArgumentBackendError()); - assertTrue(initParameters.isExceptionCompatibilityEnabled()); - verifyAsMap(initParameters, "", "true", "true", "true", "true"); + assertThat(initParameters.isServletRestricted()).isTrue(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isTrue(); + assertThat(initParameters.isIllegalArgumentBackendError()).isTrue(); + assertThat(initParameters.isExceptionCompatibilityEnabled()).isTrue(); + verifyAsMap(initParameters, "", "true", "true", "true", "true", "true", "true"); } @Test @@ -76,13 +77,16 @@ public void testBuilder_oneEntrySetsAndFalse() { .setRestricted(false) .addServiceClass(String.class) .setClientIdWhitelistEnabled(false) - .setIllegalArgumentIsBackendError(false) + .setIllegalArgumentBackendError(false) .setExceptionCompatibilityEnabled(false) + .setPrettyPrintEnabled(false) + .setAddContentLength(false) .build(); assertThat(initParameters.getServiceClasses()).containsExactly(String.class); - assertFalse(initParameters.isServletRestricted()); - assertFalse(initParameters.isClientIdWhitelistEnabled()); - verifyAsMap(initParameters, String.class.getName(), "false", "false", "false", "false"); + assertThat(initParameters.isServletRestricted()).isFalse(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isFalse(); + verifyAsMap( + initParameters, String.class.getName(), "false", "false", "false", "false", "false","false"); } @Test @@ -92,7 +96,7 @@ public void testBuilder_twoEntrySets() { .build(); assertThat(initParameters.getServiceClasses()).containsExactly(String.class, Integer.class); verifyAsMap(initParameters, String.class.getName() + ',' + Integer.class.getName(), "true", - "true", "false", "true"); + "true", "false", "true", "true", "false"); } @Test @@ -100,58 +104,65 @@ public void testFromServletConfig_nullConfig() throws ServletException { ServletInitializationParameters initParameters = ServletInitializationParameters.fromServletConfig(null, getClass().getClassLoader()); assertThat(initParameters.getServiceClasses()).isEmpty(); - assertTrue(initParameters.isServletRestricted()); - assertTrue(initParameters.isClientIdWhitelistEnabled()); + assertThat(initParameters.isServletRestricted()).isTrue(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isTrue(); } @Test public void testFromServletConfig_nullValues() throws ServletException { ServletInitializationParameters initParameters = - fromServletConfig(null, null, null, null); + fromServletConfig(null, null, null, null, null, null, null); assertThat(initParameters.getServiceClasses()).isEmpty(); - assertTrue(initParameters.isServletRestricted()); - assertTrue(initParameters.isClientIdWhitelistEnabled()); - assertFalse(initParameters.isIllegalArgumentBackendError()); + assertThat(initParameters.isServletRestricted()).isTrue(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isTrue(); + assertThat(initParameters.isIllegalArgumentBackendError()).isFalse(); + assertThat(initParameters.isExceptionCompatibilityEnabled()).isTrue(); + assertThat(initParameters.isPrettyPrintEnabled()).isTrue(); } @Test public void testFromServletConfig_emptySetsAndFalse() throws ServletException { ServletInitializationParameters initParameters = - fromServletConfig("", "false", "false", "false"); + fromServletConfig("", "false", "false", "false", "false", "false", "false"); assertThat(initParameters.getServiceClasses()).isEmpty(); - assertFalse(initParameters.isServletRestricted()); - assertFalse(initParameters.isClientIdWhitelistEnabled()); - assertFalse(initParameters.isIllegalArgumentBackendError()); + assertThat(initParameters.isServletRestricted()).isFalse(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isFalse(); + assertThat(initParameters.isIllegalArgumentBackendError()).isFalse(); + assertThat(initParameters.isExceptionCompatibilityEnabled()).isFalse(); + assertThat(initParameters.isPrettyPrintEnabled()).isFalse(); } @Test public void testFromServletConfig_oneEntrySetsAndTrue() throws ServletException { ServletInitializationParameters initParameters = - fromServletConfig(String.class.getName(), "true", "true", "true"); + fromServletConfig(String.class.getName(), "true", "true", "true", "true", "true", "true"); assertThat(initParameters.getServiceClasses()).containsExactly(String.class); - assertTrue(initParameters.isServletRestricted()); - assertTrue(initParameters.isClientIdWhitelistEnabled()); - assertTrue(initParameters.isIllegalArgumentBackendError()); + assertThat(initParameters.isServletRestricted()).isTrue(); + assertThat(initParameters.isClientIdWhitelistEnabled()).isTrue(); + assertThat(initParameters.isIllegalArgumentBackendError()).isTrue(); + assertThat(initParameters.isExceptionCompatibilityEnabled()).isTrue(); + assertThat(initParameters.isPrettyPrintEnabled()).isTrue(); } @Test public void testFromServletConfig_twoEntrySets() throws ServletException { ServletInitializationParameters initParameters = fromServletConfig( - String.class.getName() + ',' + Integer.class.getName(), null, null, null); + String.class.getName() + ',' + Integer.class.getName(), null, null, null, null, null, null); assertThat(initParameters.getServiceClasses()).containsExactly(String.class, Integer.class); } @Test public void testFromServletConfig_skipsEmptyElements() throws ServletException { ServletInitializationParameters initParameters = fromServletConfig( - ",," + String.class.getName() + ",,," + Integer.class.getName() + ",", null, null, null); + ",," + String.class.getName() + ",,," + Integer.class.getName() + ",", null, null, null, + null, null, null); assertThat(initParameters.getServiceClasses()).containsExactly(String.class, Integer.class); } @Test public void testFromServletConfig_invalidRestrictedThrows() throws ServletException { try { - fromServletConfig(null, "yes", null, null); + fromServletConfig(null, "yes", null, null, null, null, null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected @@ -161,22 +172,28 @@ public void testFromServletConfig_invalidRestrictedThrows() throws ServletExcept private void verifyAsMap( ServletInitializationParameters initParameters, String serviceClasses, String isServletRestricted, String isClientIdWhitelistEnabled, - String isIllegalArgumentBackendError, String isExceptionCompatibilityEnabled) { + String isIllegalArgumentBackendError, String isExceptionCompatibilityEnabled, + String isPrettyPrintEnabled, String isAddContentLength) { Map map = initParameters.asMap(); - assertEquals(5, map.size()); - assertEquals(serviceClasses, map.get("services")); - assertEquals(isServletRestricted, map.get("restricted")); - assertEquals(isClientIdWhitelistEnabled, map.get("clientIdWhitelistEnabled")); - assertEquals(isIllegalArgumentBackendError, map.get("illegalArgumentIsBackendError")); - assertEquals(isExceptionCompatibilityEnabled, map.get("enableExceptionCompatibility")); + assertThat(map).hasSize(7); + assertThat(map.get("services")).isEqualTo(serviceClasses); + assertThat(map.get("restricted")).isEqualTo(isServletRestricted); + assertThat(map.get("clientIdWhitelistEnabled")).isEqualTo(isClientIdWhitelistEnabled); + assertThat(map.get("illegalArgumentIsBackendError")).isEqualTo(isIllegalArgumentBackendError); + assertThat(map.get("enableExceptionCompatibility")).isEqualTo(isExceptionCompatibilityEnabled); + assertThat(map.get("prettyPrint")).isEqualTo(isPrettyPrintEnabled); + assertThat(map.get("addContentLength")).isEqualTo(isAddContentLength); } private ServletInitializationParameters fromServletConfig( String serviceClasses, String isServletRestricted, - String isClientIdWhitelistEnabled, String isIllegalArgumentBackendError) + String isClientIdWhitelistEnabled, String isIllegalArgumentBackendError, + String isExceptionCompatibilityEnabled, String isPrettyPrintEnabled, + String isAddContentLength) throws ServletException { ServletConfig servletConfig = new StubServletConfig(serviceClasses, - isServletRestricted, isClientIdWhitelistEnabled, isIllegalArgumentBackendError); + isServletRestricted, isClientIdWhitelistEnabled, isIllegalArgumentBackendError, + isExceptionCompatibilityEnabled, isPrettyPrintEnabled, isAddContentLength); return ServletInitializationParameters.fromServletConfig( servletConfig, getClass().getClassLoader()); } @@ -186,12 +203,16 @@ private static class StubServletConfig implements ServletConfig { public StubServletConfig( String serviceClasses, String isServletRestricted, String isClientIdWhitelistEnabled, - String isIllegalArgumentBackendError) { + String isIllegalArgumentBackendError, String isExceptionCompatibilityEnabled, + String isPrettyPrintEnabled, String isAddContentLength) { initParameters = Maps.newHashMap(); initParameters.put("services", serviceClasses); initParameters.put("restricted", isServletRestricted); initParameters.put("clientIdWhitelistEnabled", isClientIdWhitelistEnabled); initParameters.put("illegalArgumentIsBackendError", isIllegalArgumentBackendError); + initParameters.put("enableExceptionCompatibility", isExceptionCompatibilityEnabled); + initParameters.put("prettyPrint", isPrettyPrintEnabled); + initParameters.put("addContentLength", isAddContentLength); } @Override diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/SystemServiceServletTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/SystemServiceServletTest.java deleted file mode 100644 index e61fc727..00000000 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/SystemServiceServletTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import com.google.api.server.spi.config.model.ApiMethodConfig; -import com.google.api.server.spi.request.Attribute; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -import java.io.IOException; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Tests for {@link SystemServiceServlet}. - */ -@RunWith(MockitoJUnitRunner.class) -public class SystemServiceServletTest { - @Mock protected ServletConfig servletConfig; - @Mock protected ServletContext servletContext; - @Mock protected ApiMethodConfig methodConfig; - - private SystemServiceServlet servlet; - private MockHttpServletRequest request; - private Attribute attr; - - protected final ObjectMapper mapper = new ObjectMapper(); - - private class ExceptionSystemServiceServlet extends SystemServiceServlet { - private final ServiceException exception; - - public ExceptionSystemServiceServlet(ServiceException exception) { - this.exception = exception; - } - - @Override - protected void execute(HttpServletRequest request, HttpServletResponse response, - String serviceName, String methodName) throws ServiceException { - throw exception; - } - } - - @Before - public void setUp() throws Exception { - servlet = new SystemServiceServlet(); - request = new MockHttpServletRequest(); - attr = Attribute.from(request); - } - - @Test - public void testExceptionHandling() throws Exception { - int status = 123; - ServiceException exception = new ServiceException(status, "error"); - request.setPathInfo("/Service.method"); - - SystemServiceServlet servlet = new ExceptionSystemServiceServlet(exception); - MockHttpServletResponse fakeResponse = new MockHttpServletResponse(); - try { - servlet.doPost(request, fakeResponse); - } catch (IOException e) { - fail("should have turned all exceptions into a JSON error response"); - } - assertEquals(SystemService.MIME_JSON, fakeResponse.getContentType()); - assertEquals(status, fakeResponse.getStatus()); - JsonNode node = mapper.readTree(fakeResponse.getContentAsString()); - assertNotNull(node); - JsonNode errorNode = node.get("error_message"); - assertNotNull(errorNode); - assertEquals("error", errorNode.asText()); - } -} diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/EndpointsAuthenticatorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/EndpointsAuthenticatorTest.java index 1fc9b6a7..f9ce9db5 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/EndpointsAuthenticatorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/EndpointsAuthenticatorTest.java @@ -21,6 +21,7 @@ import com.google.api.server.spi.EnvUtil; import com.google.api.server.spi.auth.common.User; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import org.junit.Before; import org.junit.Test; @@ -53,13 +54,13 @@ public void setUp() throws Exception { } @Test - public void testAuthenticate_jwt() { + public void testAuthenticate_jwt() throws ServiceUnavailableException { when(jwtAuthenticator.authenticate(request)).thenReturn(USER); assertEquals(USER, authenticator.authenticate(request)); } @Test - public void testAuthenticate_appEngine() { + public void testAuthenticate_appEngine() throws ServiceUnavailableException { when(jwtAuthenticator.authenticate(request)).thenReturn(null); when(appEngineAuthenticator.authenticate(request)).thenReturn(USER); @@ -70,7 +71,7 @@ public void testAuthenticate_appEngine() { } @Test - public void testAuthenticate_oauth2NonAppEngine() { + public void testAuthenticate_oauth2NonAppEngine() throws ServiceUnavailableException { when(jwtAuthenticator.authenticate(request)).thenReturn(null); when(oauth2Authenticator.authenticate(request)).thenReturn(USER); @@ -81,7 +82,7 @@ public void testAuthenticate_oauth2NonAppEngine() { } @Test - public void testAuthenticate_oAuth2NotRequireAppEngineUser() { + public void testAuthenticate_oAuth2NotRequireAppEngineUser() throws ServiceUnavailableException { when(jwtAuthenticator.authenticate(request)).thenReturn(null); when(oauth2Authenticator.authenticate(request)).thenReturn(USER); diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticatorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticatorTest.java index 679c3670..3265bb83 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticatorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAppEngineAuthenticatorTest.java @@ -24,6 +24,7 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.scope.AuthScopeExpressions; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.appengine.api.oauth.OAuthRequestException; import com.google.appengine.api.oauth.OAuthService; import com.google.appengine.api.users.UserService; @@ -87,7 +88,7 @@ private void initializeRequest(String bearerString) { } @Test - public void testGetOAuth2UserNonOAuth2() { + public void testGetOAuth2UserNonOAuth2() throws ServiceUnavailableException { initializeRequest("Bearer badToken"); assertNull(authenticator.getOAuth2User(request, config)); @@ -152,7 +153,7 @@ public void testGetOAuth2UserSkipClientIdCheck() throws Exception { } @Test - public void testGetOAuth2UserAppEngineDevClientIdNotAllowed() { + public void testGetOAuth2UserAppEngineDevClientIdNotAllowed() throws ServiceUnavailableException { System.setProperty(EnvUtil.ENV_APPENGINE_RUNTIME, "Developement"); when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret(SCOPES)); when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2")); @@ -160,19 +161,19 @@ public void testGetOAuth2UserAppEngineDevClientIdNotAllowed() { } @Test - public void testAuthenticateNonAppEngine() { + public void testAuthenticateNonAppEngine() throws ServiceUnavailableException { System.clearProperty(EnvUtil.ENV_APPENGINE_RUNTIME); assertNull(authenticator.authenticate(request)); } @Test - public void testAuthenticateSkipTokenAuth() { + public void testAuthenticateSkipTokenAuth() throws ServiceUnavailableException { attr.set(Attribute.SKIP_TOKEN_AUTH, true); assertNull(authenticator.authenticate(request)); } @Test - public void testAuthenticateOAuth2Fail() { + public void testAuthenticateOAuth2Fail() throws ServiceUnavailableException { authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) { @Override com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, @@ -189,7 +190,7 @@ boolean shouldTryCookieAuth(ApiMethodConfig config) { } @Test - public void testAuthenticateOAuth2() { + public void testAuthenticateOAuth2() throws ServiceUnavailableException { authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) { @Override com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, @@ -202,7 +203,7 @@ com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, } @Test - public void testAuthenticateSkipTokenAuthCookieAuthFail() { + public void testAuthenticateSkipTokenAuthCookieAuthFail() throws ServiceUnavailableException { attr.set(Attribute.SKIP_TOKEN_AUTH, true); authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) { @Override @@ -215,7 +216,7 @@ boolean shouldTryCookieAuth(ApiMethodConfig config) { } @Test - public void testAuthenticateSkipTokenAuthCookieAuth() { + public void testAuthenticateSkipTokenAuthCookieAuth() throws ServiceUnavailableException { attr.set(Attribute.SKIP_TOKEN_AUTH, true); authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) { @Override @@ -229,7 +230,7 @@ boolean shouldTryCookieAuth(ApiMethodConfig config) { } @Test - public void testAuthenticateOAuth2CookieAuthBothFail() { + public void testAuthenticateOAuth2CookieAuthBothFail() throws ServiceUnavailableException { authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) { @Override com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, @@ -247,7 +248,7 @@ boolean shouldTryCookieAuth(ApiMethodConfig config) { } @Test - public void testAuthenticateOAuth2FailCookieAuth() { + public void testAuthenticateOAuth2FailCookieAuth() throws ServiceUnavailableException { authenticator = new GoogleAppEngineAuthenticator(oauthService, userService) { @Override com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAuthTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAuthTest.java index 61f05896..3b27c775 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAuthTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleAuthTest.java @@ -31,6 +31,7 @@ import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.server.spi.auth.GoogleAuth.TokenInfo; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.common.collect.ImmutableList; import org.junit.Test; @@ -166,7 +167,23 @@ public void testParseTokenInfo_withoutEmail() throws Exception { assertNull(GoogleAuth.parseTokenInfo(request)); } + @Test + public void testParseTokenInfo_with400() throws Exception { + HttpRequest request = constructHttpRequest("{\"error_description\": \"Invalid Value\"}", 400); + assertNull(GoogleAuth.parseTokenInfo(request)); + } + + @Test(expected = ServiceUnavailableException.class) + public void testParseTokenInfo_with500() throws Exception { + HttpRequest request = constructHttpRequest("{\"error_description\": \"Backend Error\"}", 500); + GoogleAuth.parseTokenInfo(request); + } + private HttpRequest constructHttpRequest(final String content) throws IOException { + return constructHttpRequest(content, 200); + } + + private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException { HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { @@ -176,12 +193,14 @@ public LowLevelHttpResponse execute() throws IOException { MockLowLevelHttpResponse result = new MockLowLevelHttpResponse(); result.setContentType("application/json"); result.setContent(content); + result.setStatusCode(statusCode); return result; } }; } }; - return transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")) - .setParser(new JsonObjectParser(new JacksonFactory())); + HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory())); + GoogleAuth.configureErrorHandling(httpRequest); + return httpRequest; } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleJwtAuthenticatorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleJwtAuthenticatorTest.java index a59310b4..e67140d7 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleJwtAuthenticatorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleJwtAuthenticatorTest.java @@ -16,6 +16,7 @@ package com.google.api.server.spi.auth; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; @@ -90,18 +91,21 @@ public void testVerifyToken() throws Exception { public void testAuthenticate_skipTokenAuth() { attr.set(Attribute.SKIP_TOKEN_AUTH, true); assertNull(authenticator.authenticate(request)); + assertNull(attr.get(Attribute.ID_TOKEN)); } @Test public void testAuthenticate_notJwt() { request.addHeader(GoogleAuth.AUTHORIZATION_HEADER, "Bearer abc.abc"); assertNull(authenticator.authenticate(request)); + assertNull(attr.get(Attribute.ID_TOKEN)); } @Test public void testAuthenticate_invalidToken() throws Exception { when(verifier.verify(TOKEN)).thenReturn(null); assertNull(authenticator.authenticate(request)); + assertNull(attr.get(Attribute.ID_TOKEN)); } @Test @@ -109,6 +113,7 @@ public void testAuthenticate_clientIdNotAllowed() throws Exception { when(verifier.verify(TOKEN)).thenReturn(token); when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2")); assertNull(authenticator.authenticate(request)); + assertNotNull(attr.get(Attribute.ID_TOKEN)); } @Test @@ -117,6 +122,7 @@ public void testAuthenticate_audienceNotAllowed() throws Exception { when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID)); when(config.getAudiences()).thenReturn(ImmutableList.of("audience2")); assertNull(authenticator.authenticate(request)); + assertNotNull(attr.get(Attribute.ID_TOKEN)); } @Test @@ -128,6 +134,7 @@ public void testAuthenticate_skipClientIdCheck() throws Exception { User user = authenticator.authenticate(request); assertEquals(EMAIL, user.getEmail()); assertEquals(USER_ID, user.getId()); + assertNotNull(attr.get(Attribute.ID_TOKEN)); } @Test @@ -138,6 +145,10 @@ public void testAuthenticate() throws Exception { User user = authenticator.authenticate(request); assertEquals(EMAIL, user.getEmail()); assertEquals(USER_ID, user.getId()); + GoogleIdToken idToken = attr.get(Attribute.ID_TOKEN); + assertNotNull(idToken); + assertEquals(EMAIL, idToken.getPayload().getEmail()); + assertEquals(USER_ID, idToken.getPayload().getSubject()); } @Test @@ -150,7 +161,7 @@ public void testAuthenticate_appEngineUser() throws GeneralSecurityException, IO assertEquals(EMAIL, user.getEmail()); assertEquals(USER_ID, user.getId()); com.google.appengine.api.users.User appEngineuser = - (com.google.appengine.api.users.User) attr.get(Attribute.AUTHENTICATED_APPENGINE_USER); + attr.get(Attribute.AUTHENTICATED_APPENGINE_USER); assertEquals(EMAIL, appEngineuser.getEmail()); assertNull(appEngineuser.getUserId()); } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleOAuth2AuthenticatorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleOAuth2AuthenticatorTest.java index b86a0f9c..b05839fa 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleOAuth2AuthenticatorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/auth/GoogleOAuth2AuthenticatorTest.java @@ -16,6 +16,7 @@ package com.google.api.server.spi.auth; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; @@ -24,6 +25,7 @@ import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.api.server.spi.config.scope.AuthScopeExpressions; import com.google.api.server.spi.request.Attribute; +import com.google.api.server.spi.response.ServiceUnavailableException; import com.google.common.collect.ImmutableList; import org.junit.Before; @@ -65,57 +67,67 @@ private void initializeRequest(String bearerString) { } @Test - public void testAuthenticate_skipTokenAuth() { + public void testAuthenticate_skipTokenAuth() throws ServiceUnavailableException { attr.set(Attribute.SKIP_TOKEN_AUTH, true); assertNull(authenticator.authenticate(request)); + assertNull(attr.get(Attribute.TOKEN_INFO)); } @Test - public void testAuthenticate_notOAuth2() { + public void testAuthenticate_notOAuth2() throws ServiceUnavailableException { initializeRequest("Bearer badToken"); assertNull(authenticator.authenticate(request)); + assertNull(attr.get(Attribute.TOKEN_INFO)); } @Test - public void testAuthenticate_nullTokenInfo() { + public void testAuthenticate_nullTokenInfo() throws ServiceUnavailableException { authenticator = createAuthenticator(null, null, null, null); assertNull(authenticator.authenticate(request)); + assertNull(attr.get(Attribute.TOKEN_INFO)); } @Test - public void testAuthenticate_scopeNotAllowed() { + public void testAuthenticate_scopeNotAllowed() throws ServiceUnavailableException { when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope3")); assertNull(authenticator.authenticate(request)); + assertNotNull(attr.get(Attribute.TOKEN_INFO)); } @Test - public void testAuthenticate_clientIdNotAllowed() { + public void testAuthenticate_clientIdNotAllowed() throws ServiceUnavailableException { when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1")); when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2")); assertNull(authenticator.authenticate(request)); + assertNotNull(attr.get(Attribute.TOKEN_INFO)); } @Test - public void testAuthenticate_skipClientIdCheck() { + public void testAuthenticate_skipClientIdCheck() throws ServiceUnavailableException { request.removeAttribute(Attribute.ENABLE_CLIENT_ID_WHITELIST); when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1")); when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2")); User user = authenticator.authenticate(request); assertEquals(EMAIL, user.getEmail()); assertEquals(USER_ID, user.getId()); + assertNotNull(attr.get(Attribute.TOKEN_INFO)); } @Test - public void testAuthenticate() { + public void testAuthenticate() throws ServiceUnavailableException { when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1")); when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID)); User user = authenticator.authenticate(request); assertEquals(EMAIL, user.getEmail()); assertEquals(USER_ID, user.getId()); + final TokenInfo tokenInfo = attr.get(Attribute.TOKEN_INFO); + assertNotNull(tokenInfo); + assertEquals(EMAIL, tokenInfo.email); + assertEquals(USER_ID, tokenInfo.userId); } @Test - public void testAuthenticate_appEngineUser() { + public void testAuthenticate_appEngineUser() throws ServiceUnavailableException { attr.set(Attribute.REQUIRE_APPENGINE_USER, true); when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret("scope1")); when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID)); diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfigTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfigTest.java index 8ae0c835..07bc8f23 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfigTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiAnnotationConfigTest.java @@ -59,7 +59,7 @@ public class ApiAnnotationConfigTest { public void setUp() throws Exception { serviceContext = Mockito.mock(ServiceContext.class); Mockito.when(serviceContext.getDefaultApiName()).thenReturn("api"); - Mockito.when(serviceContext.getAppHostName()).thenReturn("appHostName.com"); + Mockito.when(serviceContext.getAppHostname()).thenReturn("appHostName.com"); Mockito.when(serviceContext.getTransferProtocol()).thenReturn("https"); config = new ApiConfig.Factory().create(serviceContext, new TypeLoader(), TestEndpoint.class); @@ -74,7 +74,7 @@ public void testDefaults() { assertEquals(null, config.getDescription()); assertEquals("https://appHostName.com/_ah/spi", config.getBackendRoot()); assertEquals(false, config.getIsAbstract()); - assertEquals(false, config.getIsDefaultVersion()); + assertEquals(true, config.getIsDefaultVersion()); assertEquals(true, config.getIsDiscoverable()); assertEquals(false, config.getUseDatastore()); } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReaderTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReaderTest.java index c09598b6..a11087d9 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReaderTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/annotationreader/ApiConfigAnnotationReaderTest.java @@ -121,7 +121,7 @@ public void setUp() throws Exception { serviceContext = Mockito.mock(ServiceContext.class); Mockito.when(serviceContext.getDefaultApiName()).thenReturn("api"); - Mockito.when(serviceContext.getAppHostName()).thenReturn("appHostName.com"); + Mockito.when(serviceContext.getAppHostname()).thenReturn("appHostName.com"); annotationReader = new ApiConfigAnnotationReader(); } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/datastore/ApiConfigDatastoreReaderTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/datastore/ApiConfigDatastoreReaderTest.java deleted file mode 100644 index 36e4530c..00000000 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/datastore/ApiConfigDatastoreReaderTest.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.config.datastore; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.api.server.spi.ServiceContext; -import com.google.api.server.spi.TypeLoader; -import com.google.api.server.spi.config.ApiConfigException; -import com.google.api.server.spi.config.datastore.testing.FakeAsyncMemcacheService; -import com.google.api.server.spi.config.model.ApiConfig; -import com.google.api.server.spi.config.scope.AuthScopeExpression; -import com.google.api.server.spi.config.scope.AuthScopeExpressions; -import com.google.api.server.spi.testing.TestEndpoint; -import com.google.appengine.api.datastore.DatastoreService; -import com.google.appengine.api.datastore.DatastoreServiceFactory; -import com.google.appengine.api.datastore.Entity; -import com.google.appengine.api.memcache.MemcacheService; -import com.google.appengine.api.memcache.MemcacheServiceFactory; -import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; -import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig; -import com.google.appengine.tools.development.testing.LocalModulesServiceTestConfig; -import com.google.appengine.tools.development.testing.LocalServiceTestHelper; -import com.google.common.collect.ImmutableList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.util.List; - -/** - * Tests for {@link ApiConfigDatastoreReader} using actual (local) appengine datastore and memcache - * services. - * - * @author Eric Orth - */ -@RunWith(JUnit4.class) -public class ApiConfigDatastoreReaderTest { - private ApiConfigDatastoreReader datastoreReader; - - private LocalServiceTestHelper serviceTestHelper; - private DatastoreService datastoreService; - private MemcacheService memcacheService; - - private ServiceContext serviceContext; - private ApiConfig config; - private ApiConfig expectedConfig; - - private static final String ENTITY_NAME = TestEndpoint.class.getName(); - private static final String MEMCACHE_KEY = ApiConfigDatastoreReader.ENDPOINT_CONFIGURATION_KIND + - "." + ENTITY_NAME; - - private static final List SCOPES = ImmutableList.of("scope0", "scope1", "scope2"); - private static final AuthScopeExpression SIMPLE_SCOPE_EXPRESSION = - AuthScopeExpressions.interpret(SCOPES.get(0)); - private static final AuthScopeExpression COMPLEX_SCOPE_EXPRESSION = - AuthScopeExpressions.interpret(SCOPES); - private static final List AUDIENCES = - ImmutableList.of("audience0", "audience1", "audience2"); - private static final List CLIENT_IDS = - ImmutableList.of("clientId0", "clientId1", "clientId2"); - private static final List BAD_SCOPES = ImmutableList.of("scope0", 4, "scope2"); - - @Before - public void setUp() throws Exception { - serviceTestHelper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig(), - new LocalMemcacheServiceTestConfig(), new LocalModulesServiceTestConfig()); - serviceTestHelper.setUp(); - datastoreService = DatastoreServiceFactory.getDatastoreService(); - memcacheService = MemcacheServiceFactory.getMemcacheService(); - - serviceContext = ServiceContext.create(); - ApiConfig.Factory configFactory = new ApiConfig.Factory(); - config = configFactory.create(serviceContext, new TypeLoader(), TestEndpoint.class); - config.setUseDatastore(true); - expectedConfig = configFactory.copy(config); - assertEquals(expectedConfig, config); - - datastoreReader = new ApiConfigDatastoreReader( - datastoreService, new FakeAsyncMemcacheService(memcacheService)); - } - - @After - public void tearDown() throws Exception { - serviceTestHelper.tearDown(); - } - - private Entity createEntity() { - return new Entity(ApiConfigDatastoreReader.ENDPOINT_CONFIGURATION_KIND, ENTITY_NAME); - } - - @Test - public void testAssertStaticConfig() throws Exception { - config.getApiClassConfig().setUseDatastore(false); - assertTrue(datastoreReader.isStaticConfig(config)); - config.getApiClassConfig().setUseDatastore(true); - assertFalse(datastoreReader.isStaticConfig(config)); - } - - @Test - public void testLoadNoDatastore() throws Exception { - Entity entity = createEntity(); - entity.setUnindexedProperty("scopes", SCOPES); - entity.setUnindexedProperty("audiences", AUDIENCES); - entity.setUnindexedProperty("clientIds", CLIENT_IDS); - datastoreService.put(entity); - - config.setUseDatastore(false); - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - - expectedConfig.setUseDatastore(false); - assertEquals(expectedConfig, config); - - assertFalse(memcacheService.contains(MEMCACHE_KEY)); - } - - @Test - public void testLoadSource() throws Exception { - Entity entity = createEntity(); - entity.setUnindexedProperty("scopes", SCOPES); - entity.setUnindexedProperty("audiences", AUDIENCES); - entity.setUnindexedProperty("clientIds", CLIENT_IDS); - datastoreService.put(entity); - - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - - expectedConfig.getApiClassConfig().setScopeExpression(COMPLEX_SCOPE_EXPRESSION); - expectedConfig.getApiClassConfig().setAudiences(AUDIENCES); - expectedConfig.getApiClassConfig().setClientIds(CLIENT_IDS); - assertEquals(expectedConfig, config); - - Object memcacheValue = memcacheService.get(MEMCACHE_KEY); - assertEquals(entity, memcacheValue); - } - - @Test - public void testLoadSource_singleStrings() throws Exception { - Entity entity = createEntity(); - entity.setUnindexedProperty("scopes", SCOPES.get(0)); - entity.setUnindexedProperty("audiences", AUDIENCES.get(0)); - entity.setUnindexedProperty("clientIds", CLIENT_IDS.get(0)); - datastoreService.put(entity); - - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - - expectedConfig.getApiClassConfig().setScopeExpression(SIMPLE_SCOPE_EXPRESSION); - expectedConfig.getApiClassConfig().setAudiences(ImmutableList.of(AUDIENCES.get(0))); - expectedConfig.getApiClassConfig().setClientIds(ImmutableList.of(CLIENT_IDS.get(0))); - assertEquals(expectedConfig, config); - - Object memcacheValue = memcacheService.get(MEMCACHE_KEY); - assertEquals(entity, memcacheValue); - } - - @Test - public void testLoadSource_noValues() throws Exception { - Entity entity = createEntity(); - datastoreService.put(entity); - - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - assertEquals(expectedConfig, config); - - Object memcacheValue = memcacheService.get(MEMCACHE_KEY); - assertEquals(entity, memcacheValue); - } - - @Test - public void testLoadSource_notPresent() throws Exception { - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - assertEquals(expectedConfig, config); - - assertFalse(memcacheService.contains(MEMCACHE_KEY)); - } - - @Test - public void testLoadSource_badProperty() throws Exception { - Entity entity = createEntity(); - entity.setUnindexedProperty("scopes", true); - datastoreService.put(entity); - - try { - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - fail("Expected exception not thrown."); - } catch (ApiConfigException expected) { - } - - assertEquals(expectedConfig, config); - - Object memcacheValue = memcacheService.get(MEMCACHE_KEY); - assertEquals(entity, memcacheValue); - } - - @Test - public void testLoadSource_badArray() throws Exception { - Entity entity = createEntity(); - entity.setUnindexedProperty("scopes", BAD_SCOPES); - datastoreService.put(entity); - - try { - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - fail("Expected exception not thrown."); - } catch (ApiConfigException expected) { - } - - assertEquals(expectedConfig, config); - - Object memcacheValue = memcacheService.get(MEMCACHE_KEY); - assertEquals(entity, memcacheValue); - } - - @Test - public void testLoadFromMemcache() throws Exception { - Entity entity = createEntity(); - entity.setUnindexedProperty("scopes", SCOPES.get(0)); - entity.setUnindexedProperty("audiences", AUDIENCES.get(0)); - entity.setUnindexedProperty("clientIds", CLIENT_IDS.get(0)); - memcacheService.put(MEMCACHE_KEY, entity); - - // Put bad data in datastore to make sure we're not reading out of there. - Entity badEntity = createEntity(); - badEntity.setUnindexedProperty("scopes", BAD_SCOPES); - datastoreService.put(badEntity); - - datastoreReader.loadEndpointClass(serviceContext, TestEndpoint.class, config); - - expectedConfig.getApiClassConfig().setScopeExpression(SIMPLE_SCOPE_EXPRESSION); - expectedConfig.getApiClassConfig().setAudiences(ImmutableList.of(AUDIENCES.get(0))); - expectedConfig.getApiClassConfig().setClientIds(ImmutableList.of(CLIENT_IDS.get(0))); - assertEquals(expectedConfig, config); - - Object memcacheValue = memcacheService.get(MEMCACHE_KEY); - assertEquals(entity, memcacheValue); - } -} - diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriterTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriterTest.java index 0fd9b42f..e752c340 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriterTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/JsonConfigWriterTest.java @@ -48,6 +48,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -212,6 +213,7 @@ public void apiCollation() throws Exception { } @Test + @Ignore("ignored until we find a proper solution") public void bodyFieldConflictsWithParameter() throws Exception { final class Endpoint { @SuppressWarnings("unused") @@ -345,7 +347,7 @@ final class OneTodayAdmin { ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); TypeLoader typeLoader = new TypeLoader(); JsonConfigWriter writer = - new JsonConfigWriter(JsonConfigWriter.class.getClassLoader(), validator); + new JsonConfigWriter(new TypeLoader(JsonConfigWriter.class.getClassLoader()), validator); ApiConfig oneToday = new ApiConfig.Factory().create(serviceContext, typeLoader, OneToday.class); ApiConfig oneTodayAdmin = new ApiConfig.Factory().create(serviceContext, typeLoader, OneTodayAdmin.class); @@ -378,7 +380,7 @@ final class OneTodayAdmin2 { ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); TypeLoader typeLoader = new TypeLoader(); JsonConfigWriter writer = - new JsonConfigWriter(JsonConfigWriter.class.getClassLoader(), validator); + new JsonConfigWriter(new TypeLoader(JsonConfigWriter.class.getClassLoader()), validator); ApiConfig oneToday = new ApiConfig.Factory().create(serviceContext, typeLoader, OneToday.class); ApiConfig oneToday2 = new ApiConfig.Factory().create(serviceContext, typeLoader, OneToday2.class); diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/ResourceSchemaProviderTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/ResourceSchemaProviderTest.java index 7b82f1c9..c936b6cb 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/ResourceSchemaProviderTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/jsonwriter/ResourceSchemaProviderTest.java @@ -31,6 +31,7 @@ import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.testing.DefaultValueSerializer; import com.google.api.server.spi.testing.TestEndpoint; +import com.google.api.server.spi.testing.TestEnum; import com.google.common.reflect.TypeToken; import org.junit.Before; @@ -72,6 +73,14 @@ public void testRenamedProperty() { assertThat(schema.getProperties().keySet()).containsExactly("bar"); } + @Test + public void testDescribedProperty() { + ResourceSchema schema = getResourceSchema(DescribedPropertyBean.class); + assertEquals("description of foo", schema.getProperties().get("foo").getDescription()); + assertEquals("description of bar", schema.getProperties().get("bar").getDescription()); + assertEquals("description of choice", schema.getProperties().get("choice").getDescription()); + } + @Test public void testMissingPropertyType() { ResourceSchema schema = getResourceSchema(MissingPropertyTypeBean.class); @@ -183,6 +192,17 @@ public String getFoo() { } } + private static class DescribedPropertyBean { + @ApiResourceProperty(description = "description of foo") + private String foo; + @ApiResourceProperty(description = "description of bar") + public String getBar() { + return null; + } + @ApiResourceProperty(description = "description of choice") + public TestEnum choice; + } + /** * A JavaBean that has a JsonProperty, but no supporting JavaBean property to access it. */ diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfigTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfigTest.java index efa6acf6..a623a721 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfigTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiIssuerAudienceConfigTest.java @@ -2,8 +2,7 @@ import static com.google.common.truth.Truth.assertThat; -import com.google.common.collect.ImmutableList; - +import com.google.common.collect.ImmutableSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -31,7 +30,7 @@ public void asMap() { ApiIssuerAudienceConfig config = ApiIssuerAudienceConfig.builder() .addIssuerAudiences("issuer", "aud1", "aud2") .build(); - assertThat(config.asMap()).containsExactly("issuer", ImmutableList.of("aud1", "aud2")); + assertThat(config.asMap()).containsExactly("issuer", ImmutableSet.of("aud1", "aud2")); } @Test diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiMethodConfigTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiMethodConfigTest.java index 29d7ab84..fc401d44 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiMethodConfigTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/ApiMethodConfigTest.java @@ -44,8 +44,8 @@ public class ApiMethodConfigTest { private ApiMethodConfig methodConfig; - @Mock - ApiClassConfig apiClassConfig; + @Mock ApiConfig apiConfig; + @Mock ApiClassConfig apiClassConfig; @Mock EndpointMethod method; private static final AuthScopeExpression defaultScopeExpression = @@ -60,12 +60,15 @@ public class ApiMethodConfigTest { @Before public void setUp() throws Exception { + Mockito.when(apiConfig.getName()).thenReturn("testapi"); + Mockito.when(apiConfig.getVersion()).thenReturn("v1"); Mockito.when(apiClassConfig.getResource()).thenReturn("resource"); Mockito.when(apiClassConfig.getAuthLevel()).thenReturn(AuthLevel.NONE); Mockito.when(apiClassConfig.getScopeExpression()).thenReturn(defaultScopeExpression); Mockito.when(apiClassConfig.getAudiences()).thenReturn(defaultAudiences); Mockito.when(apiClassConfig.getClientIds()).thenReturn(defaultClientIds); Mockito.when(apiClassConfig.getApiClassJavaSimpleName()).thenReturn("className"); + Mockito.when(apiClassConfig.getApiConfig()).thenReturn(apiConfig); Mockito.when(method.getMethod()).thenReturn(TestEndpoint.class.getMethod("getResultNoParams")); Mockito.doReturn(TestEndpoint.class).when(method).getEndpointClass(); @@ -110,4 +113,17 @@ public void addInjectedParameter_notInPath() { methodConfig.addParameter("alt", null, false, null, TypeToken.of(String.class)); assertThat(methodConfig.getPath()).doesNotContain("{alt}"); } + + @Test + public void addPathParameter_appendsToCanonicalPath() { + methodConfig.addParameter("test", null, false, null, TypeToken.of(String.class)); + assertThat(methodConfig.getCanonicalPath()).contains("{test}"); + } + + @Test + public void addPathParameter_doesNotAppendIfInPathAlready() { + methodConfig.setPath("test/{test}"); + methodConfig.addParameter("test", null, false, null, TypeToken.of(String.class)); + assertThat(methodConfig.getPath()).isEqualTo("test/{test}"); + } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/SchemaRepositoryTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/SchemaRepositoryTest.java index c81ce625..f62d6d6a 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/SchemaRepositoryTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/SchemaRepositoryTest.java @@ -1,5 +1,8 @@ package com.google.api.server.spi.config.model; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_SUPPORT_ARRAYS_VALUES; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; @@ -14,6 +17,8 @@ import com.google.api.server.spi.config.model.Schema.Field; import com.google.api.server.spi.config.model.Schema.SchemaReference; import com.google.api.server.spi.response.CollectionResponse; +import com.google.api.server.spi.testing.EnumEndpoint; +import com.google.api.server.spi.testing.EnumValue; import com.google.api.server.spi.testing.TestEnum; import com.google.common.reflect.TypeParameter; import com.google.common.reflect.TypeToken; @@ -21,6 +26,7 @@ import org.junit.Before; import org.junit.Test; +import java.util.HashMap; import java.util.Map; /** @@ -75,9 +81,123 @@ public void getOrAdd_any() throws Exception { .isEqualTo(SchemaRepository.ANY_SCHEMA); } + @Test + public void getOrAdd_mapType() throws Exception { + //unsupported map types still use JsonMap schema + checkJsonMap("getStringArrayMap"); + //non-string key values generate an exception + try { + checkJsonMap("getArrayStringMap"); + fail("Should have failed to generate map schema"); + } catch (IllegalArgumentException e) { + //expected exception + } + //supported map types generate proper map schema + ApiMethodConfig methodConfig = getMethodConfig("getStringEnumMap"); + Schema schema = repo.getOrAdd(methodConfig.getReturnType(), config); + assertThat(schema).isEqualTo(Schema.builder() + .setName("Map_String_TestEnum") + .setType("object") + .setMapValueSchema(Field.builder() + .setName(SchemaRepository.MAP_UNUSED_MSG) + .setType(FieldType.ENUM) + .setSchemaReference(SchemaReference.create(repo, config, + TypeToken.of(TestEnum.class))) + .build()) + .build()); + } + + @Test + public void getOrAdd_mapSubType() throws Exception { + Schema expectedSchema = Schema.builder() + .setName("Map_String_String") + .setType("object") + .setMapValueSchema(Field.builder() + .setName(SchemaRepository.MAP_UNUSED_MSG) + .setType(FieldType.STRING) + .build()) + .build(); + assertThat(repo.getOrAdd(getMethodConfig("getMyMap").getReturnType(), config)) + .isEqualTo(expectedSchema); + assertThat(repo.getOrAdd(getMethodConfig("getMySubMap").getReturnType(), config)) + .isEqualTo(expectedSchema); + } + + @Test + public void getOrAdd_mapTypeUnsupportedKeys() throws Exception { + System.setProperty(MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.systemPropertyName, "true"); + try { + checkJsonMap("getArrayStringMap"); + } finally { + System.clearProperty(MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.systemPropertyName); + } + } + + @Test + public void getOrAdd_NestedMap() throws Exception { + Schema expectedSchema = Schema.builder() + .setName("Map_String_Map_String_String") + .setType("object") + .setMapValueSchema(Field.builder() + .setName(SchemaRepository.MAP_UNUSED_MSG) + .setType(FieldType.OBJECT) + .setSchemaReference(SchemaReference.create(repo, config, + new TypeToken>() {})) + .build()) + .build(); + assertThat(repo.getOrAdd(getMethodConfig("getNestedMap").getReturnType(), config)) + .isEqualTo(expectedSchema); + } + + @Test + public void getOrAdd_ParameterizedMap() throws Exception { + checkJsonMap("getParameterizedMap"); + checkJsonMap("getParameterizedKeyMap"); + checkJsonMap("getParameterizedValueMap"); + } + + @Test + public void getOrAdd_RawMap() throws Exception { + checkJsonMap("getRawMap"); + } + + @Test + public void getOrAdd_mapTypeArrayValues() throws Exception { + System.setProperty(MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.systemPropertyName, "true"); + try { + ApiMethodConfig methodConfig = getMethodConfig("getStringArrayMap"); + Schema schema = repo.getOrAdd(methodConfig.getReturnType(), config); + assertThat(schema).isEqualTo(Schema.builder() + .setName("Map_String_StringCollection") + .setType("object") + .setMapValueSchema(Field.builder() + .setName(SchemaRepository.MAP_UNUSED_MSG) + .setType(FieldType.ARRAY) + .setArrayItemSchema(Field.builder() + .setName(SchemaRepository.ARRAY_UNUSED_MSG) + .setType(FieldType.STRING) + .build()) + .build()) + .build()); + } finally { + System.clearProperty(MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.systemPropertyName); + } + } + @Test public void getOrAdd_jsonMap() throws Exception { - ApiMethodConfig methodConfig = getMethodConfig("getJsonMap"); + System.setProperty(MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.systemPropertyName, "true"); + try { + checkJsonMap("getStringEnumMap"); + checkJsonMap("getStringArrayMap"); + checkJsonMap("getArrayStringMap"); + } finally { + System.clearProperty(MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.systemPropertyName); + } + } + + private void checkJsonMap(String methodName) throws Exception { + ApiMethodConfig methodConfig = getMethodConfig(methodName); assertThat(repo.getOrAdd(methodConfig.getReturnType(), config)) .isEqualTo(SchemaRepository.MAP_SCHEMA); } @@ -112,6 +232,25 @@ public void getOrAdd_enum() throws Exception { .build()); } + @Test + public void getOrAdd_recursiveSchema() throws Exception { + TypeToken type = TypeToken.of(SelfReferencingObject.class); + // This test checks the case where a schema is added multiple times. The second time it's added + // to an API, it recurses through the schema. If the schema is self-referencing, we must not + // stack overflow. + repo.getOrAdd(type, config); + assertThat(repo.getOrAdd(type, config)) + .isEqualTo(Schema.builder() + .setName("SelfReferencingObject") + .setType("object") + .addField("foo", Field.builder() + .setName("foo") + .setType(FieldType.OBJECT) + .setSchemaReference(SchemaReference.create(repo, config, type)) + .build()) + .build()); + } + @Test public void get() { TypeToken> type = new TypeToken>() {}; @@ -120,6 +259,32 @@ public void get() { checkParameterizedSchema(repo.get(type, config), Integer.class); } + @Test + public void getOrAdd_multipleApis() throws Exception { + // Adding the same resource to multiple APIs should add field resources as well. + ApiConfig config2 = configLoader.loadConfiguration(ServiceContext.create(), EnumEndpoint.class); + repo.getOrAdd(new TypeToken() {}, config); + repo.getOrAdd(new TypeToken() {}, config2); + assertThat(repo.getAllSchemaForApi(config2.getApiKey().withoutRoot())).containsExactly( + Schema.builder() + .setName("TestEnum") + .setType("string") + .addEnumValue("VALUE1") + .addEnumValue("VALUE2") + .addEnumDescription("") + .addEnumDescription("") + .build(), + Schema.builder() + .setName("EnumValue") + .setType("object") + .addField("value", Field.builder() + .setName("value") + .setSchemaReference(SchemaReference.create(repo, config2, new TypeToken() {})) + .setType(FieldType.ENUM) + .build()) + .build()); + } + @Api(transformers = {ParameterizedShortTransformer.class}) private static class FooEndpoint { public Parameterized setParameterized(Parameterized p) { @@ -138,7 +303,43 @@ public Object getAny() { return null; } - public Map getJsonMap() { + public Map getStringEnumMap() { + return null; + } + + public Map getStringArrayMap() { + return null; + } + + public Map getArrayStringMap() { + return null; + } + + public MyMap getMyMap() { + return null; + } + + public Map> getNestedMap() { + return null; + } + + public Map getParameterizedMap() { + return null; + } + + public Map getParameterizedKeyMap() { + return null; + } + + public Map getParameterizedValueMap() { + return null; + } + + public Map getRawMap() { + return null; + } + + public MySubMap getMySubMap() { return null; } @@ -147,6 +348,10 @@ public Parameterized getTransformed() { } } + private static class MyMap extends HashMap { } + + private static class MySubMap extends MyMap { } + private static class Parameterized { public T getFoo() { return null; @@ -176,6 +381,12 @@ public Parameterized transformFrom(Parameterized in) { } } + private static class SelfReferencingObject { + public SelfReferencingObject getFoo() { + return null; + } + } + private ApiMethodConfig fooEndpointSetParameterized() throws Exception { return getMethodConfig("setParameterized", Parameterized.class); } @@ -250,4 +461,4 @@ private static void checkIntegerCollection(Schema schema) { .build()) .build()); } -} \ No newline at end of file +} diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/StandardParametersTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/StandardParametersTest.java index f10b1385..72536d0e 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/StandardParametersTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/model/StandardParametersTest.java @@ -17,10 +17,13 @@ import static com.google.common.truth.Truth.assertThat; +import com.google.api.server.spi.EndpointsContext; + import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; /** * Tests for {@link StandardParameters}. @@ -28,22 +31,48 @@ @RunWith(JUnit4.class) public class StandardParametersTest { @Test - public void shouldPrettyPrint_defaultValueIsTrue() { - assertThat(StandardParameters.shouldPrettyPrint(new MockHttpServletRequest())).isTrue(); + public void shouldPrettyPrint_defaultValueIsTrue_globalDefaultTrue() { + assertThat(StandardParameters.shouldPrettyPrint( + getEndpointsContext(new MockHttpServletRequest(), true))).isTrue(); + } + + @Test + public void shouldPrettyPrint_false_globalDefaultTrue() { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setParameter("prettyPrint", "false"); + assertThat(StandardParameters.shouldPrettyPrint(getEndpointsContext(request, true))).isFalse(); + } + + @Test + public void shouldPrettyPrint_true_globalDefaultTrue() { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setParameter("prettyPrint", "true"); + assertThat(StandardParameters.shouldPrettyPrint(getEndpointsContext(request, true))).isTrue(); + } + + @Test + public void shouldPrettyPrint_defaultValueIsFalse_globalDefaultFalse() { + assertThat(StandardParameters.shouldPrettyPrint( + getEndpointsContext(new MockHttpServletRequest(), false))).isFalse(); } @Test - public void shouldPrettyPrint_false() { + public void shouldPrettyPrint_false_globalDefaultFalse() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("prettyPrint", "false"); - assertThat(StandardParameters.shouldPrettyPrint(request)).isFalse(); + assertThat(StandardParameters.shouldPrettyPrint(getEndpointsContext(request, false))).isFalse(); } @Test - public void shouldPrettyPrint_true() { + public void shouldPrettyPrint_true_globalDefaultFalse() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("prettyPrint", "true"); - assertThat(StandardParameters.shouldPrettyPrint(request)).isTrue(); + assertThat(StandardParameters.shouldPrettyPrint(getEndpointsContext(request, false))).isTrue(); + } + + private EndpointsContext getEndpointsContext( + MockHttpServletRequest request, boolean prettyPrint) { + return new EndpointsContext("GET", "/", request, new MockHttpServletResponse(), prettyPrint); } @Test diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/config/validation/ApiConfigValidatorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/config/validation/ApiConfigValidatorTest.java index cd2a1e8b..db671bb3 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/config/validation/ApiConfigValidatorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/config/validation/ApiConfigValidatorTest.java @@ -24,6 +24,7 @@ import com.google.api.server.spi.EndpointMethod; import com.google.api.server.spi.ServiceContext; +import com.google.api.server.spi.TypeLoader; import com.google.api.server.spi.auth.common.User; import com.google.api.server.spi.config.AnnotationBoolean; import com.google.api.server.spi.config.Api; @@ -36,6 +37,7 @@ import com.google.api.server.spi.config.PeerAuthenticator; import com.google.api.server.spi.config.Transformer; import com.google.api.server.spi.config.model.ApiConfig; +import com.google.api.server.spi.config.model.SchemaRepository; import com.google.api.server.spi.testing.DefaultValueSerializer; import com.google.api.server.spi.testing.DuplicateMethodEndpoint; import com.google.api.server.spi.testing.PassAuthenticator; @@ -51,7 +53,6 @@ import org.junit.runners.JUnit4; import java.lang.reflect.Method; -import java.lang.reflect.Type; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -71,7 +72,9 @@ public class ApiConfigValidatorTest { @Before public void setUp() throws Exception { - validator = new ApiConfigValidator(); + TypeLoader typeLoader = new TypeLoader(ApiConfigValidator.class.getClassLoader()); + SchemaRepository schemaRepository = new SchemaRepository(typeLoader); + validator = new ApiConfigValidator(typeLoader, schemaRepository); configFactory = new ApiConfig.Factory(); configLoader = new ApiConfigLoader(); config = configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); @@ -168,11 +171,13 @@ public void testNonuniqueJavaNames() throws Exception { when(method1.getMethod()).thenReturn(DuplicateMethodEndpoint.class.getMethod( "foo", String.class)); doReturn(TestEndpoint.class).when(method1).getEndpointClass(); + when(method1.getReturnType()).thenReturn((TypeToken) TypeToken.of(Void.class)); EndpointMethod method2 = mock(EndpointMethod.class); when(method2.getMethod()).thenReturn(DuplicateMethodEndpoint.class.getMethod( "foo", Integer.class)); doReturn(TestEndpoint.class).when(method2).getEndpointClass(); + when(method2.getReturnType()).thenReturn((TypeToken) TypeToken.of(Void.class)); config.getApiClassConfig().getMethods().getOrCreate(method1).setPath("fn1"); config.getApiClassConfig().getMethods().getOrCreate(method2).setPath("fn2"); diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/AuthScopeDescriptions.java b/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/AuthScopeDescriptions.java new file mode 100644 index 00000000..1f160e22 --- /dev/null +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/AuthScopeDescriptions.java @@ -0,0 +1,77 @@ +package com.google.api.server.spi.discovery; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Ordering; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URL; +import java.util.Collections; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Vector; +import javax.annotation.Nullable; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; + +/** + * Fetches up-to-date auth scope descriptions from https://developers.google.com/identity/protocols/googlescopes. + * Use this to update the googleScopeDescriptions.properties. + * Uses Jsoup from the appengine-api-stubs package (used as test dependency). + */ +public class AuthScopeDescriptions { + + private static final String GOOGLESCOPES_URL = "https://developers.google.com/identity/protocols/googlescopes"; + + //short scopes first, then order alphabetically + private static final Ordering SCOPE_ORDERING = Ordering.compound( + ImmutableList.of( + new Ordering() { + @Override + public int compare(@Nullable String left, @Nullable String right) { + return Boolean.compare(left.startsWith("https"), right.startsWith("https")); + } + }, + Ordering.natural() + ) + ); + + public static void main(String[] args) throws Exception { + new AuthScopeDescriptions().print(System.out); + } + + private Map descriptionsByScope = new LinkedHashMap<>(); + + private AuthScopeDescriptions() throws Exception { + final Document document = Jsoup.parse(new URL(GOOGLESCOPES_URL), 10000); + final Elements scopes = document.select("table.responsive tr:has(td)"); + for (Element scope : scopes) { + final Elements cells = scope.select("td"); + descriptionsByScope.put(cells.get(0).text(), cells.get(1).text()); + } + } + + private void print(OutputStream out) throws IOException { + //sorted properties + Properties properties = new Properties() { + public Enumeration keys() { + Enumeration keysEnum = super.keys(); + Vector keyList = new Vector<>(); + while (keysEnum.hasMoreElements()) { + keyList.add((String) keysEnum.nextElement()); + } + Collections.sort(keyList, SCOPE_ORDERING); + return keyList.elements(); + } + }; + for (Entry entry : descriptionsByScope.entrySet()) { + properties.setProperty(entry.getKey(), entry.getValue()); + } + properties.store(out, "Source: " + GOOGLESCOPES_URL); + } + +} diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/DiscoveryGeneratorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/DiscoveryGeneratorTest.java index cb57193b..b4de96b0 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/DiscoveryGeneratorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/discovery/DiscoveryGeneratorTest.java @@ -15,21 +15,35 @@ */ package com.google.api.server.spi.discovery; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_SUPPORT_ARRAYS_VALUES; import static com.google.common.truth.Truth.assertThat; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.server.spi.IoUtil; +import com.google.api.server.spi.ObjectMapperUtil; import com.google.api.server.spi.ServiceContext; import com.google.api.server.spi.TypeLoader; import com.google.api.server.spi.config.ApiConfigLoader; import com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader; import com.google.api.server.spi.config.model.ApiConfig; +import com.google.api.server.spi.config.model.SchemaRepository; import com.google.api.server.spi.discovery.DiscoveryGenerator.DiscoveryContext; +import com.google.api.server.spi.testing.AbsoluteCommonPathEndpoint; +import com.google.api.server.spi.testing.AbsolutePathEndpoint; import com.google.api.server.spi.testing.ArrayEndpoint; +import com.google.api.server.spi.testing.CustomScopesEndpoint; import com.google.api.server.spi.testing.EnumEndpoint; +import com.google.api.server.spi.testing.EnumEndpointV2; +import com.google.api.server.spi.testing.FooDescriptionEndpoint; import com.google.api.server.spi.testing.FooEndpoint; +import com.google.api.server.spi.testing.MapEndpoint; +import com.google.api.server.spi.testing.MapEndpointInvalid; import com.google.api.server.spi.testing.MultipleParameterEndpoint; import com.google.api.server.spi.testing.NamespaceEndpoint; +import com.google.api.server.spi.testing.NonDiscoverableEndpoint; +import com.google.api.server.spi.testing.PrimitiveEndpoint; import com.google.api.services.discovery.model.DirectoryList; import com.google.api.services.discovery.model.RestDescription; import com.google.common.collect.ImmutableList; @@ -37,13 +51,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import io.swagger.util.Json; - /** * Tests for {@link DiscoveryGenerator}. */ @@ -51,9 +64,10 @@ public class DiscoveryGeneratorTest { private final DiscoveryContext context = new DiscoveryContext() .setApiRoot("https://discovery-test.appspot.com/api"); - private final ObjectMapper mapper = Json.mapper(); + private final ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); private DiscoveryGenerator generator; private ApiConfigLoader configLoader; + private SchemaRepository schemaRepository; @Before public void setUp() throws Exception { @@ -63,18 +77,19 @@ public void setUp() throws Exception { this.configLoader = new ApiConfigLoader(new ApiConfig.Factory(), typeLoader, annotationReader); this.generator = new DiscoveryGenerator(typeLoader); + this.schemaRepository = new SchemaRepository(typeLoader); } @Test public void testWriteDiscovery_FooEndpoint() throws Exception { - RestDescription doc = getDiscovery(FooEndpoint.class, context); + RestDescription doc = getDiscovery(context, FooEndpoint.class); RestDescription expected = readExpectedAsDiscovery("foo_endpoint.json"); compareDiscovery(expected, doc); } @Test public void testWriteDiscovery_FooEndpointDefaultContext() throws Exception { - RestDescription doc = getDiscovery(FooEndpoint.class, new DiscoveryContext()); + RestDescription doc = getDiscovery(new DiscoveryContext(), FooEndpoint.class); RestDescription expected = readExpectedAsDiscovery("foo_endpoint_default_context.json"); compareDiscovery(expected, doc); } @@ -82,35 +97,86 @@ public void testWriteDiscovery_FooEndpointDefaultContext() throws Exception { @Test public void testWriteDiscovery_FooEndpointLocalhost() throws Exception { RestDescription doc = getDiscovery( - FooEndpoint.class, new DiscoveryContext().setApiRoot("http://localhost:8080/api")); + new DiscoveryContext().setApiRoot("http://localhost:8080/api"), FooEndpoint.class); RestDescription expected = readExpectedAsDiscovery("foo_endpoint_localhost.json"); compareDiscovery(expected, doc); } @Test public void testWriteDiscovery_EnumEndpoint() throws Exception { - RestDescription doc = getDiscovery(EnumEndpoint.class, new DiscoveryContext()); + RestDescription doc = getDiscovery(new DiscoveryContext(), EnumEndpoint.class); RestDescription expected = readExpectedAsDiscovery("enum_endpoint.json"); compareDiscovery(expected, doc); } @Test public void testWriteDiscovery_ArrayEndpoint() throws Exception { - RestDescription doc = getDiscovery(ArrayEndpoint.class, new DiscoveryContext()); + RestDescription doc = getDiscovery(new DiscoveryContext(), ArrayEndpoint.class); RestDescription expected = readExpectedAsDiscovery("array_endpoint.json"); compareDiscovery(expected, doc); } + @Test + public void testWriteDiscovery_MapEndpoint() throws Exception { + RestDescription doc = getDiscovery(new DiscoveryContext(), MapEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("map_endpoint.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_MapEndpoint_Legacy() throws Exception { + System.setProperty(MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.systemPropertyName, ""); + try { + RestDescription doc = getDiscovery(new DiscoveryContext(), MapEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("map_endpoint_legacy.json"); + compareDiscovery(expected, doc); + } finally { + System.clearProperty(MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.systemPropertyName); + } + } + + @Test + public void testWriteDiscovery_MapEndpoint_InvalidKeyType() throws Exception { + try { + getDiscovery(new DiscoveryContext(), MapEndpointInvalid.class); + Assert.fail("Should have failed to generate schema for invalid key type"); + } catch (IllegalArgumentException e) { + //expected + } + } + + @Test + public void testWriteDiscovery_MapEndpoint_InvalidKeyType_ignore() throws Exception { + System.setProperty(MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.systemPropertyName, "true"); + try { + getDiscovery(new DiscoveryContext(), MapEndpointInvalid.class); + } finally { + System.clearProperty(MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.systemPropertyName); + } + } + + @Test + public void testWriteDiscovery_MapEndpoint_WithArrayValue() throws Exception { + System.setProperty(MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.systemPropertyName, "yes"); + try { + RestDescription doc = getDiscovery(new DiscoveryContext(), MapEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("map_endpoint_with_array.json"); + compareDiscovery(expected, doc); + } finally { + System.clearProperty(MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.systemPropertyName); + } + } + @Test public void testWriteDiscovery_namespace() throws Exception { - RestDescription doc = getDiscovery(NamespaceEndpoint.class, new DiscoveryContext()); + RestDescription doc = getDiscovery(new DiscoveryContext(), NamespaceEndpoint.class); RestDescription expected = readExpectedAsDiscovery("namespace_endpoint.json"); compareDiscovery(expected, doc); } @Test public void testWriteDiscovery_parameterOrder() throws Exception { - RestDescription doc = getDiscovery(MultipleParameterEndpoint.class, new DiscoveryContext()); + RestDescription doc = getDiscovery(new DiscoveryContext(), MultipleParameterEndpoint.class); RestDescription expected = readExpectedAsDiscovery("multiple_parameter_endpoint.json"); compareDiscovery(expected, doc); } @@ -118,12 +184,59 @@ public void testWriteDiscovery_parameterOrder() throws Exception { @Test public void testWriteDiscovery_newHostname() throws Exception { RestDescription doc = getDiscovery( - FooEndpoint.class, - new DiscoveryContext().setApiRoot("http://notlocalhost/api").setHostname("localhost:8080")); + new DiscoveryContext().setApiRoot("http://notlocalhost/api").setHostname("localhost:8080"), + FooEndpoint.class + ); RestDescription expected = readExpectedAsDiscovery("foo_endpoint_localhost.json"); compareDiscovery(expected, doc); } + @Test + public void testWriteDiscovery_PrimitiveEndpoint() throws Exception { + RestDescription doc = getDiscovery(context, PrimitiveEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("primitive_endpoint.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_AbsolutePathEndpoint() throws Exception { + RestDescription doc = getDiscovery(context, AbsolutePathEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("absolute_path_endpoint.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_AbsoluteCommonPathEndpoint() throws Exception { + RestDescription doc = getDiscovery(context, AbsoluteCommonPathEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("absolute_common_path_endpoint.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_FooEndpointWithDescription() throws Exception { + RestDescription doc = getDiscovery(context, FooDescriptionEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("foo_with_description_endpoint.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_multipleApisWithSharedSchema() throws Exception { + // Read in an API that uses a resource with fields that have their own schema, then read in + // another API that uses the same resource. The discovery for the second API should contain + // both schema, rather than just the first one. + getDiscovery(new DiscoveryContext(), EnumEndpointV2.class); + RestDescription doc = getDiscovery(new DiscoveryContext(), EnumEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("enum_endpoint.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_scopeDescriptions() throws Exception { + RestDescription doc = getDiscovery(context, CustomScopesEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("custom_scopes.json"); + compareDiscovery(expected, doc); + } + @Test public void testWriteDiscovery_directory() throws Exception { DiscoveryGenerator.Result result = @@ -135,6 +248,24 @@ public void testWriteDiscovery_directory() throws Exception { assertThat(result.directory()).isEqualTo(readExpectedAsDirectory("directory.json")); } + @Test + public void testWriteDiscovery_nonDiscoverableEndpointButGenerateAll() throws Exception { + getDiscovery(context, NonDiscoverableEndpoint.class); + RestDescription doc = getDiscovery(new DiscoveryContext(), NonDiscoverableEndpoint.class); + RestDescription expected = readExpectedAsDiscovery("foo_endpoint_default_context.json"); + compareDiscovery(expected, doc); + } + + @Test + public void testWriteDiscovery_nonDiscoverableEndpoint() throws Exception { + DiscoveryGenerator.Result result = generator.writeDiscovery( + ImmutableList.of( + configLoader.loadConfiguration(ServiceContext.create(), NonDiscoverableEndpoint.class)), + new DiscoveryContext().setGenerateAll(false)); + assertThat(result.discoveryDocs()).isEmpty(); + assertThat(result.directory().getItems()).isEmpty(); + } + @Test public void testDirectoryIsCloneable() throws Exception { ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), FooEndpoint.class); @@ -142,12 +273,13 @@ public void testDirectoryIsCloneable() throws Exception { result.directory().clone(); } - private RestDescription getDiscovery(Class serviceClass, DiscoveryContext context) + private RestDescription getDiscovery(DiscoveryContext context, Class serviceClass) throws Exception { ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), serviceClass); // If the clone call fails, the generated discovery is invalid. return Iterables.getFirst( - generator.writeDiscovery(ImmutableList.of(config), context).discoveryDocs().values(), + generator.writeDiscovery( + ImmutableList.of(config), context, schemaRepository).discoveryDocs().values(), null).clone(); } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/dispatcher/PathDispatcherTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/dispatcher/PathDispatcherTest.java index b281e466..90562830 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/dispatcher/PathDispatcherTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/dispatcher/PathDispatcherTest.java @@ -121,4 +121,10 @@ public void builderNullHandler() { // expected } } + + @Test + public void methodNotKnown() throws IOException { + PathDispatcher dispatcher = PathDispatcher.builder().build(); + assertThat(dispatcher.dispatch("INVALID", "test/one/two/3", context)).isFalse(); + } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ApiProxyHandlerTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ApiProxyHandlerTest.java index 78ab5dfa..b48c4a18 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ApiProxyHandlerTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ApiProxyHandlerTest.java @@ -47,10 +47,11 @@ private void testWithServletPath(String servletPath) throws Exception { request.setServletPath(servletPath); MockHttpServletResponse response = new MockHttpServletResponse(); ApiProxyHandler handler = new ApiProxyHandler(); - EndpointsContext context = new EndpointsContext("GET", "static/proxy.html", request, response); + EndpointsContext context = + new EndpointsContext("GET", "static/proxy.html", request, response, true); handler.handle(context); - assertThat(response.getContentAsString()).contains(servletPath); + assertThat(response.getContentAsString()).contains("googleapis.server.init()"); } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerTest.java index d75ec4e0..634ab850 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/EndpointsMethodHandlerTest.java @@ -66,7 +66,7 @@ public void setUp() throws Exception { classLoader = EndpointsMethodHandlerTest.class.getClassLoader(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); - context = new EndpointsContext("", "", request, response); + context = new EndpointsContext("", "", request, response, true); systemService = SystemService.builder() .withDefaults(classLoader) .addService(TestEndpoint.class, new TestEndpoint()) @@ -108,8 +108,7 @@ public void fail_findService() throws Exception { .build(); TestMethodHandler handler = new TestMethodHandler( ServletInitializationParameters.builder().build(), method, - apiConfig, methodConfig, systemService, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - RESOURCE); + methodConfig, systemService, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RESOURCE); handler.getRestHandler().handle(context); } @@ -120,8 +119,8 @@ public void rootMethodHandler() throws Exception { apiConfig.getApiClassConfig()); methodConfig.setPath("/root"); TestMethodHandler handler = new TestMethodHandler( - ServletInitializationParameters.builder().build(), method, apiConfig, methodConfig, - systemService, 200); + ServletInitializationParameters.builder().build(), method, methodConfig, systemService, + 200); assertThat(handler.getRestPath()).isEqualTo("root"); } @@ -131,7 +130,7 @@ private TestMethodHandler createTestHandler(String methodName, Object expectedRe ApiMethodConfig methodConfig = new ApiMethodConfig(method, typeLoader, apiConfig.getApiClassConfig()); return new TestMethodHandler(ServletInitializationParameters.builder().build(), method, - apiConfig, methodConfig, systemService, expectedResponse, params); + methodConfig, systemService, expectedResponse, params); } private static class TestMethodHandler extends EndpointsMethodHandler { @@ -140,12 +139,11 @@ private static class TestMethodHandler extends EndpointsMethodHandler { public TestMethodHandler( ServletInitializationParameters initParameters, EndpointMethod endpointMethod, - ApiConfig apiConfig, ApiMethodConfig methodConfig, SystemService systemService, Object expectedResult, Object... params) { - super(initParameters, null /* servletContext */, endpointMethod, apiConfig, methodConfig, + super(initParameters, null /* servletContext */, endpointMethod, methodConfig, systemService); this.params = params; this.expectedResult = expectedResult; diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ExplorerHandlerTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ExplorerHandlerTest.java index 0a0aaa9c..47d59d36 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ExplorerHandlerTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/handlers/ExplorerHandlerTest.java @@ -31,18 +31,34 @@ public class ExplorerHandlerTest { @Test public void testHandle() throws Exception { + testHandle("http", 8080, "http://apis-explorer.appspot.com/apis-explorer/" + + "?base=http://localhost:8080/_ah/api&root=http://localhost:8080/_ah/api"); + } + + @Test + public void testHandle_explicitHttpPort() throws Exception { + testHandle("http", 80, "http://apis-explorer.appspot.com/apis-explorer/" + + "?base=http://localhost/_ah/api&root=http://localhost/_ah/api"); + } + + @Test + public void testHandle_explicitHttpsPort() throws Exception { + testHandle("https", 443, "http://apis-explorer.appspot.com/apis-explorer/" + + "?base=https://localhost/_ah/api&root=https://localhost/_ah/api"); + } + + private void testHandle(String scheme, int port, String expectedLocation) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); + request.setScheme(scheme); request.setServerName("localhost"); - request.setServerPort(8080); + request.setServerPort(port); request.setRequestURI("/_ah/api/explorer/"); MockHttpServletResponse response = new MockHttpServletResponse(); ExplorerHandler handler = new ExplorerHandler(); - EndpointsContext context = new EndpointsContext("GET", "explorer", request, response); + EndpointsContext context = new EndpointsContext("GET", "explorer", request, response, true); handler.handle(context); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND); - assertThat(response.getHeader("Location")).isEqualTo( - "http://apis-explorer.appspot.com/apis-explorer/?base=http://localhost:8080/_ah/api" - + "&root=http://localhost:8080/_ah/api"); + assertThat(response.getHeader("Location")).isEqualTo(expectedLocation); } } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/request/AttributeTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/request/AttributeTest.java index 830126f9..bd6f69ce 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/request/AttributeTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/request/AttributeTest.java @@ -20,8 +20,8 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +import com.google.api.server.spi.EndpointsServlet; import com.google.api.server.spi.ServletInitializationParameters; -import com.google.api.server.spi.SystemServiceServlet; import com.google.api.server.spi.config.model.ApiMethodConfig; import com.google.common.collect.ImmutableList; @@ -113,7 +113,7 @@ public void bindStandardRequestAttributes_apiMethodConfig() throws Exception { /** * Sets up some expectations for {@link #servletConfig} when it is passed to - * {@link SystemServiceServlet#init(ServletConfig)}. + * {@link EndpointsServlet#init(ServletConfig)}. * * @throws ServletException */ diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/request/RestServletRequestParamReaderTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/request/RestServletRequestParamReaderTest.java index 15023dac..e55ebc15 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/request/RestServletRequestParamReaderTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/request/RestServletRequestParamReaderTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.fail; import com.google.api.server.spi.EndpointMethod; +import com.google.api.server.spi.EndpointsContext; import com.google.api.server.spi.ServiceContext; import com.google.api.server.spi.TypeLoader; import com.google.api.server.spi.config.Api; @@ -26,6 +27,7 @@ import com.google.api.server.spi.config.ApiMethod.HttpMethod; import com.google.api.server.spi.config.DefaultValue; import com.google.api.server.spi.config.Named; +import com.google.api.server.spi.config.Nullable; import com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.ApiMethodConfig; @@ -35,11 +37,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -61,6 +65,7 @@ public class RestServletRequestParamReaderTest { private EndpointMethod endpointMethod; private MockHttpServletRequest request; private ApiSerializationConfig serializationConfig; + private ApiConfig apiConfig; private ApiMethodConfig methodConfig; @Before @@ -72,13 +77,12 @@ public void setUp() throws Exception { ServiceContext serviceContext = ServiceContext.create(); serializationConfig = new ApiSerializationConfig(); TypeLoader typeLoader = new TypeLoader(); - ApiConfig config = (new ApiConfig.Factory()).create(serviceContext, typeLoader, - TestApi.class); + apiConfig = new ApiConfig.Factory().create(serviceContext, typeLoader, TestApi.class); ApiConfigAnnotationReader annotationReader = new ApiConfigAnnotationReader(); - annotationReader.loadEndpointClass(serviceContext, TestApi.class, config); + annotationReader.loadEndpointClass(serviceContext, TestApi.class, apiConfig); annotationReader.loadEndpointMethods(serviceContext, TestApi.class, - config.getApiClassConfig().getMethods()); - methodConfig = config.getApiClassConfig().getMethods().get(endpointMethod); + apiConfig.getApiClassConfig().getMethods()); + methodConfig = apiConfig.getApiClassConfig().getMethods().get(endpointMethod); } @Test @@ -186,9 +190,51 @@ public void gzippedRequest() throws Exception { .inOrder(); } + @Test + public void arrayPathParam() throws Exception { + endpointMethod = EndpointMethod.create(TestApi.class, + TestApi.class.getMethod("testArrayPathParam", ArrayList.class)); + methodConfig = apiConfig.getApiClassConfig().getMethods().get(endpointMethod); + RestServletRequestParamReader reader = createReader(ImmutableMap.of("values", "4,3,2,1")); + + Object[] params = reader.read(); + + assertThat(params).hasLength(endpointMethod.getParameterClasses().length); + assertThat(params).asList() + .containsExactly(ImmutableList.of("4", "3", "2", "1")); + } + + @Test + public void multipartFormData() throws Exception { + endpointMethod = EndpointMethod.create(TestApi.class, + TestApi.class.getMethod("testFormData", String.class, Integer.class)); + methodConfig = apiConfig.getApiClassConfig().getMethods().get(endpointMethod); + request.setContentType("multipart/form-data; boundary=----test"); + request.setMethod("POST"); + String requestContent = + "------test\r\n" + + "Content-Disposition: form-data; name=\"foo\"\r\n\r\n" + + "test\r\n" + + "------test\r\n" + + "Content-Disposition: form-data; name=\"bar\"\r\n\r\n" + + "1234\r\n" + + "------test--\r\n"; + request.setContent(requestContent.getBytes(StandardCharsets.UTF_8)); + RestServletRequestParamReader reader = createReader(ImmutableMap.of()); + + Object[] params = reader.read(); + + assertThat(params).hasLength(endpointMethod.getParameterClasses().length); + assertThat(params).asList() + .containsExactly("test", 1234); + } + private RestServletRequestParamReader createReader(Map rawPathParameters) { - return new RestServletRequestParamReader(endpointMethod, request, null, - serializationConfig, methodConfig, rawPathParameters); + EndpointsContext endpointsContext = + new EndpointsContext("GET", "/", request, new MockHttpServletResponse(), true); + endpointsContext.setRawPathParameters(rawPathParameters); + return new RestServletRequestParamReader(endpointMethod, endpointsContext, null, + serializationConfig, methodConfig); } public static class TestResource { @@ -209,10 +255,28 @@ public boolean equals(Object o) { @Api public static class TestApi { @ApiMethod(name = "test", httpMethod = HttpMethod.GET, path = "test/{path}") - public void test(@Named("path") long path, @Named("dates") List dates, + public void test( + @Nullable @Named("path") long path, + @Nullable @Named("dates") List dates, @Named("defaultvalue") @DefaultValue("2015-01-01") SimpleDate defaultValue, TestResource resource) { } + + @ApiMethod( + name = "testArrayPathParam", + httpMethod = HttpMethod.GET, + path = "testArrayPathParam/{values}") + public void testArrayPathParam(@Named("values") ArrayList values) { + } + + @ApiMethod( + name = "testFormData", + httpMethod = HttpMethod.POST, + path = "testFormData") + public void testFormData( + @Nullable @Named("foo") String foo, + @Nullable @Named("bar") Integer bar) { + } } private static byte[] compress(byte[] bytes) { diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/request/ServletRequestParamReaderTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/request/ServletRequestParamReaderTest.java index e9dbda79..5061f134 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/request/ServletRequestParamReaderTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/request/ServletRequestParamReaderTest.java @@ -24,9 +24,14 @@ import static org.mockito.Mockito.when; import com.google.api.server.spi.EndpointMethod; +import com.google.api.server.spi.EndpointsContext; import com.google.api.server.spi.auth.common.User; +import com.google.api.server.spi.config.AuthLevel; import com.google.api.server.spi.config.Named; import com.google.api.server.spi.config.Nullable; +import com.google.api.server.spi.config.model.ApiMethodConfig; +import com.google.api.server.spi.response.BadRequestException; +import com.google.api.server.spi.response.UnauthorizedException; import com.google.api.server.spi.testing.TestEndpoint; import com.google.api.server.spi.testing.TestEndpoint.Request; import com.google.api.server.spi.types.DateAndTime; @@ -35,12 +40,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.reflect.TypeToken; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -55,10 +54,15 @@ import java.util.Map; import java.util.Set; import java.util.TimeZone; - import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; /** * Tests for {@link ServletRequestParamReader}. @@ -83,6 +87,15 @@ public class ServletRequestParamReaderTest { @Mock private ServletContext context; + @Mock + private EndpointsContext endpointsContext; + + @Before + public void setUp() { + when(endpointsContext.getRequest()).thenReturn(request); + when(endpointsContext.isPrettyPrintEnabled()).thenReturn(true); + } + @Test public void testRead() throws Exception { Object[] params = readExecuteMethod(ImmutableMap.builder() @@ -97,6 +110,8 @@ public void testRead() throws Exception { .put(TestEndpoint.NAME_LONG_OBJECT, String.valueOf(VALUE_LONG)) .put(TestEndpoint.NAME_FLOAT_OBJECT, String.valueOf(VALUE_FLOAT)) .put(TestEndpoint.NAME_DOUBLE_OBJECT, String.valueOf(VALUE_DOUBLE)) + .put("stringValue", "321") + .put("integerValue", "321") .put("more", "999").build()); assertEquals(VALUE_STRING, params[0]); @@ -110,8 +125,8 @@ public void testRead() throws Exception { assertEquals(VALUE_LONG, params[8]); assertEquals(VALUE_FLOAT, params[9]); assertEquals(VALUE_DOUBLE, params[10]); - assertEquals(VALUE_STRING, ((Request) params[11]).getString()); - assertEquals(VALUE_INTEGER, (int) ((Request) params[11]).getInteger()); + assertEquals("321", ((Request) params[11]).getStringValue()); + assertEquals(321, (int) ((Request) params[11]).getIntegerValue()); assertEquals(USER, params[12]); assertEquals(APP_ENGINE_USER, params[13]); assertEquals(request, params[14]); @@ -133,26 +148,30 @@ public void testReadMissingParameters() throws Exception { .put(TestEndpoint.NAME_STRING, "\"" + VALUE_STRING + "\"") .put(TestEndpoint.NAME_BOOLEAN, String.valueOf(VALUE_BOOLEAN)) .put(TestEndpoint.NAME_LONG, String.valueOf(VALUE_LONG)) + .put(TestEndpoint.NAME_LONG_OBJECT, String.valueOf(VALUE_LONG)) .put(TestEndpoint.NAME_DOUBLE, String.valueOf(VALUE_DOUBLE)) + .put(TestEndpoint.NAME_DOUBLE_OBJECT, String.valueOf(VALUE_DOUBLE)) .put(TestEndpoint.NAME_BOOLEAN_OBJECT, String.valueOf(VALUE_BOOLEAN)) + .put(TestEndpoint.NAME_INTEGER, String.valueOf(VALUE_INTEGER)) .put(TestEndpoint.NAME_INTEGER_OBJECT, String.valueOf(VALUE_INTEGER)) - .put(TestEndpoint.NAME_LONG_OBJECT, String.valueOf(VALUE_LONG)) + .put(TestEndpoint.NAME_FLOAT, String.valueOf(VALUE_FLOAT)) .put(TestEndpoint.NAME_FLOAT_OBJECT, String.valueOf(VALUE_FLOAT)) + .put("stringValue", "321") .put("more", "999").build()); assertEquals(VALUE_STRING, params[0]); assertEquals(VALUE_BOOLEAN, params[1]); - assertNull(params[2]); + assertEquals(VALUE_INTEGER, params[2]); assertEquals(VALUE_LONG, params[3]); - assertNull(params[4]); + assertEquals(VALUE_FLOAT, params[4]); assertEquals(VALUE_DOUBLE, params[5]); assertEquals(VALUE_BOOLEAN, params[6]); assertEquals(VALUE_INTEGER, params[7]); assertEquals(VALUE_LONG, params[8]); assertEquals(VALUE_FLOAT, params[9]); - assertNull(params[10]); - assertEquals(VALUE_STRING, ((Request) params[11]).getString()); - assertEquals(-1, (int) ((Request) params[11]).getInteger()); + assertEquals(VALUE_DOUBLE, params[10]); + assertEquals("321", ((Request) params[11]).getStringValue()); + assertEquals(-1, (int) ((Request) params[11]).getIntegerValue()); assertEquals(USER, params[12]); assertEquals(APP_ENGINE_USER, params[13]); assertEquals(request, params[14]); @@ -222,20 +241,20 @@ public void testReadNoParameters() throws Exception { public void testReadByteArrayParameter() throws Exception { Method method = TestEndpoint.class.getDeclaredMethod("doSomething", byte[].class); - Object[] params = readParameters("\"AQIDBA==\"", method); + Object[] params = readParameters("{\"bytes\":\"AQIDBA==\"}", method); assertEquals(1, params.length); - assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, (byte[]) params[0])); + assertThat((byte[]) params[0]).isEqualTo(new byte[]{1, 2, 3, 4}); } @Test public void testReadBlobParameter() throws Exception { Method method = TestEndpoint.class.getDeclaredMethod("doBlob", Blob.class); - Object[] params = readParameters("\"AQIDBA==\"", method); + Object[] params = readParameters("{\"blob\":\"AQIDBA==\"}", method); assertEquals(1, params.length); - assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, ((Blob) params[0]).getBytes())); + assertThat(((Blob) params[0]).getBytes()).isEqualTo(new byte[]{1, 2, 3, 4}); } @Test @@ -537,7 +556,8 @@ public void foo(@Named("str") String string, } String requestString = "{\"str\":\"hello\",\"" + TestEndpoint.NAME_STRING + "\":\"" + VALUE_STRING + "\",\"" + TestEndpoint.NAME_INTEGER + "\":" + VALUE_INTEGER - + ",\"integer_array\":[1,2,3]," + "\"integer_collection\":[4,5,6]}"; + + ",\"integer_array\":[1,2,3]," + "\"integer_collection\":[4,5,6], \"stringValue\":" + + "\"321\", \"integerValue\":321}"; Method method = TestMultipleResources.class.getDeclaredMethod("foo", String.class, Integer[].class, Collection.class, Request.class); @@ -559,19 +579,21 @@ public void foo(@Named("str") String string, assertEquals(5, (int) iterator.next()); assertEquals(6, (int) iterator.next()); Request request = (Request) params[3]; - assertEquals(VALUE_STRING, request.getString()); - assertEquals(VALUE_INTEGER, (int) request.getInteger()); + assertEquals("321", request.getStringValue()); + assertEquals(321, (int) request.getIntegerValue()); } @Test public void testJavaxNamed() throws Exception { class Test { @SuppressWarnings("unused") - public void foo(@javax.inject.Named("str") String str, @javax.inject.Named("i") int i) {} + public void foo( + @javax.inject.Named("str") String str, + @Nullable @javax.inject.Named("i") Integer i) {} } String requestString = "{\"str\":\"hello\"}"; - Method method = Test.class.getDeclaredMethod("foo", String.class, int.class); + Method method = Test.class.getDeclaredMethod("foo", String.class, Integer.class); Object[] params = readParameters(requestString, method); assertEquals(2, params.length); @@ -583,7 +605,7 @@ public void foo(@javax.inject.Named("str") String str, @javax.inject.Named("i") public void testCachedNamesAreUsed() throws Exception { class Test { @SuppressWarnings("unused") - public void foo(@Named("foo1") String f1, @Named("foo2") String f2, + public void foo(@Named("foo1") String f1, @Nullable @Named("foo2") String f2, @Named("foo3") String f3) {} } @@ -605,8 +627,10 @@ public void foo(@Named("foo1") String f1, @Named("foo2") String f2, public void testNamesAreCached() throws Exception { class Test { @SuppressWarnings("unused") - public void foo(@Named("foo1") String f1, @Named("foo2") String f2, - @Named("foo3") String f3) {} + public void foo( + @Nullable @Named("foo1") String f1, + @Nullable @Named("foo2") String f2, + @Nullable @Named("foo3") String f3) {} } Method method = Test.class.getDeclaredMethod("foo", String.class, String.class, String.class); @@ -621,6 +645,38 @@ public void foo(@Named("foo1") String f1, @Named("foo2") String f2, assertEquals("foo3", parameterNames.get(2)); } + static class TestUser extends User { + public TestUser(String email) { + super(email); + } + } + + @Test + public void testReadUser() throws Exception { + class TestUserEndpoint { + @SuppressWarnings("unused") + public void user(TestUser user) {} + } + final TestUser user = new TestUser("test"); + Method method = TestUserEndpoint.class.getDeclaredMethod("user", TestUser.class); + ParamReader reader = new ServletRequestParamReader( + EndpointMethod.create(method.getDeclaringClass(), method), endpointsContext, context, null, + null) { + @Override + User getUser() { + return user; + } + + @Override + com.google.appengine.api.users.User getAppEngineUser() { + return APP_ENGINE_USER; + } + }; + Object[] params = readParameters("{}", reader); + assertEquals(1, params.length); + assertEquals(user, params[0]); + } + @Test public void testReadUserIp() throws Exception { class TestUserIp { @@ -733,12 +789,98 @@ public void prettyPrint(@Named("prettyPrint") String prettyPrint) {} assertEquals(true, params[0]); } + @Test + public void testUserInjectionThrowsExceptionIfRequired() throws Exception { + @SuppressWarnings("unused") + class TestUser { + @SuppressWarnings("unused") + public void getUser(User user) { } + } + ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class); + when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED); + methodConfig.setAuthLevel(AuthLevel.REQUIRED); + try { + Method method = TestUser.class.getDeclaredMethod("getUser", User.class); + readParameters( + "{}", EndpointMethod.create(method.getDeclaringClass(), method), + methodConfig, + null, + null); + fail("expected unauthorized method exception"); + } catch (UnauthorizedException ex) { + // expected + } + } + + @Test + public void testAppEngineUserInjectionThrowsExceptionIfRequired() throws Exception { + @SuppressWarnings("unused") + class TestUser { + @SuppressWarnings("unused") + public void getUser(com.google.appengine.api.users.User user) { } + } + ApiMethodConfig methodConfig = Mockito.mock(ApiMethodConfig.class); + when(methodConfig.getAuthLevel()).thenReturn(AuthLevel.REQUIRED); + methodConfig.setAuthLevel(AuthLevel.REQUIRED); + try { + Method method = TestUser.class + .getDeclaredMethod("getUser", com.google.appengine.api.users.User.class); + readParameters( + "{}", + EndpointMethod.create(method.getDeclaringClass(), method), + methodConfig, + null, + null); + fail("expected unauthorized method exception"); + } catch (UnauthorizedException ex) { + // expected + } + } + + @Test + public void testNullValueForRequiredParam() throws Exception { + class TestNullValueForRequiredParam { + @SuppressWarnings("unused") + public void test(@Named("testParam") String testParam) {} + } + try { + Object[] params = + readParameters("{}", + TestNullValueForRequiredParam.class.getDeclaredMethod("test", String.class)); + fail("expected bad request exception"); + } catch (BadRequestException ex) { + // expected + } + } + private Object[] readParameters(String input, Method method) throws Exception { - return readParameters(input, EndpointMethod.create( - method.getDeclaringClass(), method)); + return readParameters(input, EndpointMethod.create(method.getDeclaringClass(), method)); } private Object[] readParameters(final String input, EndpointMethod method) throws Exception { + return readParameters(input, method, null, USER, APP_ENGINE_USER); + } + + private Object[] readParameters(final String input, EndpointMethod method, + ApiMethodConfig methodConfig, final User user, + final com.google.appengine.api.users.User appEngineUser) + throws Exception { + ParamReader reader = new ServletRequestParamReader(method, endpointsContext, context, null, + methodConfig) { + @Override + User getUser() { + return user; + } + @Override + com.google.appengine.api.users.User getAppEngineUser() { + return appEngineUser; + } + }; + return readParameters(input, reader); + } + + private Object[] readParameters(final String input, ParamReader reader) + throws Exception { ServletInputStream servletInputStream = new ServletInputStream() { private final InputStream inputStream = @@ -750,17 +892,6 @@ public int read() throws IOException { } }; when(request.getInputStream()).thenReturn(servletInputStream); - - ParamReader reader = new ServletRequestParamReader(method, request, context, null) { - @Override - User getUser() { - return USER; - } - @Override - com.google.appengine.api.users.User getAppEngineUser() { - return APP_ENGINE_USER; - } - }; return reader.read(); } diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/response/RestResponseResultWriterTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/response/RestResponseResultWriterTest.java index 045c1c0e..f6cf2b1a 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/response/RestResponseResultWriterTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/response/RestResponseResultWriterTest.java @@ -47,7 +47,8 @@ public void writeError_401() throws Exception { @Test public void writeError_402() throws Exception { doWriteErrorTest(402 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "paymentRequired" /* reason */); + "unsupportedProtocol" /* compatReason */, "paymentRequired" /* reason */, + "error" /* message */); } @Test @@ -68,19 +69,21 @@ public void writeError_405() throws Exception { @Test public void writeError_406() throws Exception { doWriteErrorTest(406 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "notAcceptable" /* reason */); + "unsupportedProtocol" /* compatReason */, "notAcceptable" /* reason */, + "error" /* message */); } @Test public void writeError_407() throws Exception { doWriteErrorTest(407 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "proxyAuthentication" /* reason */); + "unsupportedProtocol" /* compatReason */, "proxyAuthentication" /* reason */, + "error" /* message */); } @Test public void writeError_408() throws Exception { doWriteErrorTest(408 /* exceptionCode */, 503 /* expectedCompatCode */, - "backendError" /* compatReason */, "requestTimeout" /* reason */); + "backendError" /* compatReason */, "requestTimeout" /* reason */, "error" /* message */); } @Test @@ -96,7 +99,8 @@ public void writeError_410() throws Exception { @Test public void writeError_411() throws Exception { doWriteErrorTest(411 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "lengthRequired" /* reason */); + "unsupportedProtocol" /* compatReason */, "lengthRequired" /* reason */, + "error" /* message */); } @Test @@ -112,25 +116,25 @@ public void writeError_413() throws Exception { @Test public void writeError_414() throws Exception { doWriteErrorTest(414 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "uriTooLong" /* reason */); + "unsupportedProtocol" /* compatReason */, "uriTooLong" /* reason */, "error" /* message */); } @Test public void writeError_415() throws Exception { doWriteErrorTest(415 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "unsupportedMediaType"); + "unsupportedProtocol" /* compatReason */, "unsupportedMediaType", "error" /* message */); } @Test public void writeError_416() throws Exception { doWriteErrorTest(416 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "rangeNotSatisfiable"); + "unsupportedProtocol" /* compatReason */, "rangeNotSatisfiable", "error" /* message */); } @Test public void writeError_417() throws Exception { doWriteErrorTest(417 /* exceptionCode */, 404 /* expectedCompatCode */, - "unsupportedProtocol" /* compatReason */, "expectationFailed"); + "unsupportedProtocol" /* compatReason */, "expectationFailed", "error" /* message */); } @Test @@ -141,13 +145,19 @@ public void writeError_500s() throws Exception { } } + @Test + public void writeError_nullMessage() throws Exception { + doWriteErrorTest(500 /* exceptionCode */, 503 /* expectedCompatCode */, + "backendError" /* compatReason */, "backendError" /* reason */, null); + } + /** * Tests that an error is translated according to Lily if specified, and the code is left alone * if compatibility mode is off. Both cases test for the correct error structure in the response. */ private void doWriteErrorTest(int exceptionCode, int expectedCompatCode, String reason) throws Exception { - doWriteErrorTest(exceptionCode, expectedCompatCode, reason, reason); + doWriteErrorTest(exceptionCode, expectedCompatCode, reason, reason, "error"); } /** @@ -155,26 +165,35 @@ private void doWriteErrorTest(int exceptionCode, int expectedCompatCode, String * if compatibility mode is off. Both cases test for the correct error structure in the response. */ private void doWriteErrorTest(int exceptionCode, int expectedCompatCode, String compatReason, - String reason) throws Exception { - writeError(exceptionCode, expectedCompatCode, compatReason, true); - writeError(exceptionCode, exceptionCode, reason, false); + String reason, String message) throws Exception { + writeError(exceptionCode, expectedCompatCode, compatReason, message, true); + writeError(exceptionCode, exceptionCode, reason, message, false); } - private void writeError(int exceptionCode, int expectedCode, String reason, + private void writeError(int exceptionCode, int expectedCode, String reason, String message, boolean enableExceptionCompatibility) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); RestResponseResultWriter writer = new RestResponseResultWriter( - response, null, true /* prettyPrint */, enableExceptionCompatibility); - writer.writeError(new ServiceException(exceptionCode, "error")); + response, null, true /* prettyPrint */, + true /* addContentLength */, enableExceptionCompatibility); + writer.writeError(new ServiceException(exceptionCode, message)); ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); ObjectNode content = mapper.readValue(response.getContentAsString(), ObjectNode.class); JsonNode outerError = content.path("error"); assertThat(outerError.path("code").asInt()).isEqualTo(expectedCode); - assertThat(outerError.path("message").asText()).isEqualTo("error"); + if (message == null) { + assertThat(outerError.path("message").isNull()).isTrue(); + } else { + assertThat(outerError.path("message").asText()).isEqualTo(message); + } JsonNode innerError = outerError.path("errors").path(0); assertThat(innerError.path("domain").asText()).isEqualTo("global"); assertThat(innerError.path("reason").asText()).isEqualTo(reason); - assertThat(innerError.path("message").asText()).isEqualTo("error"); + if (message == null) { + assertThat(innerError.path("message").isNull()).isTrue(); + } else { + assertThat(innerError.path("message").asText()).isEqualTo(message); + } } @Test @@ -191,7 +210,8 @@ private void writeError(boolean enableExceptionCompatibility, String customReaso String expectedReason, String customDomain, String expectedDomain) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); RestResponseResultWriter writer = new RestResponseResultWriter( - response, null, true /* prettyPrint */, enableExceptionCompatibility); + response, null, true /* prettyPrint */, + true /* addContentLength */, enableExceptionCompatibility); writer.writeError(new ServiceException(400, "error", customReason, customDomain)); ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper(); ObjectNode content = mapper.readValue(response.getContentAsString(), ObjectNode.class); diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/response/ServletResponseResultWriterTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/response/ServletResponseResultWriterTest.java index 6963bb3e..7762fdde 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/response/ServletResponseResultWriterTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/response/ServletResponseResultWriterTest.java @@ -172,7 +172,7 @@ public void testWriteErrorResponseHeaders() throws Exception { public void testPrettyPrint() throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); ServletResponseResultWriter writer = new ServletResponseResultWriter(response, null, - true /* prettyPrint */); + true /* prettyPrint */, true /* addContentLength */); writer.write(ImmutableMap.of("one", "two", "three", "four")); // If the response is pretty printed, there should be at least two newlines. String body = response.getContentAsString(); diff --git a/endpoints-framework/src/test/java/com/google/api/server/spi/swagger/SwaggerGeneratorTest.java b/endpoints-framework/src/test/java/com/google/api/server/spi/swagger/SwaggerGeneratorTest.java index e7ae3298..471ba6ea 100644 --- a/endpoints-framework/src/test/java/com/google/api/server/spi/swagger/SwaggerGeneratorTest.java +++ b/endpoints-framework/src/test/java/com/google/api/server/spi/swagger/SwaggerGeneratorTest.java @@ -15,6 +15,9 @@ */ package com.google.api.server.spi.swagger; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES; +import static com.google.api.server.spi.config.model.EndpointsFlag.MAP_SCHEMA_SUPPORT_ARRAYS_VALUES; import static com.google.common.truth.Truth.assertThat; import com.google.api.server.spi.Constant; @@ -30,21 +33,41 @@ import com.google.api.server.spi.config.annotationreader.ApiConfigAnnotationReader; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.swagger.SwaggerGenerator.SwaggerContext; +import com.google.api.server.spi.testing.AbsoluteCommonPathEndpoint; +import com.google.api.server.spi.testing.AbsolutePathEndpoint; import com.google.api.server.spi.testing.ArrayEndpoint; import com.google.api.server.spi.testing.EnumEndpoint; +import com.google.api.server.spi.testing.FooDescriptionEndpoint; import com.google.api.server.spi.testing.FooEndpoint; +import com.google.api.server.spi.testing.LimitMetricsEndpoint; +import com.google.api.server.spi.testing.MapEndpoint; +import com.google.api.server.spi.testing.MapEndpointInvalid; +import com.google.api.server.spi.testing.MultiResourceEndpoint.NoResourceEndpoint; +import com.google.api.server.spi.testing.MultiResourceEndpoint.Resource1Endpoint; +import com.google.api.server.spi.testing.MultiResourceEndpoint.Resource2Endpoint; +import com.google.api.server.spi.testing.MultiVersionEndpoint.Version1Endpoint; +import com.google.api.server.spi.testing.MultiVersionEndpoint.Version2Endpoint; +import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Multimap; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import io.swagger.models.HttpMethod; +import io.swagger.models.Operation; +import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.util.Json; +import java.util.Collection; +import java.util.Map.Entry; + /** * Tests for {@link SwaggerGenerator}. */ @@ -70,7 +93,7 @@ public void testWriteSwagger_FooEndpoint() throws Exception { ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), FooEndpoint.class); Swagger swagger = generator.writeSwagger(ImmutableList.of(config), false, context); Swagger expected = readExpectedAsSwagger("foo_endpoint.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test @@ -78,7 +101,7 @@ public void testWriteSwagger_FooEndpointDefaultContext() throws Exception { ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), FooEndpoint.class); Swagger swagger = generator.writeSwagger(ImmutableList.of(config), false, new SwaggerContext()); Swagger expected = readExpectedAsSwagger("foo_endpoint_default_context.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test @@ -86,21 +109,72 @@ public void testWriteSwagger_FooEndpointLocalhost() throws Exception { Swagger swagger = getSwagger( FooEndpoint.class, new SwaggerContext().setApiRoot("http://localhost:8080/api"), false); Swagger expected = readExpectedAsSwagger("foo_endpoint_localhost.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test public void testWriteSwagger_EnumEndpoint() throws Exception { Swagger swagger = getSwagger(EnumEndpoint.class, new SwaggerContext(), true); Swagger expected = readExpectedAsSwagger("enum_endpoint.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test public void testWriteSwagger_ArrayEndpoint() throws Exception { Swagger swagger = getSwagger(ArrayEndpoint.class, new SwaggerContext(), true); Swagger expected = readExpectedAsSwagger("array_endpoint.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_MapEndpoint() throws Exception { + Swagger swagger = getSwagger(MapEndpoint.class, new SwaggerContext(), true); + Swagger expected = readExpectedAsSwagger("map_endpoint.swagger"); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_MapEndpoint_Legacy() throws Exception { + System.setProperty(MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.systemPropertyName, ""); + try { + Swagger swagger = getSwagger(MapEndpoint.class, new SwaggerContext(), true); + Swagger expected = readExpectedAsSwagger("map_endpoint_legacy.swagger"); + checkSwagger(expected, swagger); + } finally { + System.clearProperty(MAP_SCHEMA_FORCE_JSON_MAP_SCHEMA.systemPropertyName); + } + } + + @Test + public void testWriteDiscovery_MapEndpoint_InvalidKeyType() throws Exception { + try { + getSwagger(MapEndpointInvalid.class, new SwaggerContext(), true); + Assert.fail("Should have failed to generate schema for invalid key type"); + } catch (IllegalArgumentException e) { + //expected + } + } + + @Test + public void testWriteDiscovery_MapEndpoint_InvalidKeyType_ignore() throws Exception { + System.setProperty(MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.systemPropertyName, "true"); + try { + getSwagger(MapEndpointInvalid.class, new SwaggerContext(), true); + } finally { + System.clearProperty(MAP_SCHEMA_IGNORE_UNSUPPORTED_KEY_TYPES.systemPropertyName); + } + } + + @Test + public void testWriteSwagger_MapEndpoint_WithArrayValue() throws Exception { + System.setProperty(MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.systemPropertyName, "TRUE"); + try { + Swagger swagger = getSwagger(MapEndpoint.class, new SwaggerContext(), true); + Swagger expected = readExpectedAsSwagger("map_endpoint_with_array.swagger"); + checkSwagger(expected, swagger); + } finally { + System.clearProperty(MAP_SCHEMA_SUPPORT_ARRAYS_VALUES.systemPropertyName); + } } @Test @@ -108,7 +182,7 @@ public void testWriteSwagger_FooEndpoint_internal() throws Exception { ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), FooEndpoint.class); Swagger swagger = generator.writeSwagger(ImmutableList.of(config), true, context); Swagger expected = readExpectedAsSwagger("foo_endpoint_internal.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test @@ -117,7 +191,7 @@ public void testWriteSwagger_ThirdPartyAuthEndpoint() throws Exception { configLoader.loadConfiguration(ServiceContext.create(), ThirdPartyAuthEndpoint.class); Swagger swagger = generator.writeSwagger(ImmutableList.of(config), true, context); Swagger expected = readExpectedAsSwagger("third_party_auth.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test @@ -126,7 +200,7 @@ public void testWriteSwagger_GoogleAuthEndpoint() throws Exception { configLoader.loadConfiguration(ServiceContext.create(), GoogleAuthEndpoint.class); Swagger swagger = generator.writeSwagger(ImmutableList.of(config), true, context); Swagger expected = readExpectedAsSwagger("google_auth.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); } @Test @@ -135,7 +209,59 @@ public void testWriteSwagger_ApiKeys() throws Exception { configLoader.loadConfiguration(ServiceContext.create(), ApiKeysEndpoint.class); Swagger swagger = generator.writeSwagger(ImmutableList.of(config), true, context); Swagger expected = readExpectedAsSwagger("api_keys.swagger"); - compareSwagger(expected, swagger); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_AbsolutePathEndpoint() throws Exception { + Swagger swagger = getSwagger(AbsolutePathEndpoint.class, new SwaggerContext(), true); + Swagger expected = readExpectedAsSwagger("absolute_path_endpoint.swagger"); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_AbsoluteCommonPathEndpoint() throws Exception { + Swagger swagger = getSwagger(AbsoluteCommonPathEndpoint.class, new SwaggerContext(), true); + Swagger expected = readExpectedAsSwagger("absolute_common_path_endpoint.swagger"); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_LimitMetricsEndpoint() throws Exception { + Swagger swagger = getSwagger(LimitMetricsEndpoint.class, new SwaggerContext(), true); + Swagger expected = readExpectedAsSwagger("limit_metrics_endpoint.swagger"); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_FooEndpointWithDescription() throws Exception { + ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), FooDescriptionEndpoint.class); + Swagger swagger = generator.writeSwagger(ImmutableList.of(config), false, context); + Swagger expected = readExpectedAsSwagger("foo_with_description_endpoint.swagger"); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_MultiResourceEndpoint() throws Exception { + ServiceContext serviceContext = ServiceContext.create(); + ImmutableList configs = ImmutableList.of( + configLoader.loadConfiguration(serviceContext, NoResourceEndpoint.class), + configLoader.loadConfiguration(serviceContext, Resource1Endpoint.class), + configLoader.loadConfiguration(serviceContext, Resource2Endpoint.class)); + Swagger swagger = generator.writeSwagger(configs, false, context); + Swagger expected = readExpectedAsSwagger("multi_resource_endpoint.swagger"); + checkSwagger(expected, swagger); + } + + @Test + public void testWriteSwagger_MultiVersionEndpoint() throws Exception { + ServiceContext serviceContext = ServiceContext.create(); + ImmutableList configs = ImmutableList.of( + configLoader.loadConfiguration(serviceContext, Version1Endpoint.class), + configLoader.loadConfiguration(serviceContext, Version2Endpoint.class)); + Swagger swagger = generator.writeSwagger(configs, false, context); + Swagger expected = readExpectedAsSwagger("multi_version_endpoint.swagger"); + checkSwagger(expected, swagger); } private Swagger getSwagger(Class serviceClass, SwaggerContext context, boolean internal) @@ -149,10 +275,51 @@ private Swagger readExpectedAsSwagger(String file) throws Exception { return mapper.readValue(expectedString, Swagger.class); } + private void checkSwagger(Swagger expected, Swagger actual) throws Exception { + compareSwagger(expected, actual); + // operationIds should be unique to be deployed on Endpoints Management + checkDuplicateOperations(actual); + // Jackson preserves order when deserializing expected result, and SwaggerGenerator should + // always output resource and security definitions in the same order + checkOrdering(expected, actual); + } + private void compareSwagger(Swagger expected, Swagger actual) throws Exception { System.out.println("Actual: " + mapper.writeValueAsString(actual)); System.out.println("Expected: " + mapper.writeValueAsString(expected)); assertThat(actual).isEqualTo(expected); + // TODO: Remove once Swagger models check this in equals + assertThat(actual.getVendorExtensions()).isEqualTo(expected.getVendorExtensions()); + } + + private void checkDuplicateOperations(Swagger actual) { + Multimap operationIds = HashMultimap.create(); + for (Entry pathEntry : actual.getPaths().entrySet()) { + for (Entry opEntry : pathEntry.getValue().getOperationMap() + .entrySet()) { + operationIds + .put(opEntry.getValue().getOperationId(), pathEntry.getKey() + "|" + opEntry.getKey()); + } + } + int duplicateOperationIdCount = 0; + for (Entry> entry : operationIds.asMap().entrySet()) { + if (entry.getValue().size() > 1) { + System.out.println("Duplicate operation id: " + entry); + duplicateOperationIdCount++; + } + } + assertThat(duplicateOperationIdCount).named("Duplicate operation ids").isEqualTo(0); + } + + private void checkOrdering(Swagger expected, Swagger actual) { + if (expected.getSecurityDefinitions() != null && actual.getSecurityDefinitions() != null) { + assertThat(ImmutableList.of(expected.getSecurityDefinitions().keySet())) + .isEqualTo(ImmutableList.of(actual.getSecurityDefinitions().keySet())); + } + if (expected.getDefinitions() != null && actual.getDefinitions() != null) { + assertThat(ImmutableList.of(expected.getDefinitions().keySet())) + .isEqualTo(ImmutableList.of(actual.getDefinitions().keySet())); + } } @Api(name = "thirdparty", version = "v1", @@ -185,6 +352,10 @@ public void googleAuth() { } } @Api(name = "apikeys", version = "v1", + issuers = { + @ApiIssuer(name = "auth0", issuer = "https://test.auth0.com/authorize", + jwksUri = "https://test.auth0.com/.wellknown/jwks.json") + }, apiKeyRequired = AnnotationBoolean.TRUE) private static class ApiKeysEndpoint { @ApiMethod(apiKeyRequired = AnnotationBoolean.FALSE) @@ -192,5 +363,11 @@ public void overrideApiKeySetting() { } @ApiMethod public void inheritApiKeySetting() { } + + @ApiMethod( + issuerAudiences = { + @ApiIssuerAudience(name = "auth0", audiences = "auth0audmethod") + }) + public void apiKeyWithAuth() { } } } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/absolute_common_path_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/absolute_common_path_endpoint.json new file mode 100644 index 00000000..857a23e6 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/absolute_common_path_endpoint.json @@ -0,0 +1,108 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/api/absolutepath/v1/", + "baseUrl": "https://discovery-test.appspot.com/api/absolutepath/v1/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "absolutepath:v1", + "kind": "discovery#restDescription", + "methods": { + "absolutepath": { + "httpMethod": "POST", + "id": "absolutepath.absolutepath", + "path": "absolutepathmethod", + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "create": { + "httpMethod": "POST", + "id": "absolutepath.create", + "path": "create", + "response": { + "$ref": "Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + }, + "name": "absolutepath", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "rootUrl": "https://discovery-test.appspot.com/api/", + "schemas": { + "Foo": { + "id": "Foo", + "properties": { + "name": { + "type": "string" + }, + "value": { + "format": "int32", + "type": "integer" + } + }, + "type": "object" + } + }, + "servicePath": "absolutepath/v1/", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/absolute_path_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/absolute_path_endpoint.json new file mode 100644 index 00000000..a0a41bf1 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/absolute_path_endpoint.json @@ -0,0 +1,116 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/api/", + "baseUrl": "https://discovery-test.appspot.com/api/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "absolutepath:v1", + "kind": "discovery#restDescription", + "methods": { + "absolutepath": { + "httpMethod": "POST", + "id": "absolutepath.absolutepath", + "path": "absolutepathmethod/v1", + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "absolutepath2": { + "httpMethod": "POST", + "id": "absolutepath.absolutepath2", + "path": "absolutepathmethod2/v1", + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "create": { + "httpMethod": "POST", + "id": "absolutepath.create", + "path": "absolutepath/v1/create", + "response": { + "$ref": "Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + }, + "name": "absolutepath", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "rootUrl": "https://discovery-test.appspot.com/api/", + "schemas": { + "Foo": { + "id": "Foo", + "properties": { + "name": { + "type": "string" + }, + "value": { + "format": "int32", + "type": "integer" + } + }, + "type": "object" + } + }, + "servicePath": "", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/array_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/array_endpoint.json index 080226f3..da404334 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/array_endpoint.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/array_endpoint.json @@ -1,96 +1,242 @@ { - "kind": "discovery#restDescription", - "discoveryVersion": "v1", - "id": "myapi:v1", - "name": "myapi", - "version": "v1", - "description": "This is an API", - "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } }, - "protocol": "rest", - "baseUrl": "https://myapi.appspot.com/_ah/api/myapi/v1/", "basePath": "/_ah/api/myapi/v1/", - "rootUrl": "https://myapi.appspot.com/_ah/api/", - "servicePath": "myapi/v1/", + "baseUrl": "https://myapi.appspot.com/_ah/api/myapi/v1/", "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "myapi:v1", + "kind": "discovery#restDescription", + "name": "myapi", "parameters": { "alt": { - "type": "string", - "description": "Data format for the response.", "default": "json", + "description": "Data format for the response.", "enum": [ "json" ], "enumDescriptions": [ "Responses with Content-Type of application/json" ], - "location": "query" + "location": "query", + "type": "string" }, "fields": { - "type": "string", "description": "Selector specifying which fields to include in a partial response.", - "location": "query" + "location": "query", + "type": "string" }, "key": { - "type": "string", "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", - "location": "query" + "location": "query", + "type": "string" }, "oauth_token": { - "type": "string", "description": "OAuth 2.0 token for the current user.", - "location": "query" + "location": "query", + "type": "string" }, "prettyPrint": { - "type": "boolean", - "description": "Returns response with indentations and line breaks.", "default": "true", - "location": "query" + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" }, "quotaUser": { - "type": "string", "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", - "location": "query" + "location": "query", + "type": "string" }, "userIp": { - "type": "string", "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", - "location": "query" + "location": "query", + "type": "string" } }, - "auth": { - "oauth2": { - "scopes": { - "https://www.googleapis.com/auth/userinfo.email": { - "description": "View your email address" + "protocol": "rest", + "resources": { + "arrayEndpoint": { + "methods": { + "getAllArrayedFoos": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getAllArrayedFoos", + "path": "foocollectioncollection", + "response": { + "$ref": "FooCollectionCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getAllFoos": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getAllFoos", + "path": "getAllFoos", + "response": { + "$ref": "FooCollectionCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getAllFoosResponse": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getAllFoosResponse", + "path": "getAllFoosResponse", + "response": { + "$ref": "CollectionResponse_FooCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getAllNestedFoosResponse": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getAllNestedFoosResponse", + "path": "getAllNestedFoosResponse", + "response": { + "$ref": "CollectionResponse_FooCollectionCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getArrayService": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getArrayService", + "path": "arrayendpoint", + "response": { + "$ref": "ArrayEndpoint" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getArrayedFoos": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getArrayedFoos", + "path": "getArrayedFoos", + "response": { + "$ref": "FooCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getBaz": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getBaz", + "path": "baz", + "response": { + "$ref": "Baz" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFoos": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getFoos", + "path": "foocollection", + "response": { + "$ref": "FooCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFoosResponse": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getFoosResponse", + "path": "collectionresponse_foo", + "response": { + "$ref": "CollectionResponse_Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntegers": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getIntegers", + "path": "integercollection", + "response": { + "$ref": "IntegerCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntegersResponse": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getIntegersResponse", + "path": "getIntegersResponse", + "response": { + "$ref": "CollectionResponse_Integer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getListOfString": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getListOfString", + "path": "getListOfString", + "response": { + "$ref": "ListContainer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getObjectIntegers": { + "httpMethod": "GET", + "id": "myapi.arrayEndpoint.getObjectIntegers", + "path": "getObjectIntegers", + "response": { + "$ref": "IntegerCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] } } } }, + "rootUrl": "https://myapi.appspot.com/_ah/api/", "schemas": { "ArrayEndpoint": { "id": "ArrayEndpoint", - "type": "object", "properties": { "allArrayedFoos": { - "type": "array", "items": { - "type": "array", "items": { "$ref": "Foo" - } - } + }, + "type": "array" + }, + "type": "array" }, "allFoos": { - "type": "array", "items": { - "type": "array", "items": { "$ref": "Foo" - } - } + }, + "type": "array" + }, + "type": "array" }, "allFoosResponse": { "$ref": "CollectionResponse_FooCollection" @@ -102,317 +248,197 @@ "$ref": "ArrayEndpoint" }, "arrayedFoos": { - "type": "array", "items": { "$ref": "Foo" - } + }, + "type": "array" }, "baz": { "$ref": "Baz" }, "foos": { - "type": "array", "items": { "$ref": "Foo" - } + }, + "type": "array" }, "foosResponse": { "$ref": "CollectionResponse_Foo" }, "integers": { - "type": "array", "items": { - "type": "integer", - "format": "int32" - } + "format": "int32", + "type": "integer" + }, + "type": "array" }, "integersResponse": { "$ref": "CollectionResponse_Integer" }, + "listOfString": { + "$ref": "ListContainer" + }, "objectIntegers": { - "type": "array", "items": { - "type": "integer", - "format": "int32" - } + "format": "int32", + "type": "integer" + }, + "type": "array" } - } + }, + "type": "object" }, "Baz": { "id": "Baz", - "type": "object", "properties": { "foo": { "$ref": "Foo" }, "foos": { - "type": "array", "items": { "$ref": "Foo" - } + }, + "type": "array" } - } + }, + "type": "object" }, "CollectionResponse_Foo": { "id": "CollectionResponse_Foo", - "type": "object", "properties": { "items": { - "type": "array", "items": { "$ref": "Foo" - } + }, + "type": "array" }, "nextPageToken": { "type": "string" } - } + }, + "type": "object" }, "CollectionResponse_FooCollection": { "id": "CollectionResponse_FooCollection", - "type": "object", "properties": { "items": { - "type": "array", "items": { - "type": "array", "items": { "$ref": "Foo" - } - } + }, + "type": "array" + }, + "type": "array" }, "nextPageToken": { "type": "string" } - } + }, + "type": "object" }, "CollectionResponse_FooCollectionCollection": { "id": "CollectionResponse_FooCollectionCollection", - "type": "object", "properties": { "items": { - "type": "array", "items": { - "type": "array", "items": { - "type": "array", "items": { "$ref": "Foo" - } - } - } + }, + "type": "array" + }, + "type": "array" + }, + "type": "array" }, "nextPageToken": { "type": "string" } - } + }, + "type": "object" }, "CollectionResponse_Integer": { "id": "CollectionResponse_Integer", - "type": "object", "properties": { "items": { - "type": "array", "items": { - "type": "integer", - "format": "int32" - } + "format": "int32", + "type": "integer" + }, + "type": "array" }, "nextPageToken": { "type": "string" } - } + }, + "type": "object" }, "Foo": { "id": "Foo", - "type": "object", "properties": { "name": { "type": "string" }, "value": { - "type": "integer", - "format": "int32" + "format": "int32", + "type": "integer" } - } + }, + "type": "object" }, "FooCollection": { "id": "FooCollection", - "type": "object", "properties": { "items": { - "type": "array", "items": { "$ref": "Foo" - } + }, + "type": "array" } - } + }, + "type": "object" }, "FooCollectionCollection": { "id": "FooCollectionCollection", - "type": "object", "properties": { "items": { - "type": "array", "items": { - "type": "array", "items": { "$ref": "Foo" - } - } + }, + "type": "array" + }, + "type": "array" } - } + }, + "type": "object" }, "IntegerCollection": { "id": "IntegerCollection", - "type": "object", "properties": { "items": { - "type": "array", "items": { - "type": "integer", - "format": "int32" - } - } - } - } - }, - "resources": { - "arrayEndpoint": { - "methods": { - "getAllArrayedFoos": { - "id": "myapi.arrayEndpoint.getAllArrayedFoos", - "path": "foocollectioncollection", - "httpMethod": "GET", - "response": { - "$ref": "FooCollectionCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getAllFoos": { - "id": "myapi.arrayEndpoint.getAllFoos", - "path": "getAllFoos", - "httpMethod": "GET", - "response": { - "$ref": "FooCollectionCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getAllFoosResponse": { - "id": "myapi.arrayEndpoint.getAllFoosResponse", - "path": "getAllFoosResponse", - "httpMethod": "GET", - "response": { - "$ref": "CollectionResponse_FooCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getAllNestedFoosResponse": { - "id": "myapi.arrayEndpoint.getAllNestedFoosResponse", - "path": "getAllNestedFoosResponse", - "httpMethod": "GET", - "response": { - "$ref": "CollectionResponse_FooCollectionCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getArrayService": { - "id": "myapi.arrayEndpoint.getArrayService", - "path": "arrayendpoint", - "httpMethod": "GET", - "response": { - "$ref": "ArrayEndpoint" + "format": "int32", + "type": "integer" }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getArrayedFoos": { - "id": "myapi.arrayEndpoint.getArrayedFoos", - "path": "getArrayedFoos", - "httpMethod": "GET", - "response": { - "$ref": "FooCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getBaz": { - "id": "myapi.arrayEndpoint.getBaz", - "path": "baz", - "httpMethod": "GET", - "response": { - "$ref": "Baz" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getFoos": { - "id": "myapi.arrayEndpoint.getFoos", - "path": "foocollection", - "httpMethod": "GET", - "response": { - "$ref": "FooCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getFoosResponse": { - "id": "myapi.arrayEndpoint.getFoosResponse", - "path": "collectionresponse_foo", - "httpMethod": "GET", - "response": { - "$ref": "CollectionResponse_Foo" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getIntegers": { - "id": "myapi.arrayEndpoint.getIntegers", - "path": "integercollection", - "httpMethod": "GET", - "response": { - "$ref": "IntegerCollection" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getIntegersResponse": { - "id": "myapi.arrayEndpoint.getIntegersResponse", - "path": "getIntegersResponse", - "httpMethod": "GET", - "response": { - "$ref": "CollectionResponse_Integer" - }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] - }, - "getObjectIntegers": { - "id": "myapi.arrayEndpoint.getObjectIntegers", - "path": "getObjectIntegers", - "httpMethod": "GET", - "response": { - "$ref": "IntegerCollection" + "type": "array" + } + }, + "type": "object" + }, + "ListContainer": { + "id": "ListContainer", + "properties": { + "strings": { + "items": { + "type": "string" }, - "scopes": [ - "https://www.googleapis.com/auth/userinfo.email" - ] + "type": "array" } - } + }, + "type": "object" } - } + }, + "servicePath": "myapi/v1/", + "version": "v1" } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/custom_scopes.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/custom_scopes.json new file mode 100644 index 00000000..4e447ddd --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/custom_scopes.json @@ -0,0 +1,155 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "doesnotexist": { + "description": "doesnotexist" + }, + "email": { + "description": "View your email address" + }, + "https://mail.google.com/": { + "description": "Read, send, delete, and manage your email" + }, + "https://www.googleapis.com/auth/drive": { + "description": "View and manage the files in your Google Drive" + }, + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + }, + "openid": { + "description": "Authenticate using OpenID Connect" + }, + "profile": { + "description": "View your basic profile info" + } + } + } + }, + "basePath": "/api/customScopes/v1/", + "baseUrl": "https://discovery-test.appspot.com/api/customScopes/v1/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "customScopes:v1", + "kind": "discovery#restDescription", + "name": "customScopes", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "customScopesEndpoint": { + "methods": { + "bar": { + "httpMethod": "POST", + "id": "customScopes.customScopesEndpoint.bar", + "path": "bar", + "response": { + "$ref": "Bar" + }, + "scopes": [ + "email" + ] + }, + "complexScopeExpression": { + "httpMethod": "POST", + "id": "customScopes.customScopesEndpoint.complexScopeExpression", + "path": "complexScopeExpression", + "scopes": [ + "email profile", + "https://mail.google.com/" + ] + }, + "foo": { + "httpMethod": "POST", + "id": "customScopes.customScopesEndpoint.foo", + "path": "foo", + "response": { + "$ref": "Foo" + }, + "scopes": [ + "https://mail.google.com/" + ] + } + } + } + }, + "rootUrl": "https://discovery-test.appspot.com/api/", + "schemas": { + "Bar": { + "id": "Bar", + "properties": { + "name": { + "type": "string" + }, + "value": { + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "Foo": { + "id": "Foo", + "properties": { + "name": { + "type": "string" + }, + "value": { + "format": "int32", + "type": "integer" + } + }, + "type": "object" + } + }, + "servicePath": "customScopes/v1/", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/directory.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/directory.json index ec3c10d6..e7a72653 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/directory.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/directory.json @@ -6,8 +6,8 @@ "discoveryLink": "./apis/myapi/v1/rest", "discoveryRestUrl": "https://myapi.appspot.com/_ah/api/discovery/v1/apis/myapi/v1/rest", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "myapi:v1", "kind": "discovery#directoryItem", @@ -20,8 +20,8 @@ "discoveryLink": "./apis/enum/v1/rest", "discoveryRestUrl": "https://myapi.appspot.com/_ah/api/discovery/v1/apis/enum/v1/rest", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "enum:v1", "kind": "discovery#directoryItem", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/enum_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/enum_endpoint.json index 2584c42c..5ef91688 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/enum_endpoint.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/enum_endpoint.json @@ -14,8 +14,8 @@ "description": "This is an API", "discoveryVersion": "v1", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "enum:v1", "kind": "discovery#restDescription", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint.json index 81d979fa..2dcf8c95 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint.json @@ -11,11 +11,13 @@ "basePath": "/api/foo/v1/", "baseUrl": "https://discovery-test.appspot.com/api/foo/v1/", "batchPath": "batch", - "description": "This is an API", + "canonicalName": "CanonicalName", + "description": "Just Foo Things", "discoveryVersion": "v1", + "documentationLink": "https://example.com", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "foo:v1", "kind": "discovery#restDescription", @@ -159,6 +161,9 @@ "description": "list desc", "httpMethod": "GET", "id": "foo.foo.list", + "parameterOrder": [ + "n" + ], "parameters": { "n": { "format": "int32", @@ -237,5 +242,6 @@ } }, "servicePath": "foo/v1/", + "title": "The Foo API", "version": "v1" } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_default_context.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_default_context.json index 0d374afb..f0e64e8d 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_default_context.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_default_context.json @@ -11,11 +11,13 @@ "basePath": "/_ah/api/foo/v1/", "baseUrl": "https://myapi.appspot.com/_ah/api/foo/v1/", "batchPath": "batch", - "description": "This is an API", + "canonicalName": "CanonicalName", + "description": "Just Foo Things", "discoveryVersion": "v1", + "documentationLink": "https://example.com", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "foo:v1", "kind": "discovery#restDescription", @@ -159,6 +161,9 @@ "description": "list desc", "httpMethod": "GET", "id": "foo.foo.list", + "parameterOrder": [ + "n" + ], "parameters": { "n": { "format": "int32", @@ -237,5 +242,6 @@ } }, "servicePath": "foo/v1/", + "title": "The Foo API", "version": "v1" } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_localhost.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_localhost.json index 50150c04..561894ba 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_localhost.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_endpoint_localhost.json @@ -11,11 +11,13 @@ "basePath": "/api/foo/v1/", "baseUrl": "http://localhost:8080/api/foo/v1/", "batchPath": "batch", - "description": "This is an API", + "canonicalName": "CanonicalName", + "description": "Just Foo Things", "discoveryVersion": "v1", + "documentationLink": "https://example.com", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "foo:v1", "kind": "discovery#restDescription", @@ -159,6 +161,9 @@ "description": "list desc", "httpMethod": "GET", "id": "foo.foo.list", + "parameterOrder": [ + "n" + ], "parameters": { "n": { "format": "int32", @@ -237,5 +242,6 @@ } }, "servicePath": "foo/v1/", + "title": "The Foo API", "version": "v1" } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_with_description_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_with_description_endpoint.json new file mode 100644 index 00000000..cf950c36 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/foo_with_description_endpoint.json @@ -0,0 +1,276 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/api/foo/v1/", + "baseUrl": "https://discovery-test.appspot.com/api/foo/v1/", + "batchPath": "batch", + "description": "Just Foo Things", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "foo:v1", + "kind": "discovery#restDescription", + "methods": { + "toplevel": { + "httpMethod": "POST", + "id": "foo.toplevel", + "path": "foos", + "response": { + "$ref": "CollectionResponse_FooDescription" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + }, + "name": "foo", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "foo": { + "methods": { + "create": { + "description": "create desc", + "httpMethod": "PUT", + "id": "foo.foo.create", + "parameterOrder": [ + "id" + ], + "parameters": { + "id": { + "description": "id desc", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "foos/{id}", + "request": { + "$ref": "FooDescription", + "parameterName": "resource" + }, + "response": { + "$ref": "FooDescription" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "delete": { + "description": "delete desc", + "httpMethod": "DELETE", + "id": "foo.foo.delete", + "parameterOrder": [ + "id" + ], + "parameters": { + "id": { + "description": "id desc", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "foos/{id}", + "response": { + "$ref": "FooDescription" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "get": { + "description": "get desc", + "httpMethod": "GET", + "id": "foo.foo.get", + "parameterOrder": [ + "id" + ], + "parameters": { + "id": { + "description": "id desc", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "foos/{id}", + "response": { + "$ref": "FooDescription" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "list": { + "description": "list desc", + "httpMethod": "GET", + "id": "foo.foo.list", + "parameterOrder": [ + "n" + ], + "parameters": { + "n": { + "format": "int32", + "location": "query", + "required": true, + "type": "integer" + }, + "enum": { + "description": "enum desc", + "enum": [ + "VALUE1", + "VALUE2" + ], + "enumDescriptions": [ + "description of value1", + "description of value2" + ], + "location": "query", + "type": "string" + } + }, + "path": "foos", + "response": { + "$ref": "CollectionResponse_FooDescription" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "update": { + "description": "update desc", + "httpMethod": "POST", + "id": "foo.foo.update", + "parameterOrder": [ + "id" + ], + "parameters": { + "id": { + "description": "id desc", + "location": "path", + "required": true, + "type": "string" + } + }, + "path": "foos/{id}", + "request": { + "$ref": "FooDescription", + "parameterName": "resource" + }, + "response": { + "$ref": "FooDescription" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + } + } + }, + "rootUrl": "https://discovery-test.appspot.com/api/", + "schemas": { + "CollectionResponse_FooDescription": { + "id": "CollectionResponse_FooDescription", + "properties": { + "items": { + "items": { + "$ref": "FooDescription" + }, + "type": "array" + }, + "nextPageToken": { + "type": "string" + } + }, + "type": "object" + }, + "FooDescription": { + "id": "FooDescription", + "properties": { + "choice": { + "$ref": "TestEnumDescription", + "description": "description of choice" + }, + "name": { + "description":"description of name", + "type": "string" + }, + "value": { + "description":"description of value", + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "TestEnumDescription": { + "enum": [ + "VALUE1", + "VALUE2" + ], + "enumDescriptions": [ + "description of value1", + "description of value2" + ], + "id": "TestEnumDescription", + "type":"string" + } + }, + "servicePath": "foo/v1/", + "title": "The Foo API", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint.json new file mode 100644 index 00000000..d5795674 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint.json @@ -0,0 +1,473 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/_ah/api/myapi/v1/", + "baseUrl": "https://myapi.appspot.com/_ah/api/myapi/v1/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "myapi:v1", + "kind": "discovery#restDescription", + "name": "myapi", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "mapEndpoint": { + "methods": { + "getBazMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getBazMap", + "path": "map_string_baz", + "response": { + "$ref": "Map_String_Baz" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getBooleanKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getBooleanKeyMap", + "path": "map_boolean_string", + "response": { + "$ref": "Map_Boolean_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getDateKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getDateKeyMap", + "path": "map_datetime_string", + "response": { + "$ref": "Map_DateTime_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getDateTimeKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getDateTimeKeyMap", + "path": "getDateTimeKeyMap", + "response": { + "$ref": "Map_DateTime_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getEnumKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getEnumKeyMap", + "path": "map_testenum_string", + "response": { + "$ref": "Map_TestEnum_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFloatKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFloatKeyMap", + "path": "map_float_string", + "response": { + "$ref": "Map_Float_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFooMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFooMap", + "path": "map_string_foo", + "response": { + "$ref": "Map_String_Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFooMapMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFooMapMap", + "path": "map_string_map_string_foo", + "response": { + "$ref": "Map_String_Map_String_Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getIntKeyMap", + "path": "map_integer_string", + "response": { + "$ref": "Map_Integer_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getIntMap", + "path": "map_string_integer", + "response": { + "$ref": "Map_String_Integer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getLongKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getLongKeyMap", + "path": "map_long_string", + "response": { + "$ref": "Map_Long_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapOfStrings": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapOfStrings", + "path": "getMapOfStrings", + "response": { + "$ref": "MapContainer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapService": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapService", + "path": "mapendpoint", + "response": { + "$ref": "MapEndpoint" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapSubclass": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapSubclass", + "path": "mapsubclass", + "response": { + "$ref": "Map_Boolean_Integer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringArrayMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringArrayMap", + "path": "map_string_stringcollection", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringCollectionMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringCollectionMap", + "path": "getStringCollectionMap", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringMap", + "path": "map_string_string", + "response": { + "$ref": "Map_String_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringValueMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringValueMap", + "path": "map_string_stringvalue", + "response": { + "$ref": "Map_String_StringValue" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + } + } + }, + "rootUrl": "https://myapi.appspot.com/_ah/api/", + "schemas": { + "Baz": { + "id": "Baz", + "properties": { + "foo": { + "$ref": "Foo" + }, + "foos": { + "items": { + "$ref": "Foo" + }, + "type": "array" + } + }, + "type": "object" + }, + "Foo": { + "id": "Foo", + "properties": { + "name": { + "type": "string" + }, + "value": { + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "JsonMap": { + "id": "JsonMap", + "type": "object" + }, + "MapContainer": { + "id": "MapContainer", + "properties": { + "stringMap": { + "$ref": "Map_String_StringValue", + "description": "A map of string values" + } + }, + "type": "object" + }, + "MapEndpoint": { + "id": "MapEndpoint", + "properties": { + "bazMap": { + "$ref": "Map_String_Baz" + }, + "booleanKeyMap": { + "$ref": "Map_Boolean_String" + }, + "dateKeyMap": { + "$ref": "Map_DateTime_String" + }, + "dateTimeKeyMap": { + "$ref": "Map_DateTime_String" + }, + "enumKeyMap": { + "$ref": "Map_TestEnum_String" + }, + "floatKeyMap": { + "$ref": "Map_Float_String" + }, + "fooMap": { + "$ref": "Map_String_Foo" + }, + "fooMapMap": { + "$ref": "Map_String_Map_String_Foo" + }, + "intKeyMap": { + "$ref": "Map_Integer_String" + }, + "intMap": { + "$ref": "Map_String_Integer" + }, + "longKeyMap": { + "$ref": "Map_Long_String" + }, + "mapOfStrings": { + "$ref": "MapContainer" + }, + "mapService": { + "$ref": "MapEndpoint" + }, + "mapSubclass": { + "$ref": "Map_Boolean_Integer" + }, + "stringArrayMap": { + "$ref": "JsonMap" + }, + "stringCollectionMap": { + "$ref": "JsonMap" + }, + "stringMap": { + "$ref": "Map_String_String" + }, + "stringValueMap": { + "$ref": "Map_String_StringValue" + } + }, + "type": "object" + }, + "Map_Boolean_Integer": { + "additionalProperties": { + "format": "int32", + "type": "integer" + }, + "id": "Map_Boolean_Integer", + "type": "object" + }, + "Map_Boolean_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Boolean_String", + "type": "object" + }, + "Map_DateTime_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_DateTime_String", + "type": "object" + }, + "Map_Float_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Float_String", + "type": "object" + }, + "Map_Integer_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Integer_String", + "type": "object" + }, + "Map_Long_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Long_String", + "type": "object" + }, + "Map_String_Baz": { + "additionalProperties": { + "$ref": "Baz" + }, + "id": "Map_String_Baz", + "type": "object" + }, + "Map_String_Foo": { + "additionalProperties": { + "$ref": "Foo" + }, + "id": "Map_String_Foo", + "type": "object" + }, + "Map_String_Integer": { + "additionalProperties": { + "format": "int32", + "type": "integer" + }, + "id": "Map_String_Integer", + "type": "object" + }, + "Map_String_Map_String_Foo": { + "additionalProperties": { + "$ref": "Map_String_Foo" + }, + "id": "Map_String_Map_String_Foo", + "type": "object" + }, + "Map_String_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_String_String", + "type": "object" + }, + "Map_String_StringValue": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_String_StringValue", + "type": "object" + }, + "Map_TestEnum_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_TestEnum_String", + "type": "object" + } + }, + "servicePath": "myapi/v1/", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint_legacy.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint_legacy.json new file mode 100644 index 00000000..e7289276 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint_legacy.json @@ -0,0 +1,352 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/_ah/api/myapi/v1/", + "baseUrl": "https://myapi.appspot.com/_ah/api/myapi/v1/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "myapi:v1", + "kind": "discovery#restDescription", + "name": "myapi", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "mapEndpoint": { + "methods": { + "getBazMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getBazMap", + "path": "map_string_baz", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getBooleanKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getBooleanKeyMap", + "path": "map_boolean_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getDateKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getDateKeyMap", + "path": "map_datetime_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getDateTimeKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getDateTimeKeyMap", + "path": "getDateTimeKeyMap", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getEnumKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getEnumKeyMap", + "path": "map_testenum_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFloatKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFloatKeyMap", + "path": "map_float_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFooMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFooMap", + "path": "map_string_foo", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFooMapMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFooMapMap", + "path": "map_string_map_string_foo", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getIntKeyMap", + "path": "map_integer_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getIntMap", + "path": "map_string_integer", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getLongKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getLongKeyMap", + "path": "map_long_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapOfStrings": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapOfStrings", + "path": "getMapOfStrings", + "response": { + "$ref": "MapContainer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapService": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapService", + "path": "mapendpoint", + "response": { + "$ref": "MapEndpoint" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapSubclass": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapSubclass", + "path": "mapsubclass", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringArrayMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringArrayMap", + "path": "map_string_stringcollection", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringCollectionMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringCollectionMap", + "path": "getStringCollectionMap", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringMap", + "path": "map_string_string", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringValueMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringValueMap", + "path": "map_string_stringvalue", + "response": { + "$ref": "JsonMap" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + } + } + }, + "rootUrl": "https://myapi.appspot.com/_ah/api/", + "schemas": { + "JsonMap": { + "id": "JsonMap", + "type": "object" + }, + "MapContainer": { + "id": "MapContainer", + "properties": { + "stringMap": { + "$ref": "JsonMap", + "description": "A map of string values" + } + }, + "type": "object" + }, + "MapEndpoint": { + "id": "MapEndpoint", + "properties": { + "bazMap": { + "$ref": "JsonMap" + }, + "booleanKeyMap": { + "$ref": "JsonMap" + }, + "dateKeyMap": { + "$ref": "JsonMap" + }, + "dateTimeKeyMap": { + "$ref": "JsonMap" + }, + "enumKeyMap": { + "$ref": "JsonMap" + }, + "floatKeyMap": { + "$ref": "JsonMap" + }, + "fooMap": { + "$ref": "JsonMap" + }, + "fooMapMap": { + "$ref": "JsonMap" + }, + "intKeyMap": { + "$ref": "JsonMap" + }, + "intMap": { + "$ref": "JsonMap" + }, + "longKeyMap": { + "$ref": "JsonMap" + }, + "mapOfStrings": { + "$ref": "MapContainer" + }, + "mapService": { + "$ref": "MapEndpoint" + }, + "mapSubclass": { + "$ref": "JsonMap" + }, + "stringArrayMap": { + "$ref": "JsonMap" + }, + "stringCollectionMap": { + "$ref": "JsonMap" + }, + "stringMap": { + "$ref": "JsonMap" + }, + "stringValueMap": { + "$ref": "JsonMap" + } + }, + "type": "object" + } + }, + "servicePath": "myapi/v1/", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint_with_array.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint_with_array.json new file mode 100644 index 00000000..9faa3ed1 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/map_endpoint_with_array.json @@ -0,0 +1,479 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/_ah/api/myapi/v1/", + "baseUrl": "https://myapi.appspot.com/_ah/api/myapi/v1/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "myapi:v1", + "kind": "discovery#restDescription", + "name": "myapi", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "mapEndpoint": { + "methods": { + "getBazMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getBazMap", + "path": "map_string_baz", + "response": { + "$ref": "Map_String_Baz" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getBooleanKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getBooleanKeyMap", + "path": "map_boolean_string", + "response": { + "$ref": "Map_Boolean_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getDateKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getDateKeyMap", + "path": "map_datetime_string", + "response": { + "$ref": "Map_DateTime_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getDateTimeKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getDateTimeKeyMap", + "path": "getDateTimeKeyMap", + "response": { + "$ref": "Map_DateTime_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getEnumKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getEnumKeyMap", + "path": "map_testenum_string", + "response": { + "$ref": "Map_TestEnum_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFloatKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFloatKeyMap", + "path": "map_float_string", + "response": { + "$ref": "Map_Float_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFooMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFooMap", + "path": "map_string_foo", + "response": { + "$ref": "Map_String_Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getFooMapMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getFooMapMap", + "path": "map_string_map_string_foo", + "response": { + "$ref": "Map_String_Map_String_Foo" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getIntKeyMap", + "path": "map_integer_string", + "response": { + "$ref": "Map_Integer_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getIntMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getIntMap", + "path": "map_string_integer", + "response": { + "$ref": "Map_String_Integer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getLongKeyMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getLongKeyMap", + "path": "map_long_string", + "response": { + "$ref": "Map_Long_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapOfStrings": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapOfStrings", + "path": "getMapOfStrings", + "response": { + "$ref": "MapContainer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapService": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapService", + "path": "mapendpoint", + "response": { + "$ref": "MapEndpoint" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getMapSubclass": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getMapSubclass", + "path": "mapsubclass", + "response": { + "$ref": "Map_Boolean_Integer" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringArrayMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringArrayMap", + "path": "map_string_stringcollection", + "response": { + "$ref": "Map_String_StringCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringCollectionMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringCollectionMap", + "path": "getStringCollectionMap", + "response": { + "$ref": "Map_String_StringCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringMap", + "path": "map_string_string", + "response": { + "$ref": "Map_String_String" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getStringValueMap": { + "httpMethod": "GET", + "id": "myapi.mapEndpoint.getStringValueMap", + "path": "map_string_stringvalue", + "response": { + "$ref": "Map_String_StringValue" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + } + } + }, + "rootUrl": "https://myapi.appspot.com/_ah/api/", + "schemas": { + "Baz": { + "id": "Baz", + "properties": { + "foo": { + "$ref": "Foo" + }, + "foos": { + "items": { + "$ref": "Foo" + }, + "type": "array" + } + }, + "type": "object" + }, + "Foo": { + "id": "Foo", + "properties": { + "name": { + "type": "string" + }, + "value": { + "format": "int32", + "type": "integer" + } + }, + "type": "object" + }, + "MapContainer": { + "id": "MapContainer", + "properties": { + "stringMap": { + "$ref": "Map_String_StringValue", + "description": "A map of string values" + } + }, + "type": "object" + }, + "MapEndpoint": { + "id": "MapEndpoint", + "properties": { + "bazMap": { + "$ref": "Map_String_Baz" + }, + "booleanKeyMap": { + "$ref": "Map_Boolean_String" + }, + "dateKeyMap": { + "$ref": "Map_DateTime_String" + }, + "dateTimeKeyMap": { + "$ref": "Map_DateTime_String" + }, + "enumKeyMap": { + "$ref": "Map_TestEnum_String" + }, + "floatKeyMap": { + "$ref": "Map_Float_String" + }, + "fooMap": { + "$ref": "Map_String_Foo" + }, + "fooMapMap": { + "$ref": "Map_String_Map_String_Foo" + }, + "intKeyMap": { + "$ref": "Map_Integer_String" + }, + "intMap": { + "$ref": "Map_String_Integer" + }, + "longKeyMap": { + "$ref": "Map_Long_String" + }, + "mapOfStrings": { + "$ref": "MapContainer" + }, + "mapService": { + "$ref": "MapEndpoint" + }, + "mapSubclass": { + "$ref": "Map_Boolean_Integer" + }, + "stringArrayMap": { + "$ref": "Map_String_StringCollection" + }, + "stringCollectionMap": { + "$ref": "Map_String_StringCollection" + }, + "stringMap": { + "$ref": "Map_String_String" + }, + "stringValueMap": { + "$ref": "Map_String_StringValue" + } + }, + "type": "object" + }, + "Map_Boolean_Integer": { + "additionalProperties": { + "format": "int32", + "type": "integer" + }, + "id": "Map_Boolean_Integer", + "type": "object" + }, + "Map_Boolean_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Boolean_String", + "type": "object" + }, + "Map_DateTime_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_DateTime_String", + "type": "object" + }, + "Map_Float_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Float_String", + "type": "object" + }, + "Map_Integer_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Integer_String", + "type": "object" + }, + "Map_Long_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_Long_String", + "type": "object" + }, + "Map_String_Baz": { + "additionalProperties": { + "$ref": "Baz" + }, + "id": "Map_String_Baz", + "type": "object" + }, + "Map_String_Foo": { + "additionalProperties": { + "$ref": "Foo" + }, + "id": "Map_String_Foo", + "type": "object" + }, + "Map_String_Integer": { + "additionalProperties": { + "format": "int32", + "type": "integer" + }, + "id": "Map_String_Integer", + "type": "object" + }, + "Map_String_Map_String_Foo": { + "additionalProperties": { + "$ref": "Map_String_Foo" + }, + "id": "Map_String_Map_String_Foo", + "type": "object" + }, + "Map_String_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_String_String", + "type": "object" + }, + "Map_String_StringCollection": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "id": "Map_String_StringCollection", + "type": "object" + }, + "Map_String_StringValue": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_String_StringValue", + "type": "object" + }, + "Map_TestEnum_String": { + "additionalProperties": { + "type": "string" + }, + "id": "Map_TestEnum_String", + "type": "object" + } + }, + "servicePath": "myapi/v1/", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/multiple_parameter_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/multiple_parameter_endpoint.json index 87eeb188..5d976b31 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/multiple_parameter_endpoint.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/multiple_parameter_endpoint.json @@ -14,8 +14,8 @@ "description": "This is an API", "discoveryVersion": "v1", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "multipleparam:v1", "kind": "discovery#restDescription", @@ -25,18 +25,34 @@ "id": "multipleparam.param", "parameterOrder": [ "parent", - "child" + "child", + "querya", + "queryb" ], "parameters": { - "child": { + "parent": { "location": "path", "required": true, "type": "string" }, - "parent": { + "query": { + "location": "query", + "type": "string" + }, + "child": { "location": "path", "required": true, "type": "string" + }, + "queryb": { + "location": "query", + "required": true, + "type": "string" + }, + "querya": { + "location": "query", + "required": true, + "type": "string" } }, "path": "{parent}/{child}", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/namespace_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/namespace_endpoint.json index 9a957fce..17edbfea 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/namespace_endpoint.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/namespace_endpoint.json @@ -14,8 +14,8 @@ "description": "This is an API", "discoveryVersion": "v1", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "namespace:v1", "kind": "discovery#restDescription", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/primitive_endpoint.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/primitive_endpoint.json new file mode 100644 index 00000000..e3ccc382 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/primitive_endpoint.json @@ -0,0 +1,151 @@ +{ + "auth": { + "oauth2": { + "scopes": { + "https://www.googleapis.com/auth/userinfo.email": { + "description": "View your email address" + } + } + } + }, + "basePath": "/api/myapi/v1/", + "baseUrl": "https://discovery-test.appspot.com/api/myapi/v1/", + "batchPath": "batch", + "description": "This is an API", + "discoveryVersion": "v1", + "icons": { + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" + }, + "id": "myapi:v1", + "kind": "discovery#restDescription", + "name": "myapi", + "parameters": { + "alt": { + "default": "json", + "description": "Data format for the response.", + "enum": [ + "json" + ], + "enumDescriptions": [ + "Responses with Content-Type of application/json" + ], + "location": "query", + "type": "string" + }, + "fields": { + "description": "Selector specifying which fields to include in a partial response.", + "location": "query", + "type": "string" + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "oauth_token": { + "description": "OAuth 2.0 token for the current user.", + "location": "query", + "type": "string" + }, + "prettyPrint": { + "default": "true", + "description": "Returns response with indentations and line breaks.", + "location": "query", + "type": "boolean" + }, + "quotaUser": { + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", + "location": "query", + "type": "string" + }, + "userIp": { + "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", + "location": "query", + "type": "string" + } + }, + "protocol": "rest", + "resources": { + "primitiveEndpoint": { + "methods": { + "getPrimitive": { + "httpMethod": "GET", + "id": "myapi.primitiveEndpoint.getPrimitive", + "path": "primitivebean", + "response": { + "$ref": "PrimitiveBean" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + }, + "getPrimitives": { + "httpMethod": "GET", + "id": "myapi.primitiveEndpoint.getPrimitives", + "path": "primitivebeancollection", + "response": { + "$ref": "PrimitiveBeanCollection" + }, + "scopes": [ + "https://www.googleapis.com/auth/userinfo.email" + ] + } + } + } + }, + "rootUrl": "https://discovery-test.appspot.com/api/", + "schemas": { + "PrimitiveBean": { + "id": "PrimitiveBean", + "properties": { + "bool": { + "type": "boolean" + }, + "byte": { + "type": "integer" + }, + "char": { + "type": "string" + }, + "double": { + "format": "double", + "type": "number" + }, + "float": { + "format": "float", + "type": "number" + }, + "int": { + "format": "int32", + "type": "integer" + }, + "long": { + "format": "int64", + "type": "string" + }, + "short": { + "type": "integer" + }, + "str": { + "type": "string" + } + }, + "type": "object" + }, + "PrimitiveBeanCollection": { + "id": "PrimitiveBeanCollection", + "properties": { + "items": { + "items": { + "$ref": "PrimitiveBean" + }, + "type": "array" + } + }, + "type": "object" + } + }, + "servicePath": "myapi/v1/", + "version": "v1" +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/tictactoe.json b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/tictactoe.json index 4c96941e..123292a5 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/tictactoe.json +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/discovery/tictactoe.json @@ -15,8 +15,8 @@ "discoveryVersion": "v1", "etag": "\"zRMgE0l9nVDW4S28VYYcYQF9UW4/JGTFfoDuVVdzoKDgyqpFMu-y3OU\"", "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" + "x16": "https://www.gstatic.com/images/branding/product/1x/googleg_16dp.png", + "x32": "https://www.gstatic.com/images/branding/product/1x/googleg_32dp.png" }, "id": "tictactoe:v1", "kind": "discovery#restDescription", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/absolute_common_path_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/absolute_common_path_endpoint.swagger new file mode 100644 index 00000000..075c602a --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/absolute_common_path_endpoint.swagger @@ -0,0 +1,59 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "myapi.appspot.com" + }, + "host": "myapi.appspot.com", + "basePath": "/_ah/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/absolutepath/v1/absolutepathmethod": { + "post": { + "operationId": "AbsolutepathV1AbsolutePath", + "parameters": [], + "responses": { + "200": { + "description": "A successful response" + } + } + } + }, + "/absolutepath/v1/create": { + "post": { + "operationId": "AbsolutepathV1CreateFoo", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + } + }, + "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/absolute_path_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/absolute_path_endpoint.swagger new file mode 100644 index 00000000..53b6bf50 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/absolute_path_endpoint.swagger @@ -0,0 +1,70 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "myapi.appspot.com" + }, + "host": "myapi.appspot.com", + "basePath": "/_ah/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/absolutepath/v1/create": { + "post": { + "operationId": "AbsolutepathV1CreateFoo", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + }, + "/absolutepathmethod/v1": { + "post": { + "operationId": "AbsolutepathV1AbsolutePath", + "parameters": [], + "responses": { + "200": { + "description": "A successful response" + } + } + } + }, + "/absolutepathmethod2/v1": { + "post": { + "operationId": "AbsolutepathV1AbsolutePath2", + "parameters": [], + "responses": { + "200": { + "description": "A successful response" + } + } + } + } + }, + "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/api_keys.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/api_keys.swagger index f711a1d5..44143838 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/api_keys.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/api_keys.swagger @@ -16,9 +16,26 @@ "application/json" ], "paths": { + "/apikeys/v1/apiKeyWithAuth": { + "post": { + "operationId": "ApikeysV1ApiKeyWithAuth", + "parameters": [], + "responses": { + "200": { + "description": "A successful response" + } + }, + "security": [ + { + "auth0-6fa4a909": [], + "api_key": [] + } + ] + } + }, "/apikeys/v1/inheritApiKeySetting": { "post": { - "operationId": "ApikeysInheritApiKeySetting", + "operationId": "ApikeysV1InheritApiKeySetting", "parameters": [], "responses": { "200": { @@ -34,7 +51,7 @@ }, "/apikeys/v1/overrideApiKeySetting": { "post": { - "operationId": "ApikeysOverrideApiKeySetting", + "operationId": "ApikeysV1OverrideApiKeySetting", "parameters": [], "responses": { "200": { @@ -45,6 +62,14 @@ } }, "securityDefinitions": { + "auth0-6fa4a909": { + "type": "oauth2", + "authorizationUrl": "", + "flow": "implicit", + "x-google-issuer": "https://test.auth0.com/authorize", + "x-google-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json", + "x-google-audiences": "auth0audmethod" + }, "api_key": { "type": "apiKey", "name": "key", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/array_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/array_endpoint.swagger index 949b6994..b2efe3c3 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/array_endpoint.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/array_endpoint.swagger @@ -18,7 +18,7 @@ "paths": { "/myapi/v1/arrayendpoint": { "get": { - "operationId": "MyapiGetArrayService", + "operationId": "MyapiV1GetArrayService", "parameters": [], "responses": { "200": { @@ -32,7 +32,7 @@ }, "/myapi/v1/baz": { "get": { - "operationId": "MyapiGetBaz", + "operationId": "MyapiV1GetBaz", "parameters": [], "responses": { "200": { @@ -46,7 +46,7 @@ }, "/myapi/v1/collectionresponse_foo": { "get": { - "operationId": "MyapiGetFoosResponse", + "operationId": "MyapiV1GetFoosResponse", "parameters": [], "responses": { "200": { @@ -60,7 +60,7 @@ }, "/myapi/v1/foocollection": { "get": { - "operationId": "MyapiGetFoos", + "operationId": "MyapiV1GetFoos", "parameters": [], "responses": { "200": { @@ -74,7 +74,7 @@ }, "/myapi/v1/foocollectioncollection": { "get": { - "operationId": "MyapiGetAllArrayedFoos", + "operationId": "MyapiV1GetAllArrayedFoos", "parameters": [], "responses": { "200": { @@ -88,7 +88,7 @@ }, "/myapi/v1/getAllFoos": { "get": { - "operationId": "MyapiGetAllFoos", + "operationId": "MyapiV1GetAllFoos", "parameters": [], "responses": { "200": { @@ -102,7 +102,7 @@ }, "/myapi/v1/getAllFoosResponse": { "get": { - "operationId": "MyapiGetAllFoosResponse", + "operationId": "MyapiV1GetAllFoosResponse", "parameters": [], "responses": { "200": { @@ -116,7 +116,7 @@ }, "/myapi/v1/getAllNestedFoosResponse": { "get": { - "operationId": "MyapiGetAllNestedFoosResponse", + "operationId": "MyapiV1GetAllNestedFoosResponse", "parameters": [], "responses": { "200": { @@ -130,7 +130,7 @@ }, "/myapi/v1/getArrayedFoos": { "get": { - "operationId": "MyapiGetArrayedFoos", + "operationId": "MyapiV1GetArrayedFoos", "parameters": [], "responses": { "200": { @@ -144,7 +144,7 @@ }, "/myapi/v1/getIntegersResponse": { "get": { - "operationId": "MyapiGetIntegersResponse", + "operationId": "MyapiV1GetIntegersResponse", "parameters": [], "responses": { "200": { @@ -156,9 +156,23 @@ } } }, + "/myapi/v1/getListOfString": { + "get": { + "operationId": "MyapiV1GetListOfString", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/ListContainer" + } + } + } + } + }, "/myapi/v1/getObjectIntegers": { "get": { - "operationId": "MyapiGetObjectIntegers", + "operationId": "MyapiV1GetObjectIntegers", "parameters": [], "responses": { "200": { @@ -172,7 +186,7 @@ }, "/myapi/v1/integercollection": { "get": { - "operationId": "MyapiGetIntegers", + "operationId": "MyapiV1GetIntegers", "parameters": [], "responses": { "200": { @@ -187,6 +201,7 @@ }, "definitions": { "CollectionResponse_Integer": { + "type": "object", "properties": { "items": { "type": "array", @@ -201,6 +216,7 @@ } }, "CollectionResponse_Foo": { + "type": "object", "properties": { "items": { "type": "array", @@ -214,6 +230,7 @@ } }, "Foo": { + "type": "object", "properties": { "name": { "type": "string" @@ -225,6 +242,7 @@ } }, "FooCollectionCollection": { + "type": "object", "properties": { "items": { "type": "array", @@ -238,6 +256,7 @@ } }, "Baz": { + "type": "object", "properties": { "foo": { "$ref": "#/definitions/Foo" @@ -250,7 +269,31 @@ } } }, + "ListContainer": { + "type": "object", + "properties": { + "strings": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "IntegerCollection": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + } + } + }, "CollectionResponse_FooCollection": { + "type": "object", "properties": { "items": { "type": "array", @@ -267,6 +310,7 @@ } }, "ArrayEndpoint": { + "type": "object", "properties": { "allArrayedFoos": { "type": "array", @@ -323,6 +367,9 @@ "integersResponse": { "$ref": "#/definitions/CollectionResponse_Integer" }, + "listOfString": { + "$ref": "#/definitions/ListContainer" + }, "objectIntegers": { "type": "array", "items": { @@ -332,18 +379,8 @@ } } }, - "IntegerCollection": { - "properties": { - "items": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - } - } - }, "FooCollection": { + "type": "object", "properties": { "items": { "type": "array", @@ -354,6 +391,7 @@ } }, "CollectionResponse_FooCollectionCollection": { + "type": "object", "properties": { "items": { "type": "array", diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/enum_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/enum_endpoint.swagger index 2c882e2d..98bf9c95 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/enum_endpoint.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/enum_endpoint.swagger @@ -18,7 +18,7 @@ "paths": { "/enum/v1/{value}": { "post": { - "operationId": "EnumCreate", + "operationId": "EnumV1Create", "parameters": [ { "name": "value", @@ -44,17 +44,16 @@ }, "definitions": { "EnumValue": { + "type": "object", "properties": { "value": { - "$ref": "#/definitions/TestEnum" + "type": "string", + "enum": [ + "VALUE1", + "VALUE2" + ] } } - }, - "TestEnum": { - "enum": [ - "VALUE1", - "VALUE2" - ] } } } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint.swagger index 5508220c..4d6a053e 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint.swagger @@ -19,7 +19,7 @@ "/foo/v1/foos": { "get": { "description": "list desc", - "operationId": "FooListFoos", + "operationId": "FooV1ListFoos", "parameters": [ { "name": "n", @@ -39,15 +39,15 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "post": { - "operationId": "FooToplevel", + "operationId": "FooV1Toplevel", "parameters": [], "responses": { "200": { @@ -59,10 +59,10 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] } @@ -70,7 +70,7 @@ "/foo/v1/foos/{id}": { "get": { "description": "get desc", - "operationId": "FooGetFoo", + "operationId": "FooV1GetFoo", "parameters": [ { "name": "id", @@ -90,16 +90,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "post": { "description": "update desc", - "operationId": "FooUpdateFoo", + "operationId": "FooV1UpdateFoo", "parameters": [ { "name": "id", @@ -109,8 +109,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -127,16 +127,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "put": { "description": "create desc", - "operationId": "FooCreateFoo", + "operationId": "FooV1CreateFoo", "parameters": [ { "name": "id", @@ -146,8 +146,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -164,16 +164,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "delete": { "description": "delete desc", - "operationId": "FooDeleteFoo", + "operationId": "FooV1DeleteFoo", "parameters": [ { "name": "id", @@ -193,33 +193,48 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] } } }, "securityDefinitions": { - "google_id_token_https": { + "google_id_token-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" }, - "google_id_token": { + "google_id_token_https-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "https://accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" } }, "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + }, "CollectionResponse_Foo": { + "type": "object", "properties": { "items": { "type": "array", @@ -231,17 +246,6 @@ "type": "string" } } - }, - "Foo": { - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "integer", - "format": "int32" - } - } } } } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_default_context.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_default_context.swagger index a63a3b03..f531f79e 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_default_context.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_default_context.swagger @@ -19,7 +19,7 @@ "/foo/v1/foos": { "get": { "description": "list desc", - "operationId": "FooListFoos", + "operationId": "FooV1ListFoos", "parameters": [ { "name": "n", @@ -39,15 +39,15 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "post": { - "operationId": "FooToplevel", + "operationId": "FooV1Toplevel", "parameters": [], "responses": { "200": { @@ -59,10 +59,10 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] } @@ -70,7 +70,7 @@ "/foo/v1/foos/{id}": { "get": { "description": "get desc", - "operationId": "FooGetFoo", + "operationId": "FooV1GetFoo", "parameters": [ { "name": "id", @@ -90,16 +90,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "post": { "description": "update desc", - "operationId": "FooUpdateFoo", + "operationId": "FooV1UpdateFoo", "parameters": [ { "name": "id", @@ -109,8 +109,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -127,16 +127,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "put": { "description": "create desc", - "operationId": "FooCreateFoo", + "operationId": "FooV1CreateFoo", "parameters": [ { "name": "id", @@ -146,8 +146,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -164,16 +164,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "delete": { "description": "delete desc", - "operationId": "FooDeleteFoo", + "operationId": "FooV1DeleteFoo", "parameters": [ { "name": "id", @@ -193,33 +193,36 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] } } }, "securityDefinitions": { - "google_id_token_https": { + "google_id_token-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" }, - "google_id_token": { + "google_id_token_https-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "https://accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" } }, "definitions": { "CollectionResponse_Foo": { + "type": "object", "properties": { "items": { "type": "array", @@ -233,6 +236,7 @@ } }, "Foo": { + "type": "object", "properties": { "name": { "type": "string" diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_internal.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_internal.swagger index 780e7590..95dd8029 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_internal.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_internal.swagger @@ -19,7 +19,7 @@ "/foo/v1/foos": { "get": { "description": "list desc", - "operationId": "FooListFoos", + "operationId": "FooV1ListFoos", "parameters": [ { "name": "n", @@ -39,31 +39,15 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "audience" - ] - } - }, - { - "google_id_token_https": { - "audiences": [ - "audience" - ] - } + "google_id_token_https-3a26ea04": [] } ] }, "post": { - "operationId": "FooToplevel", + "operationId": "FooV1Toplevel", "parameters": [], "responses": { "200": { @@ -75,26 +59,10 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "audience" - ] - } - }, - { - "google_id_token_https": { - "audiences": [ - "audience" - ] - } + "google_id_token_https-3a26ea04": [] } ] } @@ -102,7 +70,7 @@ "/foo/v1/foos/{id}": { "get": { "description": "get desc", - "operationId": "FooGetFoo", + "operationId": "FooV1GetFoo", "parameters": [ { "name": "id", @@ -122,32 +90,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "audience" - ] - } - }, - { - "google_id_token_https": { - "audiences": [ - "audience" - ] - } + "google_id_token_https-3a26ea04": [] } ] }, "post": { "description": "update desc", - "operationId": "FooUpdateFoo", + "operationId": "FooV1UpdateFoo", "parameters": [ { "name": "id", @@ -157,8 +109,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -175,32 +127,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "audience" - ] - } - }, - { - "google_id_token_https": { - "audiences": [ - "audience" - ] - } + "google_id_token_https-3a26ea04": [] } ] }, "put": { "description": "create desc", - "operationId": "FooCreateFoo", + "operationId": "FooV1CreateFoo", "parameters": [ { "name": "id", @@ -210,8 +146,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -228,32 +164,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "audience" - ] - } - }, - { - "google_id_token_https": { - "audiences": [ - "audience" - ] - } + "google_id_token_https-3a26ea04": [] } ] }, "delete": { "description": "delete desc", - "operationId": "FooDeleteFoo", + "operationId": "FooV1DeleteFoo", "parameters": [ { "name": "id", @@ -273,49 +193,36 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "audience" - ] - } - }, - { - "google_id_token_https": { - "audiences": [ - "audience" - ] - } + "google_id_token_https-3a26ea04": [] } ] } } }, "securityDefinitions": { - "google_id_token_https": { + "google_id_token-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" }, - "google_id_token": { + "google_id_token_https-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "https://accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" } }, "definitions": { "CollectionResponse_Foo": { + "type": "object", "properties": { "items": { "type": "array", @@ -329,6 +236,7 @@ } }, "Foo": { + "type": "object", "properties": { "name": { "type": "string" diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_localhost.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_localhost.swagger index 1e35acba..f91532dd 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_localhost.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_endpoint_localhost.swagger @@ -19,7 +19,7 @@ "/foo/v1/foos": { "get": { "description": "list desc", - "operationId": "FooListFoos", + "operationId": "FooV1ListFoos", "parameters": [ { "name": "n", @@ -39,15 +39,15 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "post": { - "operationId": "FooToplevel", + "operationId": "FooV1Toplevel", "parameters": [], "responses": { "200": { @@ -59,10 +59,10 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] } @@ -70,7 +70,7 @@ "/foo/v1/foos/{id}": { "get": { "description": "get desc", - "operationId": "FooGetFoo", + "operationId": "FooV1GetFoo", "parameters": [ { "name": "id", @@ -90,16 +90,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "post": { "description": "update desc", - "operationId": "FooUpdateFoo", + "operationId": "FooV1UpdateFoo", "parameters": [ { "name": "id", @@ -109,8 +109,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -127,16 +127,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "put": { "description": "create desc", - "operationId": "FooCreateFoo", + "operationId": "FooV1CreateFoo", "parameters": [ { "name": "id", @@ -146,8 +146,8 @@ "type": "string" }, { - "name": "body", "in": "body", + "name": "body", "required": false, "schema": { "$ref": "#/definitions/Foo" @@ -164,16 +164,16 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] }, "delete": { "description": "delete desc", - "operationId": "FooDeleteFoo", + "operationId": "FooV1DeleteFoo", "parameters": [ { "name": "id", @@ -193,33 +193,48 @@ }, "security": [ { - "google_id_token": [] + "google_id_token-3a26ea04": [] }, { - "google_id_token_https": [] + "google_id_token_https-3a26ea04": [] } ] } } }, "securityDefinitions": { - "google_id_token_https": { + "google_id_token-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" }, - "google_id_token": { + "google_id_token_https-3a26ea04": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "https://accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" } }, "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + }, "CollectionResponse_Foo": { + "type": "object", "properties": { "items": { "type": "array", @@ -231,17 +246,6 @@ "type": "string" } } - }, - "Foo": { - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "integer", - "format": "int32" - } - } } } } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_with_description_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_with_description_endpoint.swagger new file mode 100644 index 00000000..c291a6a6 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/foo_with_description_endpoint.swagger @@ -0,0 +1,272 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "swagger-test.appspot.com" + }, + "host": "swagger-test.appspot.com", + "basePath": "/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/foo/v1/foos": { + "get": { + "description": "list desc", + "operationId": "FooV1ListFoos", + "parameters": [ + { + "name": "n", + "in": "query", + "required": true, + "type": "integer", + "format": "int32" + }, + { + "name": "enum", + "in": "query", + "description": "enum desc", + "required": false, + "type": "string", + "enum": [ + "VALUE1", + "VALUE2" + ] + } + ], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/CollectionResponse_FooDescription" + } + } + }, + "security": [ + { + "google_id_token-3a26ea04": [] + }, + { + "google_id_token_https-3a26ea04": [] + } + ] + }, + "post": { + "operationId": "FooV1Toplevel", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/CollectionResponse_FooDescription" + } + } + }, + "security": [ + { + "google_id_token-3a26ea04": [] + }, + { + "google_id_token_https-3a26ea04": [] + } + ] + } + }, + "/foo/v1/foos/{id}": { + "get": { + "description": "get desc", + "operationId": "FooV1GetFoo", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "id desc", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/FooDescription" + } + } + }, + "security": [ + { + "google_id_token-3a26ea04": [] + }, + { + "google_id_token_https-3a26ea04": [] + } + ] + }, + "post": { + "description": "update desc", + "operationId": "FooV1UpdateFoo", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "id desc", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "required": false, + "schema": { + "$ref": "#/definitions/FooDescription" + } + } + ], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/FooDescription" + } + } + }, + "security": [ + { + "google_id_token-3a26ea04": [] + }, + { + "google_id_token_https-3a26ea04": [] + } + ] + }, + "put": { + "description": "create desc", + "operationId": "FooV1CreateFoo", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "id desc", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "required": false, + "schema": { + "$ref": "#/definitions/FooDescription" + } + } + ], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/FooDescription" + } + } + }, + "security": [ + { + "google_id_token-3a26ea04": [] + }, + { + "google_id_token_https-3a26ea04": [] + } + ] + }, + "delete": { + "description": "delete desc", + "operationId": "FooV1DeleteFoo", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "id desc", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/FooDescription" + } + } + }, + "security": [ + { + "google_id_token-3a26ea04": [] + }, + { + "google_id_token_https-3a26ea04": [] + } + ] + } + } + }, + "securityDefinitions": { + "google_id_token-3a26ea04": { + "type": "oauth2", + "authorizationUrl": "", + "flow": "implicit", + "x-google-issuer": "accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" + }, + "google_id_token_https-3a26ea04": { + "type": "oauth2", + "authorizationUrl": "", + "flow": "implicit", + "x-google-issuer": "https://accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "audience" + } + }, + "definitions": { + "FooDescription": { + "type": "object", + "properties": { + "choice": { + "type": "string", + "description": "description of choice", + "enum": [ + "VALUE1", + "VALUE2" + ] + }, + "name": { + "type": "string", + "description": "description of name" + }, + "value": { + "type": "integer", + "format": "int32", + "description": "description of value" + } + } + }, + "CollectionResponse_FooDescription": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/FooDescription" + } + }, + "nextPageToken": { + "type": "string" + } + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/google_auth.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/google_auth.swagger index 805a97a1..532b9fde 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/google_auth.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/google_auth.swagger @@ -18,7 +18,7 @@ "paths": { "/thirdparty/v1/authOverride": { "post": { - "operationId": "ThirdpartyAuthOverride", + "operationId": "ThirdpartyV1AuthOverride", "parameters": [], "responses": { "200": { @@ -27,23 +27,14 @@ }, "security": [ { - "auth0": [] - } - ], - "x-security": [ - { - "auth0": { - "audiences": [ - "auth0audmethod" - ] - } + "auth0-6fa4a909": [] } ] } }, "/thirdparty/v1/googleAuth": { "post": { - "operationId": "ThirdpartyGoogleAuth", + "operationId": "ThirdpartyV1GoogleAuth", "parameters": [], "responses": { "200": { @@ -52,23 +43,14 @@ }, "security": [ { - "google_id_token": [] - } - ], - "x-security": [ - { - "google_id_token": { - "audiences": [ - "googleaud" - ] - } + "google_id_token-57e345d7": [] } ] } }, "/thirdparty/v1/noOverride": { "post": { - "operationId": "ThirdpartyNoOverride", + "operationId": "ThirdpartyV1NoOverride", "parameters": [], "responses": { "200": { @@ -77,48 +59,36 @@ }, "security": [ { - "auth0": [] - } - ], - "x-security": [ - { - "auth0": { - "audiences": [ - "auth0audapi" - ] - } + "auth0-a05d2f2": [] } ] } } }, "securityDefinitions": { - "auth0": { - "type": "oauth2", - "authorizationUrl": "", - "flow": "implicit", - "x-issuer": "https://test.auth0.com/authorize", - "x-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json" - }, - "nojwks": { + "auth0-6fa4a909": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://nojwks.com" + "x-google-issuer": "https://test.auth0.com/authorize", + "x-google-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json", + "x-google-audiences": "auth0audmethod" }, - "google_id_token": { + "google_id_token-57e345d7": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "accounts.google.com", + "x-google-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs", + "x-google-audiences": "googleaud" }, - "google_id_token_https": { + "auth0-a05d2f2": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://accounts.google.com", - "x-jwks_uri": "https://www.googleapis.com/oauth2/v1/certs" + "x-google-issuer": "https://test.auth0.com/authorize", + "x-google-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json", + "x-google-audiences": "auth0audapi" } } } diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/limit_metrics_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/limit_metrics_endpoint.swagger new file mode 100644 index 00000000..05eaf11c --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/limit_metrics_endpoint.swagger @@ -0,0 +1,105 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "myapi.appspot.com" + }, + "host": "myapi.appspot.com", + "basePath": "/_ah/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/limits/v1/create": { + "post": { + "operationId": "LimitsV1CreateFoo", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + }, + "x-google-quota": { + "metricCosts": { + "write": 5 + } + } + } + }, + "/limits/v1/customFoo": { + "post": { + "operationId": "LimitsV1CustomFoo", + "parameters": [], + "responses": { + "200": { + "description": "A successful response" + } + }, + "x-google-quota": { + "metricCosts": { + "read": 1, + "write": 2 + } + } + } + } + }, + "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + } + }, + "x-google-management": { + "metrics": [ + { + "name": "read", + "valueType": "INT64", + "metricKind": "GAUGE" + }, + { + "name": "write", + "valueType": "INT64", + "metricKind": "GAUGE" + } + ], + "quota": { + "limits": [ + { + "name": "read", + "metric": "read", + "values": { + "STANDARD": 100 + }, + "unit": "1/min/{project}", + "displayName": "Read requests" + }, + { + "name": "write", + "metric": "write", + "values": { + "STANDARD": 10 + }, + "unit": "1/min/{project}" + } + ] + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint.swagger new file mode 100644 index 00000000..5fb2ba37 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint.swagger @@ -0,0 +1,451 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "myapi.appspot.com" + }, + "host": "myapi.appspot.com", + "basePath": "/_ah/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/myapi/v1/getDateTimeKeyMap": { + "get": { + "operationId": "MyapiV1GetDateTimeKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_DateTime_String" + } + } + } + } + }, + "/myapi/v1/getMapOfStrings": { + "get": { + "operationId": "MyapiV1GetMapOfStrings", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/MapContainer" + } + } + } + } + }, + "/myapi/v1/getStringCollectionMap": { + "get": { + "operationId": "MyapiV1GetStringCollectionMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_boolean_string": { + "get": { + "operationId": "MyapiV1GetBooleanKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Boolean_String" + } + } + } + } + }, + "/myapi/v1/map_datetime_string": { + "get": { + "operationId": "MyapiV1GetDateKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_DateTime_String" + } + } + } + } + }, + "/myapi/v1/map_float_string": { + "get": { + "operationId": "MyapiV1GetFloatKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Float_String" + } + } + } + } + }, + "/myapi/v1/map_integer_string": { + "get": { + "operationId": "MyapiV1GetIntKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Integer_String" + } + } + } + } + }, + "/myapi/v1/map_long_string": { + "get": { + "operationId": "MyapiV1GetLongKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Long_String" + } + } + } + } + }, + "/myapi/v1/map_string_baz": { + "get": { + "operationId": "MyapiV1GetBazMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Baz" + } + } + } + } + }, + "/myapi/v1/map_string_foo": { + "get": { + "operationId": "MyapiV1GetFooMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Foo" + } + } + } + } + }, + "/myapi/v1/map_string_integer": { + "get": { + "operationId": "MyapiV1GetIntMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Integer" + } + } + } + } + }, + "/myapi/v1/map_string_map_string_foo": { + "get": { + "operationId": "MyapiV1GetFooMapMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Map_String_Foo" + } + } + } + } + }, + "/myapi/v1/map_string_string": { + "get": { + "operationId": "MyapiV1GetStringMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_String" + } + } + } + } + }, + "/myapi/v1/map_string_stringcollection": { + "get": { + "operationId": "MyapiV1GetStringArrayMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_stringvalue": { + "get": { + "operationId": "MyapiV1GetStringValueMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_StringValue" + } + } + } + } + }, + "/myapi/v1/map_testenum_string": { + "get": { + "operationId": "MyapiV1GetEnumKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_TestEnum_String" + } + } + } + } + }, + "/myapi/v1/mapendpoint": { + "get": { + "operationId": "MyapiV1GetMapService", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/MapEndpoint" + } + } + } + } + }, + "/myapi/v1/mapsubclass": { + "get": { + "operationId": "MyapiV1GetMapSubclass", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Boolean_Integer" + } + } + } + } + } + }, + "definitions": { + "Map_Boolean_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Map_Float_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + }, + "Map_Integer_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Map_TestEnum_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Map_Boolean_Integer": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + }, + "JsonMap": { + "type": "object" + }, + "Map_String_StringValue": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "MapContainer": { + "type": "object", + "properties": { + "stringMap": { + "$ref": "#/definitions/Map_String_StringValue" + } + } + }, + "Map_String_Integer": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + }, + "Map_String_Baz": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/Baz" + } + }, + "Map_String_Map_String_Foo": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/Map_String_Foo" + } + }, + "Map_String_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Baz": { + "type": "object", + "properties": { + "foo": { + "$ref": "#/definitions/Foo" + }, + "foos": { + "type": "array", + "items": { + "$ref": "#/definitions/Foo" + } + } + } + }, + "Map_Long_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "MapEndpoint": { + "type": "object", + "properties": { + "bazMap": { + "$ref": "#/definitions/Map_String_Baz" + }, + "booleanKeyMap": { + "$ref": "#/definitions/Map_Boolean_String" + }, + "dateKeyMap": { + "$ref": "#/definitions/Map_DateTime_String" + }, + "dateTimeKeyMap": { + "$ref": "#/definitions/Map_DateTime_String" + }, + "enumKeyMap": { + "$ref": "#/definitions/Map_TestEnum_String" + }, + "floatKeyMap": { + "$ref": "#/definitions/Map_Float_String" + }, + "fooMap": { + "$ref": "#/definitions/Map_String_Foo" + }, + "fooMapMap": { + "$ref": "#/definitions/Map_String_Map_String_Foo" + }, + "intKeyMap": { + "$ref": "#/definitions/Map_Integer_String" + }, + "intMap": { + "$ref": "#/definitions/Map_String_Integer" + }, + "longKeyMap": { + "$ref": "#/definitions/Map_Long_String" + }, + "mapOfStrings": { + "$ref": "#/definitions/MapContainer" + }, + "mapService": { + "$ref": "#/definitions/MapEndpoint" + }, + "mapSubclass": { + "$ref": "#/definitions/Map_Boolean_Integer" + }, + "stringArrayMap": { + "$ref": "#/definitions/JsonMap" + }, + "stringCollectionMap": { + "$ref": "#/definitions/JsonMap" + }, + "stringMap": { + "$ref": "#/definitions/Map_String_String" + }, + "stringValueMap": { + "$ref": "#/definitions/Map_String_StringValue" + } + } + }, + "Map_String_Foo": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/Foo" + } + }, + "Map_DateTime_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } +} + diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint_legacy.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint_legacy.swagger new file mode 100644 index 00000000..8d4cf4e1 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint_legacy.swagger @@ -0,0 +1,344 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "myapi.appspot.com" + }, + "host": "myapi.appspot.com", + "basePath": "/_ah/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/myapi/v1/getDateTimeKeyMap": { + "get": { + "operationId": "MyapiV1GetDateTimeKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/getMapOfStrings": { + "get": { + "operationId": "MyapiV1GetMapOfStrings", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/MapContainer" + } + } + } + } + }, + "/myapi/v1/getStringCollectionMap": { + "get": { + "operationId": "MyapiV1GetStringCollectionMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_boolean_string": { + "get": { + "operationId": "MyapiV1GetBooleanKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_datetime_string": { + "get": { + "operationId": "MyapiV1GetDateKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_float_string": { + "get": { + "operationId": "MyapiV1GetFloatKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_integer_string": { + "get": { + "operationId": "MyapiV1GetIntKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_long_string": { + "get": { + "operationId": "MyapiV1GetLongKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_baz": { + "get": { + "operationId": "MyapiV1GetBazMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_foo": { + "get": { + "operationId": "MyapiV1GetFooMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_integer": { + "get": { + "operationId": "MyapiV1GetIntMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_map_string_foo": { + "get": { + "operationId": "MyapiV1GetFooMapMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_string": { + "get": { + "operationId": "MyapiV1GetStringMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_stringcollection": { + "get": { + "operationId": "MyapiV1GetStringArrayMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_string_stringvalue": { + "get": { + "operationId": "MyapiV1GetStringValueMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/map_testenum_string": { + "get": { + "operationId": "MyapiV1GetEnumKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + }, + "/myapi/v1/mapendpoint": { + "get": { + "operationId": "MyapiV1GetMapService", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/MapEndpoint" + } + } + } + } + }, + "/myapi/v1/mapsubclass": { + "get": { + "operationId": "MyapiV1GetMapSubclass", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/JsonMap" + } + } + } + } + } + }, + "definitions": { + "JsonMap": { + "type": "object" + }, + "MapContainer": { + "type": "object", + "properties": { + "stringMap": { + "$ref": "#/definitions/JsonMap" + } + } + }, + "MapEndpoint": { + "type": "object", + "properties": { + "bazMap": { + "$ref": "#/definitions/JsonMap" + }, + "booleanKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "dateKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "dateTimeKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "enumKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "floatKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "fooMap": { + "$ref": "#/definitions/JsonMap" + }, + "fooMapMap": { + "$ref": "#/definitions/JsonMap" + }, + "intKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "intMap": { + "$ref": "#/definitions/JsonMap" + }, + "longKeyMap": { + "$ref": "#/definitions/JsonMap" + }, + "mapOfStrings": { + "$ref": "#/definitions/MapContainer" + }, + "mapService": { + "$ref": "#/definitions/MapEndpoint" + }, + "mapSubclass": { + "$ref": "#/definitions/JsonMap" + }, + "stringArrayMap": { + "$ref": "#/definitions/JsonMap" + }, + "stringCollectionMap": { + "$ref": "#/definitions/JsonMap" + }, + "stringMap": { + "$ref": "#/definitions/JsonMap" + }, + "stringValueMap": { + "$ref": "#/definitions/JsonMap" + } + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint_with_array.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint_with_array.swagger new file mode 100644 index 00000000..aa7e536b --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/map_endpoint_with_array.swagger @@ -0,0 +1,456 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "myapi.appspot.com" + }, + "host": "myapi.appspot.com", + "basePath": "/_ah/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/myapi/v1/getDateTimeKeyMap": { + "get": { + "operationId": "MyapiV1GetDateTimeKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_DateTime_String" + } + } + } + } + }, + "/myapi/v1/getMapOfStrings": { + "get": { + "operationId": "MyapiV1GetMapOfStrings", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/MapContainer" + } + } + } + } + }, + "/myapi/v1/getStringCollectionMap": { + "get": { + "operationId": "MyapiV1GetStringCollectionMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_StringCollection" + } + } + } + } + }, + "/myapi/v1/map_boolean_string": { + "get": { + "operationId": "MyapiV1GetBooleanKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Boolean_String" + } + } + } + } + }, + "/myapi/v1/map_datetime_string": { + "get": { + "operationId": "MyapiV1GetDateKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_DateTime_String" + } + } + } + } + }, + "/myapi/v1/map_float_string": { + "get": { + "operationId": "MyapiV1GetFloatKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Float_String" + } + } + } + } + }, + "/myapi/v1/map_integer_string": { + "get": { + "operationId": "MyapiV1GetIntKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Integer_String" + } + } + } + } + }, + "/myapi/v1/map_long_string": { + "get": { + "operationId": "MyapiV1GetLongKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Long_String" + } + } + } + } + }, + "/myapi/v1/map_string_baz": { + "get": { + "operationId": "MyapiV1GetBazMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Baz" + } + } + } + } + }, + "/myapi/v1/map_string_foo": { + "get": { + "operationId": "MyapiV1GetFooMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Foo" + } + } + } + } + }, + "/myapi/v1/map_string_integer": { + "get": { + "operationId": "MyapiV1GetIntMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Integer" + } + } + } + } + }, + "/myapi/v1/map_string_map_string_foo": { + "get": { + "operationId": "MyapiV1GetFooMapMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_Map_String_Foo" + } + } + } + } + }, + "/myapi/v1/map_string_string": { + "get": { + "operationId": "MyapiV1GetStringMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_String" + } + } + } + } + }, + "/myapi/v1/map_string_stringcollection": { + "get": { + "operationId": "MyapiV1GetStringArrayMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_StringCollection" + } + } + } + } + }, + "/myapi/v1/map_string_stringvalue": { + "get": { + "operationId": "MyapiV1GetStringValueMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_String_StringValue" + } + } + } + } + }, + "/myapi/v1/map_testenum_string": { + "get": { + "operationId": "MyapiV1GetEnumKeyMap", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_TestEnum_String" + } + } + } + } + }, + "/myapi/v1/mapendpoint": { + "get": { + "operationId": "MyapiV1GetMapService", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/MapEndpoint" + } + } + } + } + }, + "/myapi/v1/mapsubclass": { + "get": { + "operationId": "MyapiV1GetMapSubclass", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Map_Boolean_Integer" + } + } + } + } + } + }, + "definitions": { + "Map_Boolean_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Map_Float_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + }, + "Map_Integer_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Map_TestEnum_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Map_Boolean_Integer": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + }, + "Map_String_StringValue": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "MapContainer": { + "type": "object", + "properties": { + "stringMap": { + "$ref": "#/definitions/Map_String_StringValue" + } + } + }, + "Map_String_Integer": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + }, + "Map_String_Baz": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/Baz" + } + }, + "Map_String_Map_String_Foo": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/Map_String_Foo" + } + }, + "Map_String_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "Baz": { + "type": "object", + "properties": { + "foo": { + "$ref": "#/definitions/Foo" + }, + "foos": { + "type": "array", + "items": { + "$ref": "#/definitions/Foo" + } + } + } + }, + "Map_String_StringCollection": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "Map_Long_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "MapEndpoint": { + "type": "object", + "properties": { + "bazMap": { + "$ref": "#/definitions/Map_String_Baz" + }, + "booleanKeyMap": { + "$ref": "#/definitions/Map_Boolean_String" + }, + "dateKeyMap": { + "$ref": "#/definitions/Map_DateTime_String" + }, + "dateTimeKeyMap": { + "$ref": "#/definitions/Map_DateTime_String" + }, + "enumKeyMap": { + "$ref": "#/definitions/Map_TestEnum_String" + }, + "floatKeyMap": { + "$ref": "#/definitions/Map_Float_String" + }, + "fooMap": { + "$ref": "#/definitions/Map_String_Foo" + }, + "fooMapMap": { + "$ref": "#/definitions/Map_String_Map_String_Foo" + }, + "intKeyMap": { + "$ref": "#/definitions/Map_Integer_String" + }, + "intMap": { + "$ref": "#/definitions/Map_String_Integer" + }, + "longKeyMap": { + "$ref": "#/definitions/Map_Long_String" + }, + "mapOfStrings": { + "$ref": "#/definitions/MapContainer" + }, + "mapService": { + "$ref": "#/definitions/MapEndpoint" + }, + "mapSubclass": { + "$ref": "#/definitions/Map_Boolean_Integer" + }, + "stringArrayMap": { + "$ref": "#/definitions/Map_String_StringCollection" + }, + "stringCollectionMap": { + "$ref": "#/definitions/Map_String_StringCollection" + }, + "stringMap": { + "$ref": "#/definitions/Map_String_String" + }, + "stringValueMap": { + "$ref": "#/definitions/Map_String_StringValue" + } + } + }, + "Map_String_Foo": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/Foo" + } + }, + "Map_DateTime_String": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/multi_resource_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/multi_resource_endpoint.swagger new file mode 100644 index 00000000..f207c1c2 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/multi_resource_endpoint.swagger @@ -0,0 +1,76 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "swagger-test.appspot.com" + }, + "host": "swagger-test.appspot.com", + "basePath": "/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/multiresource/v1/noresource": { + "get": { + "operationId": "MultiresourceV1Get", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + }, + "/multiresource/v1/resource1": { + "get": { + "operationId": "MultiresourceV1Resource1Get", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + }, + "/multiresource/v1/resource2": { + "get": { + "operationId": "MultiresourceV1Resource2Get", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + } + }, + "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/multi_version_endpoint.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/multi_version_endpoint.swagger new file mode 100644 index 00000000..ec4900b6 --- /dev/null +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/multi_version_endpoint.swagger @@ -0,0 +1,62 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "swagger-test.appspot.com" + }, + "host": "swagger-test.appspot.com", + "basePath": "/api", + "schemes": [ + "https" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/myapi/v1/foo": { + "get": { + "operationId": "MyapiV1Get", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + }, + "/myapi/v2/foo": { + "get": { + "operationId": "MyapiV2Get", + "parameters": [], + "responses": { + "200": { + "description": "A successful response", + "schema": { + "$ref": "#/definitions/Foo" + } + } + } + } + } + }, + "definitions": { + "Foo": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "integer", + "format": "int32" + } + } + } + } +} diff --git a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/third_party_auth.swagger b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/third_party_auth.swagger index 1dc86436..ce360959 100644 --- a/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/third_party_auth.swagger +++ b/endpoints-framework/src/test/resources/com/google/api/server/spi/swagger/third_party_auth.swagger @@ -18,7 +18,7 @@ "paths": { "/thirdparty/v1/authOverride": { "post": { - "operationId": "ThirdpartyAuthOverride", + "operationId": "ThirdpartyV1AuthOverride", "parameters": [], "responses": { "200": { @@ -27,23 +27,14 @@ }, "security": [ { - "auth0": [] - } - ], - "x-security": [ - { - "auth0": { - "audiences": [ - "auth0audmethod" - ] - } + "auth0-6fa4a909": [] } ] } }, "/thirdparty/v1/noOverride": { "post": { - "operationId": "ThirdpartyNoOverride", + "operationId": "ThirdpartyV1NoOverride", "parameters": [], "responses": { "200": { @@ -52,34 +43,28 @@ }, "security": [ { - "auth0": [] - } - ], - "x-security": [ - { - "auth0": { - "audiences": [ - "auth0audapi" - ] - } + "auth0-a05d2f2": [] } ] } } }, "securityDefinitions": { - "auth0": { + "auth0-6fa4a909": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://test.auth0.com/authorize", - "x-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json" + "x-google-issuer": "https://test.auth0.com/authorize", + "x-google-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json", + "x-google-audiences": "auth0audmethod" }, - "nojwks": { + "auth0-a05d2f2": { "type": "oauth2", "authorizationUrl": "", "flow": "implicit", - "x-issuer": "https://nojwks.com" + "x-google-issuer": "https://test.auth0.com/authorize", + "x-google-jwks_uri": "https://test.auth0.com/.wellknown/jwks.json", + "x-google-audiences": "auth0audapi" } } } diff --git a/gradle.properties b/gradle.properties index 21793dbb..d12ab317 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,21 +1,25 @@ -version=2.0.0-beta.12 +version=2.2.2 + sourceCompatibility=1.7 targetCompatibility=1.7 group=com.google.endpoints servletVersion=2.5 javaxinjectVersion=1 -guavaVersion=19.0 -jacksonVersion=2.6.4 -appengineVersion=1.9.30 -apiclientVersion=1.21.0 +guavaVersion=20.0 +jacksonVersion=2.9.6 +gradleAppenginePluginVersion=1.9.59 +appengineVersion=1.9.60 +apiclientVersion=1.25.0 +fileUploadVersion=1.3.3 findbugsVersion=3.0.1 swaggerVersion=1.5.9 slf4jVersion=1.7.21 guiceVersion=4.0 -objectifyVersion=5.1.9 +objectifyVersion=5.1.21 +floggerVersion=0.3.1 junitVersion=4.12 mockitoVersion=1.10.19 truthVersion=0.28 -springtestVersion=3.2.16.RELEASE \ No newline at end of file +springtestVersion=3.2.16.RELEASE diff --git a/settings.gradle b/settings.gradle index ec04d231..b3db3bba 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':endpoints-framework', ':endpoints-framework-tools', ':endpoints-framework-guice', ':test-utils', ':discovery-client', ':test-compat', ':test-compat:legacy-app', ':test-compat:new-app', ':test-compat:new-app-guice' +include ':endpoints-framework', 'endpoints-framework-all', ':endpoints-framework-tools', ':endpoints-framework-guice', ':test-utils', ':discovery-client', ':test-compat', ':test-compat:legacy-app', ':test-compat:new-app', ':test-compat:new-app-guice' diff --git a/test-compat/build.gradle b/test-compat/build.gradle index 925922ec..ccfa58a9 100644 --- a/test-compat/build.gradle +++ b/test-compat/build.gradle @@ -22,7 +22,7 @@ buildscript { } dependencies { - classpath "com.google.appengine:gradle-appengine-plugin:${appengineVersion}" + classpath "com.google.appengine:gradle-appengine-plugin:${gradleAppenginePluginVersion}" } } @@ -62,7 +62,6 @@ allprojects { } test { - dependsOn += ':test-compat:appengineEndpointsInstallClientLibs' } // This is necessary because otherwise gradle check runs the dev server, but since there are no @@ -88,7 +87,6 @@ def testAllConfigs = task('testAllConfigs', type: Test) { description = 'runs tests for all environments' group = 'Compatibility testing' testClassesDir = sourceSets.test.output.classesDir - dependsOn += ':test-compat:appengineEndpointsInstallClientLibs' } testConfigs.each { cfg -> @@ -127,12 +125,6 @@ dependencies { compile group: 'javax.servlet', name: 'servlet-api', version: servletVersion compileOnly group: 'com.google.appengine', name: 'appengine-endpoints', version: appengineVersion - testlibCompile(group: 'com.compat_tests', name: 'wax', version: 'v1-+') { - exclude group: 'com.google.guava', module: 'guava-jdk5' - } - testlibCompile(group: 'com.compat_tests', name: 'tictactoe', version: 'v1-+') { - exclude group: 'com.google.guava', module: 'guava-jdk5' - } testlibCompile group: 'junit', name: 'junit', version: junitVersion testlibCompile group: 'com.google.truth', name: 'truth', version: truthVersion testlibCompile group: 'javax.servlet', name: 'servlet-api', version: servletVersion diff --git a/test-compat/src/testlib/java/com/google/testapi/TictactoeTest.java b/test-compat/src/testlib/java/com/google/testapi/TictactoeTest.java deleted file mode 100644 index 8c27f813..00000000 --- a/test-compat/src/testlib/java/com/google/testapi/TictactoeTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.testapi; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.api.client.http.javanet.NetHttpTransport; -import com.google.api.client.json.jackson.JacksonFactory; -import com.google.api.client.util.DateTime; -import com.google.util.TestUtils; - -import com.compat_tests.tictactoe.Tictactoe; -import com.compat_tests.tictactoe.model.FieldContainer; - -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -/** - * End-to-end tests for {@link TestEndpoint}, which implements a tictactoe api (in name only). - */ -public class TictactoeTest { - private static final int INT = 1234; - private static final long LONG = 1234L; - private static final float FLOAT = 1.5f; - private static final double DOUBLE = 5.2; - private static final String STRING = "中文"; - private static final DateTime SIMPLE_DATE = new DateTime("2016-01-26"); - private static final DateTime DATE_TIME = new DateTime("2016-01-26T11:46:00Z"); - private static final DateTime JAVA_DATE = new DateTime("2016-01-26T11:52:00Z"); - private static final String ENUM_VALUE = "VALUE1"; - - private Tictactoe api; - - @Before - public void setUp() { - api = TestUtils.configureApiClient( - new Tictactoe.Builder(new NetHttpTransport(), new JacksonFactory(), null)).build(); - } - - @Test - public void test() throws IOException { - assertThat(api.testEndpoint().test().execute().getValue()).isEqualTo("x"); - } - - @Test - public void echo() throws IOException { - assertThat(api.testEndpoint().echo("test").execute().getValue()).isEqualTo("test"); - } - - @Test - public void testParamsPath() throws IOException { - checkResponse(api.testEndpoint().testParamsPath(INT, LONG, FLOAT, DOUBLE, true, "中文", - SIMPLE_DATE, DATE_TIME, JAVA_DATE, ENUM_VALUE).execute()); - } - - @Test - public void testParamsQuery() throws IOException { - checkResponse(api.testEndpoint().testParamsQuery(true, JAVA_DATE, DATE_TIME, DOUBLE, FLOAT, - LONG, ENUM_VALUE, INT, SIMPLE_DATE, STRING).execute()); - } - - @Test - public void testPathParamCollision() throws IOException { - assertThat(api.testEndpoint().getCollidingPath("test").execute().getValue()).isEqualTo("test"); - assertThat(api.testEndpoint().putCollidingPath("test").execute().getValue()).isEqualTo("test"); - } - - private void checkResponse(FieldContainer ret) { - assertThat(ret.getAnInt()).isEqualTo(INT); - assertThat(ret.getALong()).isEqualTo(LONG); - assertThat(ret.getAFloat()).isWithin(0.0f).of(FLOAT); - assertThat(ret.getADouble()).isWithin(0.0).of(DOUBLE); - assertThat(ret.getABoolean()).isTrue(); - assertThat(ret.getAString()).isEqualTo(STRING); - assertThat(ret.getASimpleDate()).isEqualTo(SIMPLE_DATE); - assertThat(ret.getADateAndTime()).isEqualTo(DATE_TIME); - assertThat(ret.getAnEnum()).isEqualTo(ENUM_VALUE); - } -} diff --git a/test-compat/src/testlib/java/com/google/util/TestUtils.java b/test-compat/src/testlib/java/com/google/util/TestUtils.java deleted file mode 100644 index 31f2329b..00000000 --- a/test-compat/src/testlib/java/com/google/util/TestUtils.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.util; - -import com.google.api.client.googleapis.services.AbstractGoogleClient; -import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpResponse; -import com.google.api.client.http.HttpUnsuccessfulResponseHandler; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -/** - * Miscellaneous utilities for end-to-end tests. - */ -public class TestUtils { - private static final String TEST_BACKEND_URL_PROPERTY = "test.backend.url"; - - public static T configureApiClient(T builder) { - builder - .setRootUrl(System.getProperty(TEST_BACKEND_URL_PROPERTY)) - .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() { - @Override - public void initialize(AbstractGoogleClientRequest request) throws IOException { - request.setDisableGZipContent(true); - } - }) - .setHttpRequestInitializer(new HttpRequestInitializer() { - @Override - public void initialize(HttpRequest request) throws IOException { - request.setUnsuccessfulResponseHandler(new ErrorHandler()); - } - }); - return builder; - } - - private static class ErrorHandler implements HttpUnsuccessfulResponseHandler { - @Override - public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) - throws IOException { - System.out.println(response.getStatusCode()); - BufferedReader in = new BufferedReader(new InputStreamReader(response.getContent())); - String line; - while ((line = in.readLine()) != null) { - System.out.println(line); - } - return false; - } - } -} diff --git a/test-compat/src/testlib/java/com/google/waxapi/WaxTest.java b/test-compat/src/testlib/java/com/google/waxapi/WaxTest.java deleted file mode 100644 index 1c390278..00000000 --- a/test-compat/src/testlib/java/com/google/waxapi/WaxTest.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.waxapi; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.javanet.NetHttpTransport; -import com.google.api.client.json.jackson.JacksonFactory; -import com.google.common.truth.IntegerSubject; -import com.google.util.TestUtils; - -import com.compat_tests.wax.Wax; -import com.compat_tests.wax.model.WaxDataItem; -import com.compat_tests.wax.model.WaxDataItemCollection; -import com.compat_tests.wax.model.WaxNewSessionRequest; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.io.IOException; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -/** - * End-to-end tests using the Wax API. - */ -@RunWith(JUnit4.class) -public class WaxTest { - private static final WaxDataItem ITEM_A = new WaxDataItem().setId("A").setName("Item A"); - private static final WaxDataItem ITEM_B = new WaxDataItem().setId("B").setName("Item B"); - private static final WaxDataItem ITEM_C = new WaxDataItem().setId("C").setName("Item C"); - private Wax wax; - - @Before - public void setUp() { - wax = TestUtils.configureApiClient( - new Wax.Builder(new NetHttpTransport(), new JacksonFactory(), null)).build(); - } - - @Test - public void newSession() throws IOException { - String sessionId = createSession(); - // We just care that this doesn't return an error. - wax.items().list(sessionId).execute(); - } - - @Test - public void newSession_invalidSessionId() throws IOException { - try { - wax.sessions() - .create(new WaxNewSessionRequest().setSessionName("").setDurationInMillis(1L)) - .execute(); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_BAD_REQUEST); - } - } - - @Test - public void removeSession() throws IOException { - String sessionId = createSession(); - // Make sure success is returned, but we don't care what the items are. - wax.items().list(sessionId).execute(); - wax.sessions().remove(sessionId).execute(); - try { - wax.items().list(sessionId); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void removeSession_invalidSession() throws IOException { - try { - wax.sessions().remove("not a real id").execute(); - } catch (GoogleJsonResponseException e) { - // 500 is translated to 503 by default. - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - } - } - - @Test - public void listSessionItems() throws IOException { - String sessionId = createSession(); - WaxDataItemCollection items = wax.items().list(sessionId).execute(); - assertThat(stripMetadata(items.getItems())).containsExactly(ITEM_A, ITEM_B); - } - - @Test - public void listSessionItems_invalidSession() throws IOException { - try { - wax.items().list("not a real id").execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void addSessionItem() throws IOException { - String sessionId = createSession(); - WaxDataItem item = wax.items().insert(sessionId, ITEM_C).execute(); - WaxDataItemCollection items = wax.items().list(sessionId).execute(); - assertThat(stripMetadata(item)).isEqualTo(ITEM_C); - assertThat(stripMetadata(items.getItems())).containsExactly(ITEM_A, ITEM_B, ITEM_C); - } - - @Test - public void addSessionItem_invalidSession() throws IOException { - try { - wax.items().insert("not a real id", ITEM_C).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void addSessionItem_invalidItem() throws IOException { - try { - String sessionId = createSession(); - wax.items().insert(sessionId, ITEM_A).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_BAD_REQUEST); - } - } - - @Test - public void removeSessionItem() throws Exception { - String sessionId = createSession(); - wax.items().delete(sessionId, ITEM_B.getId()).execute(); - WaxDataItemCollection items = wax.items().list(sessionId).execute(); - assertThat(stripMetadata(items.getItems())).containsExactly(ITEM_A); - } - - @Test - public void removeSessionItem_invalidSession() throws IOException { - try { - wax.items().delete("not a real id", ITEM_B.getId()).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void removeSessionItem_invalidItem() throws IOException { - try { - String sessionId = createSession(); - wax.items().delete(sessionId, "not a real id").execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void updateSessionItem() throws IOException { - String sessionId = createSession(); - WaxDataItem newItemB = new WaxDataItem().setId("B").setName("New Item B"); - WaxDataItem item = wax.items().update(sessionId, newItemB.getId(), newItemB).execute(); - WaxDataItemCollection items = wax.items().list(sessionId).execute(); - assertThat(stripMetadata(item)).isEqualTo(newItemB); - assertThat(stripMetadata(items.getItems())).containsExactly(ITEM_A, newItemB); - } - - @Test - public void updateSessionItem_invalidSession() throws IOException { - try { - wax.items().update("not a real id", ITEM_B.getId(), ITEM_B).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void updateSessionItem_invalidItem() throws IOException { - try { - String sessionId = createSession(); - wax.items().update(sessionId, ITEM_C.getId(), ITEM_C).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void updateSessionItem_invalidItemIdChange() throws IOException { - try { - String sessionId = createSession(); - wax.items().update(sessionId, ITEM_B.getId(), ITEM_C).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_BAD_REQUEST); - } - } - - @Test - public void getSessionItem() throws IOException { - String sessionId = createSession(); - WaxDataItem item = wax.items().get(sessionId, ITEM_B.getId()).execute(); - assertThat(stripMetadata(item)).isEqualTo(ITEM_B); - } - - @Test - public void getSessionItem_invalidSession() throws IOException { - try { - wax.items().get("not a real id", ITEM_B.getId()).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - @Test - public void getSessionItem_invalidItem() throws IOException { - try { - String sessionId = createSession(); - wax.items().get(sessionId, ITEM_C.getId()).execute(); - fail("expected exception"); - } catch (GoogleJsonResponseException e) { - assertThatResponseCode(e).isEqualTo(HttpServletResponse.SC_NOT_FOUND); - } - } - - private String createSession() throws IOException { - return wax.sessions() - .create(new WaxNewSessionRequest().setSessionName("test").setDurationInMillis(1L)) - .execute() - .getNewSessionId(); - } - - private static IntegerSubject assertThatResponseCode(GoogleJsonResponseException e) { - return assertThat(e.getStatusCode()); - } - - public List stripMetadata(List items) { - for (WaxDataItem item : items) { - stripMetadata(item); - } - return items; - } - - public WaxDataItem stripMetadata(WaxDataItem item) { - item.remove("kind"); - item.remove("etag"); - return item; - } -} diff --git a/test-utils/src/main/java/com/google/api/server/spi/BaseSystemServiceTest.java b/test-utils/src/main/java/com/google/api/server/spi/BaseSystemServiceTest.java index d108d2e6..d4c61670 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/BaseSystemServiceTest.java +++ b/test-utils/src/main/java/com/google/api/server/spi/BaseSystemServiceTest.java @@ -22,14 +22,11 @@ import static org.mockito.Mockito.times; import com.google.api.server.spi.config.Api; -import com.google.api.server.spi.config.ApiConfigException; import com.google.api.server.spi.config.ApiConfigLoader; import com.google.api.server.spi.config.ApiConfigWriter; import com.google.api.server.spi.config.jsonwriter.JsonConfigWriter; import com.google.api.server.spi.config.model.ApiConfig; import com.google.api.server.spi.config.model.ApiKey; -import com.google.api.server.spi.config.model.ApiMethodConfig; -import com.google.api.server.spi.config.scope.AuthScopeExpressions; import com.google.api.server.spi.config.validation.ApiConfigValidator; import com.google.api.server.spi.request.FakeParamReader; import com.google.api.server.spi.response.ErrorResultWriter; @@ -139,7 +136,9 @@ public void testFindServiceMethod() { @Test public void testOverrideMethod() throws Exception { - assertEquals(String.class, getTestServiceMethod("overrideMethod").getReturnType()); + assertEquals( + com.google.api.server.spi.testing.Foo.class, + getTestServiceMethod("overrideMethod").getReturnType()); } @Test @@ -192,8 +191,8 @@ protected SystemService getSystemService(Object[] services, boolean isIllegalArg boolean enableBackendService) throws Exception { return new SystemService( - new ApiConfigLoader(), new ApiConfigValidator(), "app", new JsonConfigWriter(), services, - isIllegalArgumentBackendError, enableBackendService); + new ApiConfigLoader(), "app", new JsonConfigWriter(), services, + isIllegalArgumentBackendError); } protected abstract TestEndpoint getTestService(); @@ -211,125 +210,6 @@ private static class InnerClasses { @Api private static class TestEndpoint {} } - @Test - public void testResolveAndUpdateServiceConfig() throws Exception { - ApiConfigLoader configLoader = Mockito.spy(new ApiConfigLoader()); - ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); - - SystemService systemService = new SystemService( - configLoader, validator, "app", new JsonConfigWriter(), new Object[] { service }, - false /* isIllegalArgumentBackendError */, false /* enableBackendService */); - - // Force the config loader to return a different config from that used during registration. - ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); - ApiMethodConfig methodConfig = config.getApiClassConfig().getMethods().get( - methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams"))); - methodConfig.setScopeExpression(AuthScopeExpressions.interpret("foo")); - Mockito.doReturn(config).when(configLoader).reloadConfiguration( - Mockito.any(), Mockito.eq(TestEndpoint.class), Mockito.any()); - Mockito.doReturn(false).when(configLoader).isStaticConfig(Mockito.any()); - - assertEquals(methodConfig, - systemService.resolveAndUpdateServiceConfig("TestEndpoint", "getResultNoParams")); - } - - @Test - public void testResolveAndUpdateServiceConfig_noChange() throws Exception { - ApiConfigLoader configLoader = Mockito.spy(new ApiConfigLoader()); - ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); - - ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); - ApiMethodConfig methodConfig = config.getApiClassConfig().getMethods().get( - methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams"))); - - Mockito.doReturn(false).when(configLoader).isStaticConfig(Mockito.any()); - - SystemService systemService = new SystemService( - configLoader, validator, "app", new JsonConfigWriter(), new Object[] { service }, - false /* isIllegalArgumentBackendError */, false /* enableBackendService */); - - assertEquals(methodConfig, - systemService.resolveAndUpdateServiceConfig("TestEndpoint", "getResultNoParams")); - } - - @Test - public void testResolveAndUpdateServiceConfig_staticConfig() throws Exception { - ApiConfigLoader configLoader = Mockito.spy(new ApiConfigLoader()); - ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); - - ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); - ApiMethodConfig methodConfig = config.getApiClassConfig().getMethods().get( - methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams"))); - - ApiConfig alteredConfig = - configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); - ApiMethodConfig alteredMethodConfig = alteredConfig.getApiClassConfig().getMethods().get( - methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams"))); - alteredMethodConfig.setScopeExpression(AuthScopeExpressions.interpret("foo")); - Mockito.doReturn(alteredConfig).when(configLoader).reloadConfiguration( - Mockito.any(), Mockito.eq(TestEndpoint.class), Mockito.any()); - Mockito.doReturn(true).when(configLoader).isStaticConfig(Mockito.any()); - - SystemService systemService = new SystemService( - configLoader, validator, "app", new JsonConfigWriter(), new Object[] { service }, - false /* isIllegalArgumentBackendError */, false /* enableBackendService */); - - assertEquals(methodConfig, - systemService.resolveAndUpdateServiceConfig("TestEndpoint", "getResultNoParams")); - } - - @Test - public void testResolveAndUpdateServiceConfig_badConfig() throws Exception { - ApiConfigLoader configLoader = Mockito.spy(new ApiConfigLoader()); - ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); - - ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); - ApiMethodConfig methodConfig = config.getApiClassConfig().getMethods().get( - methodToEndpointMethod(TestEndpoint.class.getMethod("getResultNoParams"))); - - SystemService systemService = new SystemService( - configLoader, validator, "app", new JsonConfigWriter(), new Object[] { service }, - false /* isIllegalArgumentBackendError */, false /* enableBackendService */); - - Mockito.doThrow(new ApiConfigException("bleh")).when(configLoader).reloadConfiguration( - Mockito.any(), Mockito.eq(TestEndpoint.class), Mockito.any()); - Mockito.doReturn(false).when(configLoader).isStaticConfig(Mockito.any()); - - // Should use previously registered config when new config fails to load. - assertEquals(methodConfig, - systemService.resolveAndUpdateServiceConfig("TestEndpoint", "getResultNoParams")); - } - - @Test - public void testResolveAndUpdateServiceConfig_badConfigAfterGood() throws Exception { - ApiConfigLoader configLoader = Mockito.spy(new ApiConfigLoader()); - ApiConfigValidator validator = Mockito.mock(ApiConfigValidator.class); - - SystemService systemService = new SystemService( - configLoader, validator, "app", new JsonConfigWriter(), new Object[] { service }, - false /* isIllegalArgumentBackendError */, false /* enableBackendService */); - - // Force the config loader to return a different config from that used during registration. - ApiConfig config = configLoader.loadConfiguration(ServiceContext.create(), TestEndpoint.class); - ApiMethodConfig methodConfig = - config.getApiClassConfig().getMethods().get(methodToEndpointMethod( - TestEndpoint.class.getMethod("getResultNoParams"))); - methodConfig.setScopeExpression(AuthScopeExpressions.interpret("foo")); - Mockito.doReturn(config).when(configLoader).reloadConfiguration( - Mockito.any(), Mockito.eq(TestEndpoint.class), Mockito.any()); - Mockito.doReturn(false).when(configLoader).isStaticConfig(Mockito.any()); - - assertEquals(methodConfig, - systemService.resolveAndUpdateServiceConfig("TestEndpoint", "getResultNoParams")); - - Mockito.doThrow(new ApiConfigException("bleh")).when(configLoader).reloadConfiguration( - Mockito.any(), Mockito.eq(TestEndpoint.class), Mockito.any()); - - // Should use previously used config when new config fails to load. - assertEquals(methodConfig, - systemService.resolveAndUpdateServiceConfig("TestEndpoint", "getResultNoParams")); - } - @Test public void testGetApiConfigs() throws Exception { final String apiConfig1 = "api1 configuration"; @@ -356,9 +236,8 @@ public void testGetApiConfigs() throws Exception { .when(configWriter).writeConfig(setOf(config1, config2)); SystemService systemService = - new SystemService(configLoader, configValidator, "app", configWriter, - new Object[] { service, getTestService2() }, false /* isIllegalArgumentBackendError */, - false /* enableBackendService */); + new SystemService(configLoader, "app", configWriter, + new Object[] { service, getTestService2() }, false /* isIllegalArgumentBackendError */); Map configs = systemService.getApiConfigs(); diff --git a/test-utils/src/main/java/com/google/api/server/spi/config/datastore/testing/FakeAsyncMemcacheService.java b/test-utils/src/main/java/com/google/api/server/spi/config/datastore/testing/FakeAsyncMemcacheService.java deleted file mode 100644 index bebd2513..00000000 --- a/test-utils/src/main/java/com/google/api/server/spi/config/datastore/testing/FakeAsyncMemcacheService.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.api.server.spi.config.datastore.testing; - -import com.google.api.server.spi.config.datastore.ApiConfigDatastoreReader; -import com.google.appengine.api.memcache.AsyncMemcacheService; -import com.google.appengine.api.memcache.ErrorHandler; -import com.google.appengine.api.memcache.Expiration; -import com.google.appengine.api.memcache.MemcacheService; -import com.google.appengine.api.memcache.MemcacheService.CasValues; -import com.google.appengine.api.memcache.MemcacheService.IdentifiableValue; -import com.google.appengine.api.memcache.MemcacheService.SetPolicy; -import com.google.appengine.api.memcache.Stats; -import com.google.common.util.concurrent.Futures; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Future; - -/** - * An {@link AsyncMemcacheService} that delegates to a synchronous {@link MemcacheService}. - * - * This is used for testing {@link ApiConfigDatastoreReader}. - */ -@SuppressWarnings("deprecation") -public class FakeAsyncMemcacheService implements AsyncMemcacheService { - - private final MemcacheService memcacheService; - - public FakeAsyncMemcacheService(MemcacheService memcacheService) { - this.memcacheService = memcacheService; - } - - @Override - public String getNamespace() { - return memcacheService.getNamespace(); - } - - @Override - public ErrorHandler getErrorHandler() { - return memcacheService.getErrorHandler(); - } - - @Override - public void setErrorHandler(ErrorHandler handler) { - memcacheService.setErrorHandler(handler); - } - - @Override - public Future clearAll() { - memcacheService.clearAll(); - return Futures.immediateFuture(null); - } - - @Override - public Future contains(Object key) { - return Futures.immediateFuture(memcacheService.contains(key)); - } - - @Override - public Future delete(Object key) { - return Futures.immediateFuture(memcacheService.delete(key)); - } - - @Override - public Future delete(Object key, long millisNoReAdd) { - return Futures.immediateFuture(memcacheService.delete(key, millisNoReAdd)); - } - - @Override - public Future> deleteAll(Collection keys) { - return Futures.immediateFuture(memcacheService.deleteAll(keys)); - } - - @Override - public Future> deleteAll(Collection keys, long millisNoReAdd) { - return Futures.immediateFuture(memcacheService.deleteAll(keys, millisNoReAdd)); - } - - @Override - public Future get(Object key) { - return Futures.immediateFuture(memcacheService.get(key)); - } - - @Override - public Future> getAll(Collection keys) { - return Futures.immediateFuture(memcacheService.getAll(keys)); - } - - @Override - public Future getIdentifiable(Object key) { - return Futures.immediateFuture(memcacheService.getIdentifiable(key)); - } - - @Override - public Future> getIdentifiables(Collection keys) { - return Futures.immediateFuture(memcacheService.getIdentifiables(keys)); - } - - @Override - public Future getStatistics() { - return Futures.immediateFuture(memcacheService.getStatistics()); - } - - @Override - public Future increment(Object key, long delta) { - return Futures.immediateFuture(memcacheService.increment(key, delta)); - } - - @Override - public Future increment(Object key, long delta, Long initialValue) { - return Futures.immediateFuture(memcacheService.increment(key, delta, initialValue)); - } - - @Override - public Future> incrementAll(Map offsets) { - return Futures.immediateFuture(memcacheService.incrementAll(offsets)); - } - - @Override - public Future> incrementAll(Collection keys, long delta) { - return Futures.immediateFuture(memcacheService.incrementAll(keys, delta)); - } - - @Override - public Future> incrementAll(Map offsets, Long initialValue) { - return Futures.immediateFuture(memcacheService.incrementAll(offsets, initialValue)); - } - - @Override - public Future> incrementAll(Collection keys, long delta, Long initialValue) { - return Futures.immediateFuture(memcacheService.incrementAll(keys, delta, initialValue)); - } - - @Override - public Future put(Object key, Object value) { - memcacheService.put(key, value); - return Futures.immediateFuture(null); - } - - @Override - public Future put(Object key, Object value, Expiration expires) { - memcacheService.put(key, value, expires); - return Futures.immediateFuture(null); - } - - @Override - public Future put(Object key, Object value, Expiration expires, SetPolicy policy) { - return Futures.immediateFuture(memcacheService.put(key, value, expires, policy)); - } - - @Override - public Future putAll(Map values) { - memcacheService.putAll(values); - return Futures.immediateFuture(null); - } - - @Override - public Future putAll(Map values, Expiration expires) { - memcacheService.putAll(values, expires); - return Futures.immediateFuture(null); - } - - @Override - public Future> putAll(Map values, Expiration expires, SetPolicy policy) { - return Futures.immediateFuture(memcacheService.putAll(values, expires, policy)); - } - - @Override - public Future> putIfUntouched(Map values) { - return Futures.immediateFuture(memcacheService.putIfUntouched(values)); - } - - @Override - public Future> putIfUntouched(Map values, Expiration expiration) { - return Futures.immediateFuture(memcacheService.putIfUntouched(values, expiration)); - } - - @Override - public Future putIfUntouched(Object key, IdentifiableValue oldValue, Object newValue) { - return Futures.immediateFuture(memcacheService.putIfUntouched(key, oldValue, newValue)); - } - - @Override - public Future putIfUntouched(Object key, IdentifiableValue oldValue, Object newValue, - Expiration expires) { - return Futures.immediateFuture( - memcacheService.putIfUntouched(key, oldValue, newValue, expires)); - } -} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/AbsoluteCommonPathEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/AbsoluteCommonPathEndpoint.java new file mode 100644 index 00000000..b8144384 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/AbsoluteCommonPathEndpoint.java @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; + +/** + * Testing for API methods that have absolute paths. + */ +@Api(name = "absolutepath", version = "v1") +public class AbsoluteCommonPathEndpoint { + @ApiMethod(name = "create", path = "create") + public Foo createFoo() { + return null; + } + + @ApiMethod(name = "absolutepath", path = "/absolutepath/v1/absolutepathmethod") + public void absolutePath() { } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/AbsolutePathEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/AbsolutePathEndpoint.java new file mode 100644 index 00000000..0c88da53 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/AbsolutePathEndpoint.java @@ -0,0 +1,21 @@ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; + +/** + * Testing for API methods that have absolute paths. + */ +@Api(name = "absolutepath", version = "v1") +public class AbsolutePathEndpoint { + @ApiMethod(name = "create", path = "create") + public Foo createFoo() { + return null; + } + + @ApiMethod(name = "absolutepath", path = "/absolutepathmethod/v1") + public void absolutePath() { } + + @ApiMethod(name = "absolutepath2", path = "/absolutepathmethod2/v1") + public void absolutePath2() { } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/ArrayEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/ArrayEndpoint.java index ab8a5e65..d681e637 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/ArrayEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/ArrayEndpoint.java @@ -20,11 +20,12 @@ import com.google.api.server.spi.response.CollectionResponse; import java.util.Collection; +import java.util.List; /** * Test service used for testing array schemas. */ -@Api +@Api(transformers = StringValueTransformer.class) public class ArrayEndpoint { public ArrayEndpoint getArrayService() { @@ -80,4 +81,14 @@ public Integer[] getObjectIntegers() { public CollectionResponse getIntegersResponse() { return null; } + + @ApiMethod(path = "getListOfString") + public ListContainer getListOfString() { + return null; + } + + public static class ListContainer { + public List strings; + } + } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionContravarianceEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionContravarianceEndpoint.java index 1a254900..f03dd20a 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionContravarianceEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionContravarianceEndpoint.java @@ -26,7 +26,7 @@ class BaseCollectionContravarianceEndpoint { @ApiMethod(name = "api.foos.base", path = "base", httpMethod = HttpMethod.GET) - public String foo(List id) { + public Foo foo(List id) { return null; } } @@ -37,7 +37,7 @@ public String foo(List id) { @Api public class CollectionContravarianceEndpoint extends BaseCollectionContravarianceEndpoint { @ApiMethod(name = "api.foos.fn", path = "fn", httpMethod = HttpMethod.GET) - public String foo(@Named("id") Collection id) { + public Foo foo(@Named("id") Collection id) { return null; } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionCovarianceEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionCovarianceEndpoint.java index 0908a045..cc1dad1a 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionCovarianceEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/CollectionCovarianceEndpoint.java @@ -26,7 +26,7 @@ class BaseCollectionCovarianceEndpoint { @ApiMethod(name = "api.foos.base", path = "base", httpMethod = HttpMethod.GET) - public String foo(Collection id) { + public Foo foo(Collection id) { return null; } } @@ -37,7 +37,7 @@ public String foo(Collection id) { @Api public class CollectionCovarianceEndpoint extends BaseCollectionCovarianceEndpoint { @ApiMethod(name = "api.foos.fn", path = "fn", httpMethod = HttpMethod.GET) - public String foo(@Named("id") List id) { + public Foo foo(@Named("id") List id) { return null; } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/CustomScopesEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/CustomScopesEndpoint.java new file mode 100644 index 00000000..8c20ca49 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/CustomScopesEndpoint.java @@ -0,0 +1,25 @@ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; + +@Api( + name = "customScopes", + version = "v1", + scopes = { + "openid", //short scope with description + "https://www.googleapis.com/auth/drive", //long scope with description + "doesnotexist" //should not find a description + }) +public class CustomScopesEndpoint { + @ApiMethod(scopes = "https://mail.google.com/") + public Foo foo() { + return null; + } + @ApiMethod(scopes = "email") + public Bar bar() { + return null; + } + @ApiMethod(scopes = {"email profile", "https://mail.google.com/"}) + public void complexScopeExpression() {} +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/DuplicateMethodEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/DuplicateMethodEndpoint.java index 4c4facdb..ca086bbf 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/DuplicateMethodEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/DuplicateMethodEndpoint.java @@ -28,12 +28,12 @@ @Api public class DuplicateMethodEndpoint { @ApiMethod(name = "api.foos.fn1", path = "fn1", httpMethod = HttpMethod.GET) - public String foo(@Named("id") String id) { + public Foo foo(@Named("id") String id) { return null; } @ApiMethod(name = "api.foos.fn2", path = "fn2", httpMethod = HttpMethod.GET) - public String foo(@Named("id") Integer id) { + public Foo foo(@Named("id") Integer id) { return null; } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpoint.java index 818f6266..0698abcf 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpoint.java @@ -25,8 +25,4 @@ public class EnumEndpoint { public EnumValue create(@Named("value") TestEnum value) { return null; } - - private static class EnumValue { - public TestEnum value; - } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpointV2.java b/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpointV2.java new file mode 100644 index 00000000..d8598c32 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/EnumEndpointV2.java @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; +import com.google.api.server.spi.config.Named; + +@Api(name = "enum", version = "v2") +public class EnumEndpointV2 { + @ApiMethod(name = "create", path = "{value}") + public EnumValue create(@Named("value") TestEnum value) { + return null; + } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/EnumValue.java b/test-utils/src/main/java/com/google/api/server/spi/testing/EnumValue.java new file mode 100644 index 00000000..0bb01e92 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/EnumValue.java @@ -0,0 +1,23 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +/** + * A resource which wraps a test enum. + */ +public class EnumValue { + public TestEnum value; +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/Foo.java b/test-utils/src/main/java/com/google/api/server/spi/testing/Foo.java index 729c5667..921da6bb 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/Foo.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/Foo.java @@ -27,4 +27,11 @@ public String getName() { public int getValue() { return 0; } + + private String getHidden() { + return null; + } + + private void setHidden(String hidden) { + } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/FooDescription.java b/test-utils/src/main/java/com/google/api/server/spi/testing/FooDescription.java new file mode 100644 index 00000000..cd480cdc --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/FooDescription.java @@ -0,0 +1,52 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.ApiResourceProperty; + +/** + * Test resource type with descriptions. + */ +public class FooDescription { + + @ApiResourceProperty(description = "description of name") + private String name; + private int value; + private String hidden; + @ApiResourceProperty(description = "description of choice") + private TestEnumDescription choice; + + public String getName() { + return name; + } + + @ApiResourceProperty(description = "description of value") + public int getValue() { + return value; + } + + private String getHidden() { + return hidden; + } + + private void setHidden(String hidden) { + this.hidden = hidden; + } + + public TestEnumDescription getChoice() { + return choice; + } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/FooDescriptionEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/FooDescriptionEndpoint.java new file mode 100644 index 00000000..7288e029 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/FooDescriptionEndpoint.java @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; +import com.google.api.server.spi.config.ApiMethod.HttpMethod; +import com.google.api.server.spi.config.Description; +import com.google.api.server.spi.config.Named; +import com.google.api.server.spi.config.Nullable; +import com.google.api.server.spi.response.CollectionResponse; + +@Api( + name = "foo", + version = "v1", + audiences = {"audience"}, + title = "The Foo API", + description = "Just Foo Things") +public class FooDescriptionEndpoint { + @ApiMethod(name = "foo.create", description = "create desc", path = "foos/{id}", + httpMethod = HttpMethod.PUT) + public FooDescription createFoo(@Named("id") @Description("id desc") String id, FooDescription foo) { + return null; + } + @ApiMethod(name = "foo.get", description = "get desc", path = "foos/{id}", + httpMethod = HttpMethod.GET) + public FooDescription getFoo(@Named("id") @Description("id desc") String id) { + return null; + } + @ApiMethod(name = "foo.update", description = "update desc", path = "foos/{id}", + httpMethod = HttpMethod.POST) + public FooDescription updateFoo(@Named("id") @Description("id desc") String id, FooDescription foo) { + return null; + } + @ApiMethod(name = "foo.delete", description = "delete desc", path = "foos/{id}", + httpMethod = HttpMethod.DELETE) + public FooDescription deleteFoo(@Named("id") @Description("id desc") String id) { + return null; + } + @ApiMethod(name = "foo.list", description = "list desc", path = "foos", + httpMethod = HttpMethod.GET) + public CollectionResponse listFoos(@Named("n") Integer n, @Nullable @Named("enum") @Description("enum desc") TestEnumDescription testEnum) { + return null; + } + @ApiMethod(name = "toplevel", path = "foos", httpMethod = HttpMethod.POST) + public CollectionResponse toplevel() { + return null; + } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/FooEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/FooEndpoint.java index 7abbecd4..73b64782 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/FooEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/FooEndpoint.java @@ -22,7 +22,14 @@ import com.google.api.server.spi.config.Named; import com.google.api.server.spi.response.CollectionResponse; -@Api(name = "foo", version = "v1", audiences = {"audience"}) +@Api( + name = "foo", + version = "v1", + audiences = {"audience"}, + title = "The Foo API", + description = "Just Foo Things", + documentationLink = "https://example.com", + canonicalName = "CanonicalName") public class FooEndpoint { @ApiMethod(name = "foo.create", description = "create desc", path = "foos/{id}", httpMethod = HttpMethod.PUT) diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/LimitMetricsEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/LimitMetricsEndpoint.java new file mode 100644 index 00000000..1fa1c43d --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/LimitMetricsEndpoint.java @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiLimitMetric; +import com.google.api.server.spi.config.ApiMethod; +import com.google.api.server.spi.config.ApiMetricCost; + +/** + * Testing for API methods that have absolute paths. + */ +@Api( + name = "limits", + version = "v1", + limitDefinitions = { + @ApiLimitMetric( + name = "read", + displayName = "Read requests", + limit = 100), + @ApiLimitMetric( + name = "write", + limit = 10), + }) +public class LimitMetricsEndpoint { + @ApiMethod( + name = "create", + path = "create", + metricCosts = {@ApiMetricCost(name = "write", cost = 5)}) + public Foo createFoo() { + return null; + } + + @ApiMethod( + name = "custom", + metricCosts = { + @ApiMetricCost(name = "read", cost = 1), + @ApiMetricCost(name = "write", cost = 2) + }) + public void customFoo() { } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/MapEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/MapEndpoint.java new file mode 100644 index 00000000..02e24fc1 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/MapEndpoint.java @@ -0,0 +1,121 @@ +/* + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; +import com.google.api.server.spi.config.ApiResourceProperty; +import com.google.api.server.spi.types.DateAndTime; + +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Test service used for testing map schemas. + */ +@Api(transformers = StringValueTransformer.class) +public class MapEndpoint { + + public static class MapSubclass extends HashMap { } + + public MapEndpoint getMapService() { + return null; + } + + public Map getStringMap() { + return null; + } + + public Map getIntMap() { + return null; + } + + public Map getFooMap() { + return null; + } + + public Map getBazMap() { + return null; + } + + public Map> getFooMapMap() { + return null; + } + + public Map getStringValueMap() { + return null; + } + + public MapSubclass getMapSubclass() { + return null; + } + + @ApiMethod(path = "getMapOfStrings") + public MapContainer getMapOfStrings() { + return null; + } + + public static class MapContainer { + @ApiResourceProperty(description = "A map of string values") + public Map stringMap; + } + + //Keys that can be converted from / to String generate schema with additionalProperties + + public Map getEnumKeyMap() { + return null; + } + + public Map getBooleanKeyMap() { + return null; + } + + public Map getIntKeyMap() { + return null; + } + + public Map getLongKeyMap() { + return null; + } + + public Map getFloatKeyMap() { + return null; + } + + public Map getDateKeyMap() { + return null; + } + + @ApiMethod(path = "getDateTimeKeyMap") + public Map getDateTimeKeyMap() { + return null; + } + + //Maps with array-like values generate a JsonMap schema (not supported by API client generator) + //unless activated with EndpointsFlag.SUPPORT_ARRAYS_VALUES + + public Map getStringArrayMap() { + return null; + } + + @ApiMethod(path = "getStringCollectionMap") + public Map> getStringCollectionMap() { + return null; + } + +} diff --git a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/SystemServiceModule.java b/test-utils/src/main/java/com/google/api/server/spi/testing/MapEndpointInvalid.java similarity index 54% rename from endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/SystemServiceModule.java rename to test-utils/src/main/java/com/google/api/server/spi/testing/MapEndpointInvalid.java index b6cf3ae4..856c389d 100644 --- a/endpoints-framework-guice/src/main/java/com/google/api/server/spi/guice/SystemServiceModule.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/MapEndpointInvalid.java @@ -13,27 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.google.api.server.spi.guice; +package com.google.api.server.spi.testing; -import com.google.inject.AbstractModule; - -import java.util.Set; +import com.google.api.server.spi.config.Api; +import java.util.Map; /** - * Configures bindings needed for system service integration. - * - * @author Joe Catalano + * Test service used for testing Map schemas with invalid key. */ -@Deprecated -public abstract class SystemServiceModule extends AbstractModule { +@Api +public class MapEndpointInvalid { - @Override - protected void configure() { - bind(ServiceMap.class).toInstance(ServiceMap.create(binder(), getServiceClasses())); + public Map getInvalidKeyMap() { + return null; } - /** - * Gets the service classes of the system services. - */ - protected abstract Set> getServiceClasses(); } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/MultiResourceEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/MultiResourceEndpoint.java new file mode 100644 index 00000000..abeef71f --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/MultiResourceEndpoint.java @@ -0,0 +1,47 @@ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiClass; +import com.google.api.server.spi.config.ApiMethod; + +public class MultiResourceEndpoint { + + @Api( + name = "multiresource", + version = "v1") + public static class NoResourceEndpoint { + + @ApiMethod(path = "noresource") + public Foo get() { + return null; + } + + } + + @Api( + name = "multiresource", + version = "v1") + @ApiClass(resource = "resource1") + public static class Resource1Endpoint { + + @ApiMethod(path = "resource1") + public Foo get() { + return null; + } + + } + + @Api( + name = "multiresource", + version = "v1") + @ApiClass(resource = "resource2") + public static class Resource2Endpoint { + + @ApiMethod(path = "resource2") + public Foo get() { + return null; + } + + } + +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/MultiVersionEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/MultiVersionEndpoint.java new file mode 100644 index 00000000..a385b116 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/MultiVersionEndpoint.java @@ -0,0 +1,31 @@ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiClass; +import com.google.api.server.spi.config.ApiMethod; + +public class MultiVersionEndpoint { + + @Api( + name = "myapi", + version = "v1") + public static class Version1Endpoint { + + public Foo get() { + return null; + } + + } + + @Api( + name = "myapi", + version = "v2") + public static class Version2Endpoint { + + public Foo get() { + return null; + } + + } + +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/MultipleParameterEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/MultipleParameterEndpoint.java index c2425430..16e29a93 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/MultipleParameterEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/MultipleParameterEndpoint.java @@ -3,6 +3,7 @@ import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.Named; +import com.google.api.server.spi.config.Nullable; /** * This endpoint is used for testing that named parameters are output in order. @@ -10,5 +11,10 @@ @Api(name = "multipleparam", version = "v1") public class MultipleParameterEndpoint { @ApiMethod(name = "param", path = "param/{parent}/{child}") - public void param(@Named("parent") String parent, @Named("child") String child) { } + public void param( + @Named("parent") String parent, + @Named("query") @Nullable String query, + @Named("child") String child, + @Named("queryb") String queryB, + @Named("querya") String queryA) { } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/NonDiscoverableEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/NonDiscoverableEndpoint.java new file mode 100644 index 00000000..13531a99 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/NonDiscoverableEndpoint.java @@ -0,0 +1,65 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.AnnotationBoolean; +import com.google.api.server.spi.config.Api; +import com.google.api.server.spi.config.ApiMethod; +import com.google.api.server.spi.config.ApiMethod.HttpMethod; +import com.google.api.server.spi.config.Description; +import com.google.api.server.spi.config.Named; +import com.google.api.server.spi.response.CollectionResponse; + +@Api( + name = "foo", + version = "v1", + audiences = {"audience"}, + title = "The Foo API", + description = "Just Foo Things", + documentationLink = "https://example.com", + canonicalName = "CanonicalName", + discoverable = AnnotationBoolean.FALSE) +public class NonDiscoverableEndpoint { + @ApiMethod(name = "foo.create", description = "create desc", path = "foos/{id}", + httpMethod = HttpMethod.PUT) + public Foo createFoo(@Named("id") @Description("id desc") String id, Foo foo) { + return null; + } + @ApiMethod(name = "foo.get", description = "get desc", path = "foos/{id}", + httpMethod = HttpMethod.GET) + public Foo getFoo(@Named("id") @Description("id desc") String id) { + return null; + } + @ApiMethod(name = "foo.update", description = "update desc", path = "foos/{id}", + httpMethod = HttpMethod.POST) + public Foo updateFoo(@Named("id") @Description("id desc") String id, Foo foo) { + return null; + } + @ApiMethod(name = "foo.delete", description = "delete desc", path = "foos/{id}", + httpMethod = HttpMethod.DELETE) + public Foo deleteFoo(@Named("id") @Description("id desc") String id) { + return null; + } + @ApiMethod(name = "foo.list", description = "list desc", path = "foos", + httpMethod = HttpMethod.GET) + public CollectionResponse listFoos(@Named("n") Integer n) { + return null; + } + @ApiMethod(name = "toplevel", path = "foos", httpMethod = HttpMethod.POST) + public CollectionResponse toplevel() { + return null; + } +} \ No newline at end of file diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleContravarianceEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleContravarianceEndpoint.java index 5d74c1eb..8178c353 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleContravarianceEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleContravarianceEndpoint.java @@ -21,7 +21,7 @@ class BaseSimpleContravarianceEndpoint { @ApiMethod(name = "api.foos.base", path = "base", httpMethod = HttpMethod.GET) - public String foo(Number id) { + public Foo foo(Number id) { return null; } } @@ -32,7 +32,7 @@ public String foo(Number id) { @Api public class SimpleContravarianceEndpoint extends BaseSimpleContravarianceEndpoint { @ApiMethod(name = "api.foos.fn", path = "fn", httpMethod = HttpMethod.GET) - public String foo(Object id) { + public Foo foo(Object id) { return null; } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleCovarianceEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleCovarianceEndpoint.java index 0c73b5e1..6429d769 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleCovarianceEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleCovarianceEndpoint.java @@ -23,7 +23,7 @@ class BaseSimpleCovarianceEndpoint { @ApiMethod(name = "api.foos.base", path = "base", httpMethod = HttpMethod.GET) - public String foo(Object id) { + public Foo foo(Object id) { return null; } } @@ -34,7 +34,7 @@ public String foo(Object id) { @Api public class SimpleCovarianceEndpoint extends BaseSimpleCovarianceEndpoint { @ApiMethod(name = "api.foos.fn", path = "fn", httpMethod = HttpMethod.GET) - public String foo(@Named("id") String id) { + public Foo foo(@Named("id") String id) { return null; } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleOverloadEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleOverloadEndpoint.java index d1a3c2e4..6bf6fdac 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleOverloadEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/SimpleOverloadEndpoint.java @@ -23,7 +23,7 @@ class BaseSimpleOverloadEndpoint { @ApiMethod(name = "api.foos.base", path = "base", httpMethod = HttpMethod.GET) - public String foo(@Named("id") String id) { + public Foo foo(@Named("id") String id) { return null; } } @@ -34,7 +34,7 @@ public String foo(@Named("id") String id) { @Api public class SimpleOverloadEndpoint extends BaseSimpleOverloadEndpoint { @ApiMethod(name = "api.foos.fn", path = "fn", httpMethod = HttpMethod.GET) - public String foo(@Named("id") Integer id) { + public Foo foo(@Named("id") Integer id) { return null; } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/StringValue.java b/test-utils/src/main/java/com/google/api/server/spi/testing/StringValue.java new file mode 100644 index 00000000..1b534cb7 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/StringValue.java @@ -0,0 +1,20 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +public class StringValue { + public String value; +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/StringValueTransformer.java b/test-utils/src/main/java/com/google/api/server/spi/testing/StringValueTransformer.java new file mode 100644 index 00000000..b45300a2 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/StringValueTransformer.java @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Transformer; + +public class StringValueTransformer implements Transformer { + @Override + public String transformTo(StringValue in) { + return null; + } + + @Override + public StringValue transformFrom(String in) { + return null; + } +} diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpoint.java b/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpoint.java index bc96926a..97ce8f1d 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpoint.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpoint.java @@ -36,7 +36,7 @@ * Endpoint class for testing. */ @Api -public class TestEndpoint extends TestEndpointSuperclass { +public class TestEndpoint extends TestEndpointSuperclass { public static final String NAME_DATE = "date"; public static final String NAME_DATE_AND_TIME = "dateandtime"; @@ -52,18 +52,26 @@ public class TestEndpoint extends TestEndpointSuperclass { public static final String NAME_FLOAT_OBJECT = "Float"; public static final String NAME_DOUBLE_OBJECT = "Double"; public static final String NAME_ENUM = "enum"; - public static final String RESULT = "result"; + public static final Foo RESULT = new Foo(); public static final String ERROR_MESSAGE = "error message"; public static class Request { private String string; - private final Integer integer = -1; + private Integer integer = -1; - public String getString() { + public void setStringValue(String string) { + this.string = string; + } + + public void setIntegerValue(int integer) { + this.integer = integer; + } + + public String getStringValue() { return string; } - public Integer getInteger() { + public Integer getIntegerValue() { return integer; } } @@ -72,7 +80,7 @@ public enum TestEnum { TEST1, TEST2 } - public String succeed(@Named(NAME_STRING) String s, @Named(NAME_BOOLEAN) boolean b1, + public Foo succeed(@Named(NAME_STRING) String s, @Named(NAME_BOOLEAN) boolean b1, @Named(NAME_INTEGER) int i1, @Named(NAME_LONG) long l1, @Named(NAME_FLOAT) float f1, @Named(NAME_DOUBLE) double d1, @Named(NAME_BOOLEAN_OBJECT) Boolean b2, @Named(NAME_INTEGER_OBJECT) Integer i2, @Named(NAME_LONG_OBJECT) Long l2, @@ -82,46 +90,46 @@ public String succeed(@Named(NAME_STRING) String s, @Named(NAME_BOOLEAN) boolean return RESULT; } - public String getDate(@Named(NAME_DATE) Date date) { + public Foo getDate(@Named(NAME_DATE) Date date) { return RESULT; } @ApiMethod(path = "dateandtime") - public String getDateAndTime(@Named(NAME_DATE_AND_TIME) DateAndTime dateTime) { + public Foo getDateAndTime(@Named(NAME_DATE_AND_TIME) DateAndTime dateTime) { return RESULT; } @ApiMethod(path = "simpledate") - public String getSimpleDate(@Named(NAME_DATE_AND_TIME) SimpleDate simpleDate) { + public Foo getSimpleDate(@Named(NAME_DATE_AND_TIME) SimpleDate simpleDate) { return RESULT; } @ApiMethod(path = "noresults") - public String getResultNoParams() { + public Foo getResultNoParams() { return RESULT; } - public String fail(@Named(NAME_STRING) String p0, @Named(NAME_INTEGER) int p1, Request request, + public Foo fail(@Named(NAME_STRING) String p0, @Named(NAME_INTEGER) int p1, Request request, User p2, HttpServletRequest httpRequest) throws BadRequestException { throw new BadRequestException(ERROR_MESSAGE); } - public String failOAuth(@Named(NAME_STRING) String p0, @Named(NAME_INTEGER) int p1, + public Foo failOAuth(@Named(NAME_STRING) String p0, @Named(NAME_INTEGER) int p1, Request request, User p2, HttpServletRequest httpRequest) throws OAuthRequestException { throw new OAuthRequestException(ERROR_MESSAGE); } - public String failWrapped() throws Exception { + public Foo failWrapped() throws Exception { throw new Exception(null, new ServiceException(401, ERROR_MESSAGE)); } - public String failIllegalArgumentException() { + public Foo failIllegalArgumentException() { throw new IllegalArgumentException(); } - public void doSomething(byte[] in) {} + public void doSomething(@Named("bytes") byte[] in) {} - public void doBlob(Blob b) {} + public void doBlob(@Named("blob") Blob b) {} public void doParameterizedOverloadTest(Map m) {} @@ -130,7 +138,7 @@ public void doMap(Map m) {} public void doEnum(@Named(NAME_ENUM) TestEnum e) {} @Override - public String overrideMethod(@Named(NAME_STRING) String s) { + public Foo overrideMethod(Foo s) { return null; } @@ -138,8 +146,8 @@ public String overrideMethod(@Named(NAME_STRING) String s) { public void overrideMethod1() {} @Override - public boolean overrideMethod2(@Named(NAME_BOOLEAN) boolean bleh) { - return true; + public Foo overrideMethod2(@Named(NAME_BOOLEAN) boolean bleh) { + return null; } public static Map staticMethod() { diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpointSuperclass.java b/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpointSuperclass.java index 7ca854ae..86c2b2c9 100644 --- a/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpointSuperclass.java +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/TestEndpointSuperclass.java @@ -30,7 +30,7 @@ public T overrideMethod(T param) { public void overrideMethod1() {} - public boolean overrideMethod2(boolean bleh) { - return false; + public Foo overrideMethod2(boolean bleh) { + return null; } } diff --git a/test-utils/src/main/java/com/google/api/server/spi/testing/TestEnumDescription.java b/test-utils/src/main/java/com/google/api/server/spi/testing/TestEnumDescription.java new file mode 100644 index 00000000..f49941c8 --- /dev/null +++ b/test-utils/src/main/java/com/google/api/server/spi/testing/TestEnumDescription.java @@ -0,0 +1,27 @@ +/* + * Copyright 2018 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.api.server.spi.testing; + +import com.google.api.server.spi.config.Description; + +public enum TestEnumDescription { + @Description("description of value1") + VALUE1, + @Description("description of value2") + VALUE2; + + public String notAConstant; +}