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 extends Class>> 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 extends Class>> 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 extends PeerAuthenticator> 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 extends PeerAuthenticator> clazz) {
+ return INSTANTIATOR.getInstanceOrDefault(clazz);
+ }
private final HttpServletRequest request;
private final Attribute attr;
@@ -78,7 +50,7 @@ public PeerAuthenticator apply(Class extends PeerAuthenticator> 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 extends Class>> 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 super T> 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 extends Annotation> 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 extends A> 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 extends A> 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:
+ *
+ * Set system property {@link EndpointsFlag#systemPropertyName} (defined as
+ * "endpoints." + systemPropertySuffix) to any value except a false-y one
+ * Set env variable {@link EndpointsFlag#envVarName} (defined as "ENDPOINTS_"
+ * + name()) to any value except a falsy one
+ *
+ *
+ * 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 extends Authenticator> 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 extends Authenticator> clazz) {
+ return INSTANTIATOR.getInstanceOrDefault(clazz);
+ }
private final HttpServletRequest request;
private final Attribute attr;
@@ -74,7 +52,7 @@ public Authenticator apply(Class extends Authenticator> 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.