diff --git a/appengine-java-logging/src/main/java/com/google/apphosting/logging/JsonFormatter.java b/appengine-java-logging/src/main/java/com/google/apphosting/logging/JsonFormatter.java index 9fec754..9951785 100644 --- a/appengine-java-logging/src/main/java/com/google/apphosting/logging/JsonFormatter.java +++ b/appengine-java-logging/src/main/java/com/google/apphosting/logging/JsonFormatter.java @@ -28,95 +28,99 @@ * properties that App Engine expects. */ public class JsonFormatter extends Formatter { - @Override - public String format(LogRecord record) { - Instant timestamp = Instant.ofEpochMilli(record.getMillis()); - StringWriter out = new StringWriter(); + @Override + public String format(LogRecord record) { + Instant timestamp = Instant.ofEpochMilli(record.getMillis()); + StringWriter out = new StringWriter(); - // Write using a simple JsonWriter rather than the more sophisticated Gson as we generally - // will not need to serialize complex objects that require introspection and reflection. - try (JsonWriter writer = new JsonWriter(out)) { - writer.setSerializeNulls(false); - writer.setHtmlSafe(false); + // Write using a simple JsonWriter rather than the more sophisticated Gson as we generally + // will not need to serialize complex objects that require introspection and reflection. + try (JsonWriter writer = new JsonWriter(out)) { + writer.setSerializeNulls(false); + writer.setHtmlSafe(false); - writer.beginObject(); - writer.name("timestamp") - .beginObject() - .name("seconds").value(timestamp.getEpochSecond()) - .name("nanos").value(timestamp.getNano()) - .endObject(); - writer.name("severity").value(severity(record.getLevel())); - writer.name("thread").value(Thread.currentThread().getName()); - writer.name("message").value(formatMessage(record)); + writer.beginObject(); + writer + .name("timestamp") + .beginObject() + .name("seconds") + .value(timestamp.getEpochSecond()) + .name("nanos") + .value(timestamp.getNano()) + .endObject(); + writer.name("severity").value(severity(record.getLevel())); + writer.name("thread").value(Thread.currentThread().getName()); + writer.name("message").value(formatMessage(record)); - // If there is a LogContext associated with this thread then add its properties. - LogContext logContext = LogContext.current(); - if (logContext != null) { - logContext.forEach((name, value) -> { - try { - writer.name(name); - if (value == null) { - writer.nullValue(); - } else if (value instanceof Boolean) { - writer.value((boolean) value); - } else if (value instanceof Number) { - writer.value((Number) value); - } else { - writer.value(value.toString()); - } - } catch (IOException e) { - // Should not happen as StringWriter does not throw IOException - throw new AssertionError(e); - } - }); - } - writer.endObject(); - } catch (IOException e) { - // Should not happen as StringWriter does not throw IOException - throw new AssertionError(e); - } - out.append(System.lineSeparator()); - return out.toString(); + // If there is a LogContext associated with this thread then add its properties. + LogContext logContext = LogContext.current(); + if (logContext != null) { + logContext.forEach( + (name, value) -> { + try { + writer.name(name); + if (value == null) { + writer.nullValue(); + } else if (value instanceof Boolean) { + writer.value((boolean) value); + } else if (value instanceof Number) { + writer.value((Number) value); + } else { + writer.value(value.toString()); + } + } catch (IOException e) { + // Should not happen as StringWriter does not throw IOException + throw new AssertionError(e); + } + }); + } + writer.endObject(); + } catch (IOException e) { + // Should not happen as StringWriter does not throw IOException + throw new AssertionError(e); } + out.append(System.lineSeparator()); + return out.toString(); + } - @Override - public synchronized String formatMessage(LogRecord record) { - StringBuilder sb = new StringBuilder(); - if (record.getSourceClassName() != null) { - sb.append(record.getSourceClassName()); - } else { - sb.append(record.getLoggerName()); - } - if (record.getSourceMethodName() != null) { - sb.append(' '); - sb.append(record.getSourceMethodName()); - } - sb.append(": "); - sb.append(super.formatMessage(record)); - Throwable thrown = record.getThrown(); - if (thrown != null) { - StringWriter sw = new StringWriter(); - try (PrintWriter pw = new PrintWriter(sw);) { - sb.append("\n"); - thrown.printStackTrace(pw); - } - sb.append(sw.getBuffer()); - } - return sb.toString(); + @Override + public synchronized String formatMessage(LogRecord record) { + StringBuilder sb = new StringBuilder(); + if (record.getSourceClassName() != null) { + sb.append(record.getSourceClassName()); + } else { + sb.append(record.getLoggerName()); } + if (record.getSourceMethodName() != null) { + sb.append(' '); + sb.append(record.getSourceMethodName()); + } + sb.append(": "); + sb.append(super.formatMessage(record)); + Throwable thrown = record.getThrown(); + if (thrown != null) { + StringWriter sw = new StringWriter(); + try (PrintWriter pw = new PrintWriter(sw); ) { + sb.append("\n"); + thrown.printStackTrace(pw); + } + sb.append(sw.getBuffer()); + } + return sb.toString(); + } - private static String severity(Level level) { - int intLevel = level.intValue(); + private static String severity(Level level) { + int intLevel = level.intValue(); - if (intLevel >= Level.SEVERE.intValue()) { - return "ERROR"; - } else if (intLevel >= Level.WARNING.intValue()) { - return "WARNING"; - } else if (intLevel >= Level.INFO.intValue()) { - return "INFO"; - } else { - // There's no trace, so we'll map everything below this to debug. - return "DEBUG"; - } + if (intLevel >= Level.SEVERE.intValue()) { + return "ERROR"; + } else if (intLevel >= Level.WARNING.intValue()) { + return "WARNING"; + } else if (intLevel >= Level.INFO.intValue()) { + return "INFO"; + } else { + // There's no trace, so we'll map everything below this to debug. + return "DEBUG"; } + } } diff --git a/appengine-java-logging/src/main/java/com/google/apphosting/logging/LogContext.java b/appengine-java-logging/src/main/java/com/google/apphosting/logging/LogContext.java index 41efd13..401fe69 100644 --- a/appengine-java-logging/src/main/java/com/google/apphosting/logging/LogContext.java +++ b/appengine-java-logging/src/main/java/com/google/apphosting/logging/LogContext.java @@ -25,20 +25,19 @@ *

This is an implementation of a Mapped Diagnostic Context for use with the java.util.logging * framework. */ -public class LogContext extends ConcurrentHashMap{ +public class LogContext extends ConcurrentHashMap { - private static final ThreadLocal threadContext = new ThreadLocal() - { - @Override - protected LogContext initialValue() { - return new LogContext(); - } - }; + private static final ThreadLocal threadContext = + new ThreadLocal() { + @Override + protected LogContext initialValue() { + return new LogContext(); + } + }; private final Map values = new ConcurrentHashMap<>(); - private LogContext() { - } + private LogContext() {} /** * Returns the log context associated with the current Thread. @@ -79,5 +78,4 @@ public T get(String name, Class type) { public Stream> stream() { return values.entrySet().stream(); } - } diff --git a/appengine-java-logging/src/test/java/com/google/apphosting/logging/JsonFormatterTest.java b/appengine-java-logging/src/test/java/com/google/apphosting/logging/JsonFormatterTest.java index 74d1dc1..df1d645 100644 --- a/appengine-java-logging/src/test/java/com/google/apphosting/logging/JsonFormatterTest.java +++ b/appengine-java-logging/src/test/java/com/google/apphosting/logging/JsonFormatterTest.java @@ -27,73 +27,76 @@ public class JsonFormatterTest { - private JsonFormatter formatter = new JsonFormatter(); + private JsonFormatter formatter = new JsonFormatter(); - @Test - public void formatProducesExpectedJsonData() throws Exception { - LogRecord record = new LogRecord(Level.INFO, "message"); - record.setMillis(12345_678); - record.setLoggerName("logger"); - LogContext.current().put("traceId", "abcdef"); + @Test + public void formatProducesExpectedJsonData() throws Exception { + LogRecord record = new LogRecord(Level.INFO, "message"); + record.setMillis(12345_678); + record.setLoggerName("logger"); + LogContext.current().put("traceId", "abcdef"); - String logLine = formatter.format(record); - assertThat(logLine, endsWith(System.lineSeparator())); + String logLine = formatter.format(record); + assertThat(logLine, endsWith(System.lineSeparator())); - JsonData data = new Gson().fromJson(logLine, JsonData.class); - assertEquals("INFO", data.severity); - assertEquals(12345, data.timestamp.seconds); - assertEquals(678_000_000, data.timestamp.nanos); - assertEquals(Thread.currentThread().getName(), data.thread); - assertEquals("logger: message", data.message); - assertEquals("abcdef", data.traceId); - } + JsonData data = new Gson().fromJson(logLine, JsonData.class); + assertEquals("INFO", data.severity); + assertEquals(12345, data.timestamp.seconds); + assertEquals(678_000_000, data.timestamp.nanos); + assertEquals(Thread.currentThread().getName(), data.thread); + assertEquals("logger: message", data.message); + assertEquals("abcdef", data.traceId); + } - @Test - public void messageIncludesLoggerName() throws Exception { - LogRecord record = new LogRecord(Level.INFO, "message"); - record.setLoggerName("logger"); - assertEquals("logger: message", formatter.formatMessage(record)); - } + @Test + public void messageIncludesLoggerName() throws Exception { + LogRecord record = new LogRecord(Level.INFO, "message"); + record.setLoggerName("logger"); + assertEquals("logger: message", formatter.formatMessage(record)); + } - @Test - public void messageIncludesClassName() throws Exception { - LogRecord record = new LogRecord(Level.INFO, "message"); - record.setSourceClassName("class"); - record.setLoggerName("logger"); - assertEquals("class: message", formatter.formatMessage(record)); - } + @Test + public void messageIncludesClassName() throws Exception { + LogRecord record = new LogRecord(Level.INFO, "message"); + record.setSourceClassName("class"); + record.setLoggerName("logger"); + assertEquals("class: message", formatter.formatMessage(record)); + } - @Test - public void messageIncludesMethodName() throws Exception { - LogRecord record = new LogRecord(Level.INFO, "message"); - record.setSourceClassName("class"); - record.setSourceMethodName("method"); - assertEquals("class method: message", formatter.formatMessage(record)); - } + @Test + public void messageIncludesMethodName() throws Exception { + LogRecord record = new LogRecord(Level.INFO, "message"); + record.setSourceClassName("class"); + record.setSourceMethodName("method"); + assertEquals("class method: message", formatter.formatMessage(record)); + } - @Test - public void messageIncludesStackTrace() throws Exception { - LogRecord record = new LogRecord(Level.INFO, "message"); - record.setLoggerName("logger"); - record.setThrown(new Throwable("thrown").fillInStackTrace()); - String message = formatter.formatMessage(record); - BufferedReader reader = new BufferedReader(new StringReader(message)); - assertEquals("logger: message", reader.readLine()); - assertEquals("java.lang.Throwable: thrown", reader.readLine()); - assertTrue(reader.readLine() - .startsWith("\tat " + getClass().getName() + ".messageIncludesStackTrace")); - } + @Test + public void messageIncludesStackTrace() throws Exception { + LogRecord record = new LogRecord(Level.INFO, "message"); + record.setLoggerName("logger"); + record.setThrown(new Throwable("thrown").fillInStackTrace()); + String message = formatter.formatMessage(record); + BufferedReader reader = new BufferedReader(new StringReader(message)); + assertEquals("logger: message", reader.readLine()); + assertEquals("java.lang.Throwable: thrown", reader.readLine()); + assertTrue( + reader + .readLine() + .startsWith("\tat " + getClass().getName() + ".messageIncludesStackTrace")); + } - // Something that JSON can parser the JSON into - public static class JsonData { - public static class LogTimestamp { - public long seconds; - public long nanos; - } - public LogTimestamp timestamp; - public String severity; - public String thread; - public String message; - public String traceId; + // Something that JSON can parser the JSON into + public static class JsonData { + public static class LogTimestamp { + public long seconds; + public long nanos; } -} \ No newline at end of file + + public LogTimestamp timestamp; + public String severity; + public String thread; + public String message; + public String traceId; + } +} diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DatastoreSessionStore.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DatastoreSessionStore.java index c8c898d..a5d8106 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DatastoreSessionStore.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DatastoreSessionStore.java @@ -1,19 +1,18 @@ /** * Copyright 2011 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.apphosting.runtime; import static com.google.apphosting.runtime.SessionManagerUtil.deserialize; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DeferredDatastoreSessionStore.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DeferredDatastoreSessionStore.java index 5bb3031..ea11203 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DeferredDatastoreSessionStore.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/DeferredDatastoreSessionStore.java @@ -1,19 +1,18 @@ /** * Copyright 2011 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.apphosting.runtime; import static com.google.appengine.api.taskqueue.RetryOptions.Builder.withTaskAgeLimitSeconds; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/MemcacheSessionStore.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/MemcacheSessionStore.java index 619f87e..93eda41 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/MemcacheSessionStore.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/MemcacheSessionStore.java @@ -1,20 +1,18 @@ /** * Copyright 2011 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.apphosting.runtime; import static com.google.apphosting.runtime.SessionManagerUtil.deserialize; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionData.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionData.java index 5d01f32..e346e08 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionData.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionData.java @@ -1,20 +1,18 @@ /** * Copyright 2009 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.apphosting.runtime; import java.util.HashMap; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionManagerUtil.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionManagerUtil.java index fe2d801..bc0329b 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionManagerUtil.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionManagerUtil.java @@ -1,20 +1,18 @@ /** * Copyright 2012 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.apphosting.runtime; import java.io.ByteArrayInputStream; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionStore.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionStore.java index 4443f95..90ed30f 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionStore.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/SessionStore.java @@ -1,19 +1,18 @@ /** * Copyright 2011 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.apphosting.runtime; import java.util.Map; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/AbstractIntervalTimer.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/AbstractIntervalTimer.java index 3e7f71d..c591bb4 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/AbstractIntervalTimer.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/AbstractIntervalTimer.java @@ -1,20 +1,18 @@ /** * Copyright 2007 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.apphosting.runtime.timer; /** diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/Timer.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/Timer.java index 7f47d35..68c9849 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/Timer.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/runtime/timer/Timer.java @@ -1,20 +1,18 @@ /** * Copyright 2007 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.apphosting.runtime.timer; public interface Timer { diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineConfigException.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineConfigException.java index 42d1de8..128eb3b 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineConfigException.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineConfigException.java @@ -1,19 +1,18 @@ /** * Copyright 2008 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.apphosting.utils.config; /** diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXml.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXml.java index c0d8a2a..04ad607 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXml.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXml.java @@ -41,7 +41,11 @@ public class AppEngineWebXml implements Cloneable { /** * Enumeration of supported scaling types. */ - public static enum ScalingType {AUTOMATIC, MANUAL, BASIC} + public static enum ScalingType { + AUTOMATIC, + MANUAL, + BASIC + } // System properties defined by the application in appengine-web.xml private final Map systemProperties = Maps.newHashMap(); @@ -64,7 +68,7 @@ public static enum ScalingType {AUTOMATIC, MANUAL, BASIC} public static final String WARMUP_SERVICE = "warmup"; public static final String URL_HANDLER_URLFETCH = "urlfetch"; - public static final String URL_HANDLER_NATIVE= "native"; + public static final String URL_HANDLER_NATIVE = "native"; private String appId; @@ -359,8 +363,8 @@ public void excludeResourcePattern(String url) { public void addUserPermission(String className, String name, String actions) { if (className.startsWith("java.")) { - throw new AppEngineConfigException("Cannot specify user-permissions for " + - "classes in java.* packages."); + throw new AppEngineConfigException( + "Cannot specify user-permissions for " + "classes in java.* packages."); } userPermissions.add(new UserPermission(className, name, actions)); @@ -369,22 +373,20 @@ public void addUserPermission(String className, String name, String actions) { public Permissions getUserPermissions() { Permissions permissions = new Permissions(); for (UserPermission permission : userPermissions) { - permissions.add(new UnresolvedPermission(permission.getClassName(), - permission.getName(), - permission.getActions(), - null)); + permissions.add( + new UnresolvedPermission( + permission.getClassName(), permission.getName(), permission.getActions(), null)); } permissions.setReadOnly(); return permissions; } - public void setPublicRoot(String root) { if (root.indexOf('*') != -1) { throw new AppEngineConfigException("public-root cannot contain wildcards"); } if (root.endsWith("/")) { - root = root.substring(0, root.length() - 1); + root = root.substring(0, root.length() - 1); } if (root.length() > 0 && !root.startsWith("/")) { root = "/" + root; @@ -520,8 +522,12 @@ public void setUrlStreamHandlerType(String urlStreamHandlerType) { if (!URL_HANDLER_URLFETCH.equals(urlStreamHandlerType) && !URL_HANDLER_NATIVE.equals(urlStreamHandlerType)) { throw new AppEngineConfigException( - "url-stream-handler must be " + URL_HANDLER_URLFETCH + " or " + URL_HANDLER_NATIVE + - " given " + urlStreamHandlerType); + "url-stream-handler must be " + + URL_HANDLER_URLFETCH + + " or " + + URL_HANDLER_NATIVE + + " given " + + urlStreamHandlerType); } this.urlStreamHandlerType = urlStreamHandlerType; } @@ -672,7 +678,8 @@ public boolean equals(Object o) { if (threadsafeValueProvided != that.threadsafeValueProvided) { return false; } - if (autoIdPolicy != null ? !autoIdPolicy.equals(that.autoIdPolicy) + if (autoIdPolicy != null + ? !autoIdPolicy.equals(that.autoIdPolicy) : that.autoIdPolicy != null) { return false; } @@ -682,21 +689,24 @@ public boolean equals(Object o) { if (useSessions != that.useSessions) { return false; } - if (adminConsolePages != null ? !adminConsolePages.equals(that.adminConsolePages) + if (adminConsolePages != null + ? !adminConsolePages.equals(that.adminConsolePages) : that.adminConsolePages != null) { return false; } if (appId != null ? !appId.equals(that.appId) : that.appId != null) { return false; } - if (majorVersionId != null ? !majorVersionId.equals(that.majorVersionId) + if (majorVersionId != null + ? !majorVersionId.equals(that.majorVersionId) : that.majorVersionId != null) { return false; } if (service != null ? !service.equals(that.service) : that.service != null) { return false; } - if (instanceClass != null ? !instanceClass.equals(that.instanceClass) + if (instanceClass != null + ? !instanceClass.equals(that.instanceClass) : that.instanceClass != null) { return false; } @@ -712,75 +722,90 @@ public boolean equals(Object o) { if (appRoot != null ? !appRoot.equals(that.appRoot) : that.appRoot != null) { return false; } - if (asyncSessionPersistenceQueueName != null ? !asyncSessionPersistenceQueueName - .equals(that.asyncSessionPersistenceQueueName) + if (asyncSessionPersistenceQueueName != null + ? !asyncSessionPersistenceQueueName.equals(that.asyncSessionPersistenceQueueName) : that.asyncSessionPersistenceQueueName != null) { return false; } - if (envVariables != null ? !envVariables.equals(that.envVariables) + if (envVariables != null + ? !envVariables.equals(that.envVariables) : that.envVariables != null) { return false; } - if (errorHandlers != null ? !errorHandlers.equals(that.errorHandlers) + if (errorHandlers != null + ? !errorHandlers.equals(that.errorHandlers) : that.errorHandlers != null) { return false; } - if (inboundServices != null ? !inboundServices.equals(that.inboundServices) + if (inboundServices != null + ? !inboundServices.equals(that.inboundServices) : that.inboundServices != null) { return false; } - if (majorVersionId != null ? !majorVersionId.equals(that.majorVersionId) + if (majorVersionId != null + ? !majorVersionId.equals(that.majorVersionId) : that.majorVersionId != null) { return false; } - if (sourceLanguage != null ? !sourceLanguage.equals(that.sourceLanguage) + if (sourceLanguage != null + ? !sourceLanguage.equals(that.sourceLanguage) : that.sourceLanguage != null) { return false; } if (publicRoot != null ? !publicRoot.equals(that.publicRoot) : that.publicRoot != null) { return false; } - if (resourceExcludePattern != null ? !resourceExcludePattern.equals(that.resourceExcludePattern) + if (resourceExcludePattern != null + ? !resourceExcludePattern.equals(that.resourceExcludePattern) : that.resourceExcludePattern != null) { return false; } - if (resourceFileExcludes != null ? !resourceFileExcludes.equals(that.resourceFileExcludes) + if (resourceFileExcludes != null + ? !resourceFileExcludes.equals(that.resourceFileExcludes) : that.resourceFileExcludes != null) { return false; } - if (resourceFileIncludes != null ? !resourceFileIncludes.equals(that.resourceFileIncludes) + if (resourceFileIncludes != null + ? !resourceFileIncludes.equals(that.resourceFileIncludes) : that.resourceFileIncludes != null) { return false; } - if (resourceIncludePattern != null ? !resourceIncludePattern.equals(that.resourceIncludePattern) + if (resourceIncludePattern != null + ? !resourceIncludePattern.equals(that.resourceIncludePattern) : that.resourceIncludePattern != null) { return false; } - if (staticExcludePattern != null ? !staticExcludePattern.equals(that.staticExcludePattern) + if (staticExcludePattern != null + ? !staticExcludePattern.equals(that.staticExcludePattern) : that.staticExcludePattern != null) { return false; } - if (staticFileExcludes != null ? !staticFileExcludes.equals(that.staticFileExcludes) + if (staticFileExcludes != null + ? !staticFileExcludes.equals(that.staticFileExcludes) : that.staticFileExcludes != null) { return false; } - if (staticFileIncludes != null ? !staticFileIncludes.equals(that.staticFileIncludes) + if (staticFileIncludes != null + ? !staticFileIncludes.equals(that.staticFileIncludes) : that.staticFileIncludes != null) { return false; } - if (staticIncludePattern != null ? !staticIncludePattern.equals(that.staticIncludePattern) + if (staticIncludePattern != null + ? !staticIncludePattern.equals(that.staticIncludePattern) : that.staticIncludePattern != null) { return false; } - if (systemProperties != null ? !systemProperties.equals(that.systemProperties) + if (systemProperties != null + ? !systemProperties.equals(that.systemProperties) : that.systemProperties != null) { return false; } - if (betaSettings != null ? !betaSettings.equals(that.betaSettings) : that.betaSettings != null) { + if (betaSettings != null + ? !betaSettings.equals(that.betaSettings) + : that.betaSettings != null) { return false; } - if (healthCheck != null ? !healthCheck.equals(that.healthCheck) - : that.healthCheck != null) { + if (healthCheck != null ? !healthCheck.equals(that.healthCheck) : that.healthCheck != null) { return false; } if (resources != null ? !resources.equals(that.resources) : that.resources != null) { @@ -789,24 +814,27 @@ public boolean equals(Object o) { if (network != null ? !network.equals(that.network) : that.network != null) { return false; } - if (userPermissions != null ? !userPermissions.equals(that.userPermissions) + if (userPermissions != null + ? !userPermissions.equals(that.userPermissions) : that.userPermissions != null) { return false; } - if (apiConfig != null ? !apiConfig.equals(that.apiConfig) - : that.apiConfig != null) { + if (apiConfig != null ? !apiConfig.equals(that.apiConfig) : that.apiConfig != null) { return false; } - if (apiEndpointIds != null ? !apiEndpointIds.equals(that.apiEndpointIds) + if (apiEndpointIds != null + ? !apiEndpointIds.equals(that.apiEndpointIds) : that.apiEndpointIds != null) { return false; } - if (classLoaderConfig != null ? !classLoaderConfig.equals(that.classLoaderConfig) : - that.classLoaderConfig != null) { + if (classLoaderConfig != null + ? !classLoaderConfig.equals(that.classLoaderConfig) + : that.classLoaderConfig != null) { return false; } - if (urlStreamHandlerType != null ? !urlStreamHandlerType.equals(that.urlStreamHandlerType) : - that.urlStreamHandlerType != null) { + if (urlStreamHandlerType != null + ? !urlStreamHandlerType.equals(that.urlStreamHandlerType) + : that.urlStreamHandlerType != null) { return false; } if (useGoogleConnectorJ != that.useGoogleConnectorJ) { @@ -833,8 +861,10 @@ public int hashCode() { result = 31 * result + (useSessions ? 1 : 0); result = 31 * result + (asyncSessionPersistence ? 1 : 0); result = - 31 * result + (asyncSessionPersistenceQueueName != null ? asyncSessionPersistenceQueueName - .hashCode() : 0); + 31 * result + + (asyncSessionPersistenceQueueName != null + ? asyncSessionPersistenceQueueName.hashCode() + : 0); result = 31 * result + (staticFileIncludes != null ? staticFileIncludes.hashCode() : 0); result = 31 * result + (staticFileExcludes != null ? staticFileExcludes.hashCode() : 0); result = 31 * result + (resourceFileIncludes != null ? resourceFileIncludes.hashCode() : 0); @@ -893,8 +923,7 @@ public boolean includesStatic(String path) { } else { staticRoot = "**"; } - staticIncludePattern = Pattern.compile( - makeRegexp(Collections.singletonList(staticRoot))); + staticIncludePattern = Pattern.compile(makeRegexp(Collections.singletonList(staticRoot))); } else { List patterns = new ArrayList(); for (StaticFileInclude include : staticFileIncludes) { @@ -921,7 +950,7 @@ public boolean includesStatic(String path) { * anything from the {@code includes} set. */ public boolean includes(String path, Pattern includes, Pattern excludes) { - assert(includes != null); + assert (includes != null); if (!includes.matcher(path).matches()) { return false; } @@ -1110,7 +1139,7 @@ public boolean equals(Object obj) { if (!pattern.equals(other.pattern)) { return false; } - } else { // pattern == null + } else { // pattern == null if (other.pattern != null) { return false; } @@ -1122,7 +1151,7 @@ public boolean equals(Object obj) { if (!expiration.equals(other.expiration)) { return false; } - } else { // expiration == null + } else { // expiration == null if (other.expiration != null) { return false; } @@ -1134,7 +1163,7 @@ public boolean equals(Object obj) { if (!httpHeaders.equals(other.httpHeaders)) { return false; } - } else { // httpHeaders == null + } else { // httpHeaders == null if (other.httpHeaders != null) { return false; } @@ -1174,16 +1203,30 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } AdminConsolePage other = (AdminConsolePage) obj; if (name == null) { - if (other.name != null) return false; - } else if (!name.equals(other.name)) return false; + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } if (url == null) { - if (other.url != null) return false; - } else if (!url.equals(other.url)) return false; + if (other.url != null) { + return false; + } + } else if (!url.equals(other.url)) { + return false; + } return true; } } @@ -1214,8 +1257,7 @@ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((file == null) ? 0 : file.hashCode()); - result = prime * result + - ((errorCode == null) ? 0 : errorCode.hashCode()); + result = prime * result + ((errorCode == null) ? 0 : errorCode.hashCode()); return result; } @@ -1276,16 +1318,30 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) { return true; } - if (obj == null) { return false; } - if (getClass() != obj.getClass()) { return false; } + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } ApiConfig other = (ApiConfig) obj; if (servletClass == null) { - if (other.servletClass != null) { return false; } - } else if (!servletClass.equals(other.servletClass)) { return false; } + if (other.servletClass != null) { + return false; + } + } else if (!servletClass.equals(other.servletClass)) { + return false; + } if (url == null) { - if (other.url != null) { return false; } - } else if (!url.equals(other.url)) { return false; } + if (other.url != null) { + return false; + } + } else if (!url.equals(other.url)) { + return false; + } return true; } @@ -1294,7 +1350,7 @@ public String toString() { return "ApiConfig{servletClass=\"" + servletClass + "\", url=\"" + url + "\"}"; } } - + /** * Holder for automatic settings. */ @@ -1348,7 +1404,7 @@ public String getMaxPendingLatency() { * Sets maxPendingLatency. Normalizes empty and null inputs to null. */ public void setMaxPendingLatency(String maxPendingLatency) { - this.maxPendingLatency = toNullIfEmptyOrWhitespace(maxPendingLatency); + this.maxPendingLatency = toNullIfEmptyOrWhitespace(maxPendingLatency); } public String getMinIdleInstances() { @@ -1359,7 +1415,7 @@ public String getMinIdleInstances() { * Sets minIdleInstances. Normalizes empty and null inputs to null. */ public void setMinIdleInstances(String minIdleInstances) { - this.minIdleInstances = toNullIfEmptyOrWhitespace(minIdleInstances); + this.minIdleInstances = toNullIfEmptyOrWhitespace(minIdleInstances); } public String getMaxIdleInstances() { @@ -1370,7 +1426,7 @@ public String getMaxIdleInstances() { * Sets maxIdleInstances. Normalizes empty and null inputs to null. */ public void setMaxIdleInstances(String maxIdleInstances) { - this.maxIdleInstances = toNullIfEmptyOrWhitespace(maxIdleInstances); + this.maxIdleInstances = toNullIfEmptyOrWhitespace(maxIdleInstances); } public boolean isEmpty() { @@ -1385,7 +1441,7 @@ public String getMaxConcurrentRequests() { * Sets maxConcurrentRequests. Normalizes empty and null inputs to null. */ public void setMaxConcurrentRequests(String maxConcurrentRequests) { - this.maxConcurrentRequests = toNullIfEmptyOrWhitespace(maxConcurrentRequests); + this.maxConcurrentRequests = toNullIfEmptyOrWhitespace(maxConcurrentRequests); } public Integer getMinNumInstances() { @@ -1502,14 +1558,26 @@ public void setTargetConcurrentRequests(Integer targetConcurrentRequests) { @Override public int hashCode() { - return Objects.hash(maxPendingLatency, minPendingLatency, maxIdleInstances, - minIdleInstances, maxConcurrentRequests, minNumInstances, - maxNumInstances, coolDownPeriodSec, cpuUtilization, - targetNetworkSentBytesPerSec, targetNetworkSentPacketsPerSec, - targetNetworkReceivedBytesPerSec, targetNetworkReceivedPacketsPerSec, - targetDiskWriteBytesPerSec, targetDiskWriteOpsPerSec, - targetDiskReadBytesPerSec, targetDiskReadOpsPerSec, - targetRequestCountPerSec, targetConcurrentRequests); + return Objects.hash( + maxPendingLatency, + minPendingLatency, + maxIdleInstances, + minIdleInstances, + maxConcurrentRequests, + minNumInstances, + maxNumInstances, + coolDownPeriodSec, + cpuUtilization, + targetNetworkSentBytesPerSec, + targetNetworkSentPacketsPerSec, + targetNetworkReceivedBytesPerSec, + targetNetworkReceivedPacketsPerSec, + targetDiskWriteBytesPerSec, + targetDiskWriteOpsPerSec, + targetDiskReadBytesPerSec, + targetDiskReadOpsPerSec, + targetRequestCountPerSec, + targetConcurrentRequests); } @Override @@ -1535,10 +1603,10 @@ public boolean equals(Object obj) { && Objects.equals(cpuUtilization, other.cpuUtilization) && Objects.equals(targetNetworkSentBytesPerSec, other.targetNetworkSentBytesPerSec) && Objects.equals(targetNetworkSentPacketsPerSec, other.targetNetworkSentPacketsPerSec) - && Objects.equals(targetNetworkReceivedBytesPerSec, - other.targetNetworkReceivedBytesPerSec) - && Objects.equals(targetNetworkReceivedPacketsPerSec, - other.targetNetworkReceivedPacketsPerSec) + && Objects.equals( + targetNetworkReceivedBytesPerSec, other.targetNetworkReceivedBytesPerSec) + && Objects.equals( + targetNetworkReceivedPacketsPerSec, other.targetNetworkReceivedPacketsPerSec) && Objects.equals(targetDiskWriteBytesPerSec, other.targetDiskWriteBytesPerSec) && Objects.equals(targetDiskWriteOpsPerSec, other.targetDiskWriteOpsPerSec) && Objects.equals(targetDiskReadBytesPerSec, other.targetDiskReadBytesPerSec) @@ -1549,25 +1617,44 @@ public boolean equals(Object obj) { @Override public String toString() { - return "AutomaticScaling [minPendingLatency=" + minPendingLatency - + ", maxPendingLatency=" + maxPendingLatency - + ", minIdleInstances=" + minIdleInstances - + ", maxIdleInstances=" + maxIdleInstances - + ", maxConcurrentRequests=" + maxConcurrentRequests - + ", minNumInstances=" + minNumInstances - + ", maxNumInstances=" + maxNumInstances - + ", coolDownPeriodSec=" + coolDownPeriodSec - + ", cpuUtilization=" + cpuUtilization - + ", targetNetworkSentBytesPerSec=" + targetNetworkSentBytesPerSec - + ", targetNetworkSentPacketsPerSec=" + targetNetworkSentPacketsPerSec - + ", targetNetworkReceivedBytesPerSec=" + targetNetworkReceivedBytesPerSec - + ", targetNetworkReceivedPacketsPerSec=" + targetNetworkReceivedPacketsPerSec - + ", targetDiskWriteBytesPerSec=" + targetDiskWriteBytesPerSec - + ", targetDiskWriteOpsPerSec=" + targetDiskWriteOpsPerSec - + ", targetDiskReadBytesPerSec=" + targetDiskReadBytesPerSec - + ", targetDiskReadOpsPerSec=" + targetDiskReadOpsPerSec - + ", targetRequestCountPerSec=" + targetRequestCountPerSec - + ", targetConcurrentRequests=" + targetConcurrentRequests + return "AutomaticScaling [minPendingLatency=" + + minPendingLatency + + ", maxPendingLatency=" + + maxPendingLatency + + ", minIdleInstances=" + + minIdleInstances + + ", maxIdleInstances=" + + maxIdleInstances + + ", maxConcurrentRequests=" + + maxConcurrentRequests + + ", minNumInstances=" + + minNumInstances + + ", maxNumInstances=" + + maxNumInstances + + ", coolDownPeriodSec=" + + coolDownPeriodSec + + ", cpuUtilization=" + + cpuUtilization + + ", targetNetworkSentBytesPerSec=" + + targetNetworkSentBytesPerSec + + ", targetNetworkSentPacketsPerSec=" + + targetNetworkSentPacketsPerSec + + ", targetNetworkReceivedBytesPerSec=" + + targetNetworkReceivedBytesPerSec + + ", targetNetworkReceivedPacketsPerSec=" + + targetNetworkReceivedPacketsPerSec + + ", targetDiskWriteBytesPerSec=" + + targetDiskWriteBytesPerSec + + ", targetDiskWriteOpsPerSec=" + + targetDiskWriteOpsPerSec + + ", targetDiskReadBytesPerSec=" + + targetDiskReadBytesPerSec + + ", targetDiskReadOpsPerSec=" + + targetDiskReadOpsPerSec + + ", targetRequestCountPerSec=" + + targetRequestCountPerSec + + ", targetConcurrentRequests=" + + targetConcurrentRequests + "]"; } } @@ -1577,7 +1664,7 @@ public String toString() { */ public static class CpuUtilization { private static final CpuUtilization EMPTY_SETTINGS = new CpuUtilization(); - // The target of CPU utilization. + // The target of CPU utilization. private Double targetUtilization; // The number of seconds used to aggregate CPU usage. private Integer aggregationWindowLengthSec; @@ -1585,23 +1672,23 @@ public static class CpuUtilization { public Double getTargetUtilization() { return targetUtilization; } - + public void setTargetUtilization(Double targetUtilization) { this.targetUtilization = targetUtilization; } - + public Integer getAggregationWindowLengthSec() { return aggregationWindowLengthSec; } - + public void setAggregationWindowLengthSec(Integer aggregationWindowLengthSec) { this.aggregationWindowLengthSec = aggregationWindowLengthSec; } - + public boolean isEmpty() { return this.equals(EMPTY_SETTINGS); } - + @Override public int hashCode() { return Objects.hash(targetUtilization, aggregationWindowLengthSec); @@ -1625,8 +1712,11 @@ public boolean equals(Object obj) { @Override public String toString() { - return "CpuUtilization [targetUtilization=" + targetUtilization - + ", aggregationWindowLengthSec=" + aggregationWindowLengthSec + "]"; + return "CpuUtilization [targetUtilization=" + + targetUtilization + + ", aggregationWindowLengthSec=" + + aggregationWindowLengthSec + + "]"; } } @@ -1698,7 +1788,6 @@ public Integer getHealthyThreshold() { /** * Sets healthyThreshold. */ - public void setHealthyThreshold(Integer healthyThreshold) { this.healthyThreshold = healthyThreshold; } @@ -1731,8 +1820,14 @@ public boolean isEmpty() { @Override public int hashCode() { - return Objects.hash(enableHealthCheck, checkIntervalSec, timeoutSec, unhealthyThreshold, - healthyThreshold, restartThreshold, host); + return Objects.hash( + enableHealthCheck, + checkIntervalSec, + timeoutSec, + unhealthyThreshold, + healthyThreshold, + restartThreshold, + host); } @Override @@ -1758,13 +1853,21 @@ public boolean equals(Object obj) { @Override public String toString() { - return "HealthCheck [enableHealthCheck=" + enableHealthCheck - + ", checkIntervalSec=" + checkIntervalSec - + ", timeoutSec=" + timeoutSec - + ", unhealthyThreshold=" + unhealthyThreshold - + ", healthyThreshold=" + healthyThreshold - + ", restartThreshold=" + restartThreshold - + ", host=" + host + "]"; + return "HealthCheck [enableHealthCheck=" + + enableHealthCheck + + ", checkIntervalSec=" + + checkIntervalSec + + ", timeoutSec=" + + timeoutSec + + ", unhealthyThreshold=" + + unhealthyThreshold + + ", healthyThreshold=" + + healthyThreshold + + ", restartThreshold=" + + restartThreshold + + ", host=" + + host + + "]"; } } @@ -1830,16 +1933,21 @@ public boolean equals(Object obj) { return false; } Resources other = (Resources) obj; - return Objects.equals(cpu, other.cpu) && - Objects.equals(memory_gb, other.memory_gb) && - Objects.equals(disk_size_gb, other.disk_size_gb); + return Objects.equals(cpu, other.cpu) + && Objects.equals(memory_gb, other.memory_gb) + && Objects.equals(disk_size_gb, other.disk_size_gb); } @Override public String toString() { - return "Resources [" + "cpu=" + cpu + - ", memory_gb=" + memory_gb + - ", disk_size_gb=" + disk_size_gb + "]"; + return "Resources [" + + "cpu=" + + cpu + + ", memory_gb=" + + memory_gb + + ", disk_size_gb=" + + disk_size_gb + + "]"; } } @@ -2032,8 +2140,12 @@ public boolean equals(Object obj) { @Override public String toString() { - return "BasicScaling [" + "maxInstances=" + maxInstances - + ", idleTimeout=" + idleTimeout + "]"; + return "BasicScaling [" + + "maxInstances=" + + maxInstances + + ", idleTimeout=" + + idleTimeout + + "]"; } } @@ -2060,13 +2172,23 @@ public int hashCode() { // Generated by eclipse. @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } ClassLoaderConfig other = (ClassLoaderConfig) obj; if (entries == null) { - if (other.entries != null) return false; - } else if (!entries.equals(other.entries)) return false; + if (other.entries != null) { + return false; + } + } else if (!entries.equals(other.entries)) { + return false; + } return true; } @@ -2078,12 +2200,13 @@ public String toString() { public static class PrioritySpecifierEntry { private String filename; - private Double priority; // null means not present. Default priority is 1.0. + private Double priority; // null means not present. Default priority is 1.0. private void checkNotAlreadySet() { if (filename != null) { - throw new AppEngineConfigException("Found more that one file name matching tag. " - + "Only one of 'filename' attribute allowed."); + throw new AppEngineConfigException( + "Found more that one file name matching tag. " + + "Only one of 'filename' attribute allowed."); } } @@ -2142,16 +2265,30 @@ public int hashCode() { // Generated by eclipse. @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } PrioritySpecifierEntry other = (PrioritySpecifierEntry) obj; if (filename == null) { - if (other.filename != null) return false; - } else if (!filename.equals(other.filename)) return false; + if (other.filename != null) { + return false; + } + } else if (!filename.equals(other.filename)) { + return false; + } if (priority == null) { - if (other.priority != null) return false; - } else if (!priority.equals(other.priority)) return false; + if (other.priority != null) { + return false; + } + } else if (!priority.equals(other.priority)) { + return false; + } return true; } @@ -2160,4 +2297,4 @@ public String toString() { return "PrioritySpecifierEntry{filename=\"" + filename + "\", priority=\"" + priority + "\"}"; } } -} \ No newline at end of file +} diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlProcessor.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlProcessor.java index b58a281..458b3b0 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlProcessor.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlProcessor.java @@ -1,19 +1,18 @@ /** * Copyright 2008 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.apphosting.utils.config; import com.google.apphosting.utils.config.AppEngineWebXml.AdminConsolePage; @@ -46,7 +45,10 @@ */ class AppEngineWebXmlProcessor { - enum FileType { STATIC, RESOURCE } + enum FileType { + STATIC, + RESOURCE + } // Error handling to disallow having both module and service entries. private boolean moduleNodeFound; @@ -95,8 +97,8 @@ private static void checkScalingConstraints(AppEngineWebXml appEngineWebXml) { count += appEngineWebXml.getAutomaticScaling().isEmpty() ? 0 : 1; if (count > 1) { throw new AppEngineConfigException( - "There may be only one of 'automatic-scaling', 'manual-scaling' or " + - "'basic-scaling' elements."); + "There may be only one of 'automatic-scaling', 'manual-scaling' or " + + "'basic-scaling' elements."); } } @@ -253,7 +255,7 @@ private void processModuleNode(Element node, AppEngineWebXml appEngineWebXml) { private void processServiceNode(Element node, AppEngineWebXml appEngineWebXml) { appEngineWebXml.setService(getTextNode(node)); } - + private void processInstanceClassNode(Element node, AppEngineWebXml appEngineWebXml) { appEngineWebXml.setInstanceClass(getTextNode(node)); @@ -307,6 +309,7 @@ private Double getChildNodeDouble(Element parentNode, String childTag) { } return result; } + private void processAutomaticScalingNode(Element settingsNode, AppEngineWebXml appEngineWebXml) { AutomaticScaling automaticScaling = appEngineWebXml.getAutomaticScaling(); automaticScaling.setMinPendingLatency(getChildNodeText(settingsNode, "min-pending-latency")); @@ -492,10 +495,8 @@ private void processHealthCheckNode(Element settingsNode, AppEngineWebXml appEng healthCheck.setTimeoutSec(getChildNodePositiveInteger(settingsNode, "timeout-sec")); healthCheck.setUnhealthyThreshold( getChildNodePositiveInteger(settingsNode, "unhealthy-threshold")); - healthCheck.setHealthyThreshold( - getChildNodePositiveInteger(settingsNode, "healthy-threshold")); - healthCheck.setRestartThreshold( - getChildNodePositiveInteger(settingsNode, "restart-threshold")); + healthCheck.setHealthyThreshold(getChildNodePositiveInteger(settingsNode, "healthy-threshold")); + healthCheck.setRestartThreshold(getChildNodePositiveInteger(settingsNode, "restart-threshold")); healthCheck.setHost(getChildNodeText(settingsNode, "host")); } @@ -598,6 +599,7 @@ private void processApiConfigNode(Element node, AppEngineWebXml appEngineWebXml) } } } + private void processClassLoaderConfig(Element node, AppEngineWebXml appEngineWebXml) { ClassLoaderConfig config = new ClassLoaderConfig(); appEngineWebXml.setClassLoaderConfig(config); @@ -646,4 +648,4 @@ private String trim(String attribute) { private void processUseGoogleConnectorJNode(Element node, AppEngineWebXml appEngineWebXml) { appEngineWebXml.setUseGoogleConnectorJ(getBooleanValue(node)); } -} \ No newline at end of file +} diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlReader.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlReader.java index f2e048d..dabc109 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlReader.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/AppEngineWebXmlReader.java @@ -1,19 +1,18 @@ /** * Copyright 2008 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.apphosting.utils.config; import java.io.File; @@ -32,8 +31,7 @@ * */ public class AppEngineWebXmlReader { - private static final Logger logger = - Logger.getLogger(AppEngineWebXmlReader.class.getName()); + private static final Logger logger = Logger.getLogger(AppEngineWebXmlReader.class.getName()); private static final String CONCURRENT_REQUESTS_URL = "http://code.google.com/appengine/docs/java/config/appconfig.html#Using_Concurrent_Requests"; @@ -92,21 +90,30 @@ public AppEngineWebXml readAppEngineWebXml() { if (!appEngineWebXml.getThreadsafeValueProvided()) { if (allowMissingThreadsafeElement()) { // make some noise if there is no element. - logger.warning("appengine-web.xml does not contain a element. This will " - + "be treated as an error the next time you deploy.\nSee " + CONCURRENT_REQUESTS_URL - + " for more information.\nYou probably want to enable concurrent requests."); + logger.warning( + "appengine-web.xml does not contain a element. This will " + + "be treated as an error the next time you deploy.\nSee " + + CONCURRENT_REQUESTS_URL + + " for more information.\nYou probably want to enable concurrent requests."); } else { - throw new AppEngineConfigException("appengine-web.xml does not contain a " - + "element.\nSee " + CONCURRENT_REQUESTS_URL + " for more information.\nYou probably " - + "want to enable concurrent requests."); + throw new AppEngineConfigException( + "appengine-web.xml does not contain a " + + "element.\nSee " + + CONCURRENT_REQUESTS_URL + + " for more information.\nYou probably " + + "want to enable concurrent requests."); } } if ("legacy".equals(appEngineWebXml.getAutoIdPolicy())) { - logger.warning("You have set the datastore auto id policy to 'legacy'. It is recommended " - + "that you select 'default' instead.\nLegacy auto ids are deprecated. You can " - + "continue to allocate legacy ids manually using the allocateIds() API functions.\n" - + "For more information see:\n" - + APPCFG_AUTO_IDS_URL + "\n" + DATASTORE_AUTO_IDS_URL + "\n"); + logger.warning( + "You have set the datastore auto id policy to 'legacy'. It is recommended " + + "that you select 'default' instead.\nLegacy auto ids are deprecated. You can " + + "continue to allocate legacy ids manually using the allocateIds() API functions.\n" + + "For more information see:\n" + + APPCFG_AUTO_IDS_URL + + "\n" + + DATASTORE_AUTO_IDS_URL + + "\n"); } } catch (Exception e) { String msg = "Received exception processing " + getFilename(); diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/XmlUtils.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/XmlUtils.java index 88a69d9..cc8c37b 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/XmlUtils.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/config/XmlUtils.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.utils.config; import com.google.appengine.repackaged.com.google.common.io.Files; @@ -73,8 +72,9 @@ static Document parseXml(InputStream inputStream, String filename) { String msg = "Received SAXException parsing the input stream" + maybeFilename(filename); throw new AppEngineConfigException(msg, e); } catch (ParserConfigurationException e) { - String msg = "Received ParserConfigurationException parsing the input stream" - + maybeFilename(filename); + String msg = + "Received ParserConfigurationException parsing the input stream" + + maybeFilename(filename); throw new AppEngineConfigException(msg, e); } } @@ -129,8 +129,9 @@ static void validateXmlContent(String content, File schema) { factory .newSchema(schema) .newValidator() - .validate(new StreamSource(new ByteArrayInputStream( - content.getBytes(StandardCharsets.UTF_8)))); + .validate( + new StreamSource( + new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)))); } catch (SAXException ex) { throw new AppEngineConfigException( "XML error validating " + content + " against " + schema.getPath(), ex); @@ -216,4 +217,4 @@ static List getChildren(Element element, String tagName) { } return elements; } -} \ No newline at end of file +} diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpRequest.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpRequest.java index 1828a3e..856353f 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpRequest.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpRequest.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.utils.http; /** diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpResponse.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpResponse.java index 408c944..0b4311a 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpResponse.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/http/HttpResponse.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.utils.http; import java.io.IOException; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/DeferredTaskServlet.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/DeferredTaskServlet.java index d9b0dd2..08dd5e0 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/DeferredTaskServlet.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/DeferredTaskServlet.java @@ -1,20 +1,18 @@ /** * Copyright 2011 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.apphosting.utils.servlet; import com.google.appengine.api.taskqueue.DeferredTask; @@ -60,15 +58,14 @@ public class DeferredTaskServlet extends HttpServlet { static final String X_APPENGINE_QUEUENAME = "X-AppEngine-QueueName"; static final String DEFERRED_TASK_SERVLET_KEY = - DeferredTaskContext.class.getName() + ".httpServlet"; + DeferredTaskContext.class.getName() + ".httpServlet"; static final String DEFERRED_TASK_REQUEST_KEY = - DeferredTaskContext.class.getName() + ".httpServletRequest"; + DeferredTaskContext.class.getName() + ".httpServletRequest"; static final String DEFERRED_TASK_RESPONSE_KEY = - DeferredTaskContext.class.getName() + ".httpServletResponse"; + DeferredTaskContext.class.getName() + ".httpServletResponse"; static final String DEFERRED_DO_NOT_RETRY_KEY = - DeferredTaskContext.class.getName() + ".doNotRetry"; - static final String DEFERRED_MARK_RETRY_KEY = - DeferredTaskContext.class.getName() + ".markRetry"; + DeferredTaskContext.class.getName() + ".doNotRetry"; + static final String DEFERRED_MARK_RETRY_KEY = DeferredTaskContext.class.getName() + ".markRetry"; /** * Thrown by readRequest when an error occurred during deserialization. @@ -94,9 +91,9 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) String protocol = req.getProtocol(); String msg = "DeferredTaskServlet does not support method: " + method; if (protocol.endsWith("1.1")) { - resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); + resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } return; } @@ -125,9 +122,11 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) if (doNotRetry == null || !doNotRetry) { throw new ServletException(e); } else if (doNotRetry) { - resp.setStatus(HttpURLConnection.HTTP_NOT_AUTHORITATIVE); // Alternate success code. - log(DeferredTaskServlet.class.getName() + - " - Deferred task failed but doNotRetry specified. Exception: " + e); + resp.setStatus(HttpURLConnection.HTTP_NOT_AUTHORITATIVE); // Alternate success code. + log( + DeferredTaskServlet.class.getName() + + " - Deferred task failed but doNotRetry specified. Exception: " + + e); } } finally { // Clean out the attributes. @@ -149,8 +148,8 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) *

Note that other exceptions may be thrown by the * {@link DeferredTask#run()} method. */ - protected void performRequest( - HttpServletRequest req, HttpServletResponse resp) throws DeferredTaskException { + protected void performRequest(HttpServletRequest req, HttpServletResponse resp) + throws DeferredTaskException { readRequest(req, resp).run(); } @@ -165,68 +164,74 @@ protected void performRequest( *

  • {@link IOException}: Deserialization failure. *
  • {@link ClassCastException}: Deserialization failure. * */ - protected DeferredTask readRequest( - HttpServletRequest req, HttpServletResponse resp) throws DeferredTaskException { + protected DeferredTask readRequest(HttpServletRequest req, HttpServletResponse resp) + throws DeferredTaskException { String contentType = req.getHeader("content-type"); - if (contentType == null || - !contentType.equals(DeferredTaskContext.RUNNABLE_TASK_CONTENT_TYPE)) { - throw new DeferredTaskException(new IllegalArgumentException( - "Invalid content-type header." - + " received: '" + (contentType == null ? "null" : contentType) - + "' expected: '" + DeferredTaskContext.RUNNABLE_TASK_CONTENT_TYPE + "'")); + if (contentType == null + || !contentType.equals(DeferredTaskContext.RUNNABLE_TASK_CONTENT_TYPE)) { + throw new DeferredTaskException( + new IllegalArgumentException( + "Invalid content-type header." + + " received: '" + + (contentType == null ? "null" : contentType) + + "' expected: '" + + DeferredTaskContext.RUNNABLE_TASK_CONTENT_TYPE + + "'")); } DeferredTask deferredTask; try { ServletInputStream stream = req.getInputStream(); - ObjectInputStream objectStream = new ObjectInputStream(stream) { - @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, - ClassNotFoundException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - String name = desc.getName(); - try { - return Class.forName(name, false, classLoader); - } catch (ClassNotFoundException ex) { - // This one should also handle primitive types - return super.resolveClass(desc); - } - } - - @Override - protected Class resolveProxyClass(String[] interfaces) - throws IOException, ClassNotFoundException { - // Note(user) This logic was copied from ObjectInputStream.java in the - // JDK, and then modified to use the thread context class loader instead of the - // "latest" loader that is used there. - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader nonPublicLoader = null; - boolean hasNonPublicInterface = false; + ObjectInputStream objectStream = + new ObjectInputStream(stream) { + @Override + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + String name = desc.getName(); + try { + return Class.forName(name, false, classLoader); + } catch (ClassNotFoundException ex) { + // This one should also handle primitive types + return super.resolveClass(desc); + } + } - // define proxy in class loader of non-public interface(s), if any - Class[] classObjs = new Class[interfaces.length]; - for (int i = 0; i < interfaces.length; i++) { - Class cl = Class.forName(interfaces[i], false, classLoader); - if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { - if (hasNonPublicInterface) { - if (nonPublicLoader != cl.getClassLoader()) { - throw new IllegalAccessError("conflicting non-public interface class loaders"); + @Override + protected Class resolveProxyClass(String[] interfaces) + throws IOException, ClassNotFoundException { + // Note(user) This logic was copied from ObjectInputStream.java in the + // JDK, and then modified to use the thread context class loader instead of the + // "latest" loader that is used there. + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + ClassLoader nonPublicLoader = null; + boolean hasNonPublicInterface = false; + + // define proxy in class loader of non-public interface(s), if any + Class[] classObjs = new Class[interfaces.length]; + for (int i = 0; i < interfaces.length; i++) { + Class cl = Class.forName(interfaces[i], false, classLoader); + if ((cl.getModifiers() & Modifier.PUBLIC) == 0) { + if (hasNonPublicInterface) { + if (nonPublicLoader != cl.getClassLoader()) { + throw new IllegalAccessError( + "conflicting non-public interface class loaders"); + } + } else { + nonPublicLoader = cl.getClassLoader(); + hasNonPublicInterface = true; + } } - } else { - nonPublicLoader = cl.getClassLoader(); - hasNonPublicInterface = true; + classObjs[i] = cl; + } + try { + return Proxy.getProxyClass( + hasNonPublicInterface ? nonPublicLoader : classLoader, classObjs); + } catch (IllegalArgumentException e) { + throw new ClassNotFoundException(null, e); } } - classObjs[i] = cl; - } - try { - return Proxy.getProxyClass( - hasNonPublicInterface ? nonPublicLoader : classLoader, classObjs); - } catch (IllegalArgumentException e) { - throw new ClassNotFoundException(null, e); - } - } - }; + }; deferredTask = (DeferredTask) objectStream.readObject(); } catch (ClassNotFoundException e) { throw new DeferredTaskException(e); diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletRequestAdapter.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletRequestAdapter.java index 50a59c7..8dcf6d9 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletRequestAdapter.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletRequestAdapter.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.utils.servlet; import com.google.apphosting.utils.http.HttpRequest; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletResponseAdapter.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletResponseAdapter.java index d668bd8..cbf447f 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletResponseAdapter.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/HttpServletResponseAdapter.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.utils.servlet; import com.google.apphosting.utils.http.HttpResponse; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/MultipartMimeUtils.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/MultipartMimeUtils.java index 7873a88..bee57fa 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/MultipartMimeUtils.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/MultipartMimeUtils.java @@ -1,20 +1,18 @@ /** * Copyright 2009 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.apphosting.utils.servlet; import com.google.appengine.repackaged.com.google.common.io.ByteStreams; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/ParseBlobUploadFilter.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/ParseBlobUploadFilter.java index b0624ec..fed1469 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/ParseBlobUploadFilter.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/ParseBlobUploadFilter.java @@ -1,20 +1,18 @@ /** * Copyright 2009 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.apphosting.utils.servlet; import java.io.ByteArrayInputStream; @@ -56,8 +54,7 @@ * */ public class ParseBlobUploadFilter implements Filter { - private static final Logger logger = Logger.getLogger( - ParseBlobUploadFilter.class.getName()); + private static final Logger logger = Logger.getLogger(ParseBlobUploadFilter.class.getName()); /** * An arbitrary HTTP header that is set on all blob upload @@ -80,11 +77,9 @@ public class ParseBlobUploadFilter implements Filter { static final String CONTENT_LENGTH_HEADER = "Content-Length"; - public void init(FilterConfig config) { - } + public void init(FilterConfig config) {} - public void destroy() { - } + public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/SessionCleanupServlet.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/SessionCleanupServlet.java index 8752599..186cab8 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/SessionCleanupServlet.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/SessionCleanupServlet.java @@ -1,20 +1,18 @@ /** * Copyright 2008 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.apphosting.utils.servlet; import com.google.appengine.api.datastore.DatastoreService; @@ -67,11 +65,10 @@ public void service(HttpServletRequest request, HttpServletResponse response) { private void clearAll(HttpServletResponse response) { Query query = new Query(SESSION_ENTITY_TYPE); query.setKeysOnly(); - query.addFilter(EXPIRES_PROP, Query.FilterOperator.LESS_THAN, - System.currentTimeMillis()); + query.addFilter(EXPIRES_PROP, Query.FilterOperator.LESS_THAN, System.currentTimeMillis()); ArrayList killList = new ArrayList(); - Iterable entities = datastore.prepare(query).asIterable( - FetchOptions.Builder.withLimit(MAX_SESSION_COUNT)); + Iterable entities = + datastore.prepare(query).asIterable(FetchOptions.Builder.withLimit(MAX_SESSION_COUNT)); for (Entity expiredSession : entities) { Key key = expiredSession.getKey(); killList.add(key); @@ -88,8 +85,7 @@ private void clearAll(HttpServletResponse response) { private void sendForm(String actionUrl, HttpServletResponse response) { Query query = new Query(SESSION_ENTITY_TYPE); query.setKeysOnly(); - query.addFilter(EXPIRES_PROP, Query.FilterOperator.LESS_THAN, - System.currentTimeMillis()); + query.addFilter(EXPIRES_PROP, Query.FilterOperator.LESS_THAN, System.currentTimeMillis()); int count = datastore.prepare(query).countEntities(); response.setContentType("text/html"); diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/TransactionCleanupFilter.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/TransactionCleanupFilter.java index 7a6e9d0..011b54d 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/TransactionCleanupFilter.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/TransactionCleanupFilter.java @@ -1,22 +1,20 @@ /** * Copyright 2008 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.apphosting.utils.servlet; - import java.io.IOException; import javax.servlet.FilterConfig; @@ -31,13 +29,12 @@ */ public class TransactionCleanupFilter implements Filter { - public void init(FilterConfig filterConfig) { - } + public void init(FilterConfig filterConfig) {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - chain.doFilter(request, response); - } - public void destroy() { + chain.doFilter(request, response); } + + public void destroy() {} } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmHealthServlet.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmHealthServlet.java index 322b31a..aabaabd 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmHealthServlet.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmHealthServlet.java @@ -1,20 +1,18 @@ /** * Copyright 2013 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.apphosting.utils.servlet; import com.google.appengine.api.LifecycleManager; @@ -41,8 +39,8 @@ private String fullVersionId() { ApiProxy.Environment environment = ApiProxy.getCurrentEnvironment(); String actualVersionId = environment.getVersionId(); if (!(environment.getModuleId() == null - || environment.getModuleId().isEmpty() - || environment.getModuleId().equals("default"))) { + || environment.getModuleId().isEmpty() + || environment.getModuleId().equals("default"))) { actualVersionId = environment.getModuleId() + ":" + actualVersionId; } return actualVersionId; @@ -53,20 +51,23 @@ public void service(HttpServletRequest request, HttpServletResponse response) th // Check if the instance is shutting down, in that case return unhealthy (lameduck). LifecycleManager lifeCycleManager = LifecycleManager.getInstance(); if (LifecycleManager.getInstance().isShuttingDown()) { - long remainingShutdownTime = lifeCycleManager.getRemainingShutdownTime(); - response.sendError(HttpServletResponse.SC_BAD_GATEWAY, - "App is shutting down, time remaining: " + remainingShutdownTime + " ms"); - return; + long remainingShutdownTime = lifeCycleManager.getRemainingShutdownTime(); + response.sendError( + HttpServletResponse.SC_BAD_GATEWAY, + "App is shutting down, time remaining: " + remainingShutdownTime + " ms"); + return; } String expectedVersion = request.getParameter("VersionID"); String actualVersion = fullVersionId(); - if ((expectedVersion == null) || expectedVersion.equals(actualVersion)){ + if ((expectedVersion == null) || expectedVersion.equals(actualVersion)) { response.setContentType("text/plain"); response.getWriter().write("ok"); } else { response.setContentType("text/plain"); - response.getWriter().write( - String.format("version mismatch \"%s\" != \"%s\"", expectedVersion, actualVersion)); + response + .getWriter() + .write( + String.format("version mismatch \"%s\" != \"%s\"", expectedVersion, actualVersion)); } } } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmStopFilter.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmStopFilter.java index 8854d43..83d3178 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmStopFilter.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/VmStopFilter.java @@ -1,20 +1,18 @@ /** * Copyright 2013 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.apphosting.utils.servlet; import com.google.appengine.api.LifecycleManager; @@ -45,12 +43,10 @@ public class VmStopFilter implements Filter { TimeUnit.SECONDS.convert(60, TimeUnit.MILLISECONDS); @Override - public void init(FilterConfig config) { - } + public void init(FilterConfig config) {} @Override - public void destroy() { - } + public void destroy() {} /** * Handle stop requests. diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/WarmupServlet.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/WarmupServlet.java index fd277ed..60d67ca 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/WarmupServlet.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/utils/servlet/WarmupServlet.java @@ -1,20 +1,18 @@ /** * Copyright 2010 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.apphosting.utils.servlet; import java.io.IOException; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/RPCFailedStatusException.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/RPCFailedStatusException.java index c564db2..5f87c41 100644 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/RPCFailedStatusException.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/RPCFailedStatusException.java @@ -3,14 +3,14 @@ import com.google.apphosting.api.ApiProxy; public class RPCFailedStatusException extends ApiProxy.RPCFailedException { - private final int statusCode; + private final int statusCode; - public RPCFailedStatusException(String packageName, String methodName, int statusCode) { - super(packageName, methodName); - this.statusCode = statusCode; - } + public RPCFailedStatusException(String packageName, String methodName, int statusCode) { + super(packageName, methodName); + this.statusCode = statusCode; + } - public int getStatusCode() { - return statusCode; - } + public int getStatusCode() { + return statusCode; + } } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyDelegate.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyDelegate.java index 97c59fe..f88cd42 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyDelegate.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyDelegate.java @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package com.google.apphosting.vmruntime; import com.google.appengine.api.appidentity.AppIdentityServiceFailureException; @@ -36,7 +34,6 @@ import com.google.apphosting.api.ApiProxy.LogRecord; import com.google.apphosting.api.ApiProxy.RPCFailedException; import com.google.apphosting.api.UserServicePb.CreateLoginURLResponse; -import com.google.apphosting.api.UserServicePb.CreateLogoutURLRequest; import com.google.apphosting.api.UserServicePb.CreateLogoutURLResponse; import com.google.apphosting.utils.remoteapi.RemoteApiPb; @@ -117,7 +114,6 @@ public VmApiProxyDelegate() { this(new DefaultHttpClient(createConnectionManager())); } - VmApiProxyDelegate(HttpClient httpclient) { this.defaultTimeoutMs = DEFAULT_RPC_TIMEOUT_MS; this.executor = Executors.newCachedThreadPool(); @@ -128,99 +124,144 @@ public VmApiProxyDelegate() { @Override public byte[] makeSyncCall( - VmApiProxyEnvironment environment, - String packageName, - String methodName, - byte[] requestData) + VmApiProxyEnvironment environment, String packageName, String methodName, byte[] requestData) throws ApiProxyException { - return makeSyncCallWithTimeout(environment, packageName, methodName, requestData, - defaultTimeoutMs); + return makeSyncCallWithTimeout( + environment, packageName, methodName, requestData, defaultTimeoutMs); } private byte[] makeSyncCallWithTimeout( - VmApiProxyEnvironment environment, - String packageName, - String methodName, - byte[] requestData, - int timeoutMs) - throws ApiProxyException { + VmApiProxyEnvironment environment, + String packageName, + String methodName, + byte[] requestData, + int timeoutMs) + throws ApiProxyException { return makeApiCall(environment, packageName, methodName, requestData, timeoutMs, false); } - private byte[] makeApiCall(VmApiProxyEnvironment environment, + private byte[] makeApiCall( + VmApiProxyEnvironment environment, String packageName, String methodName, byte[] requestData, int timeoutMs, boolean wasAsync) { - + // If this was caused by an async call we need to return the pending call semaphore. long start = System.currentTimeMillis(); environment.apiCallStarted(VmRuntimeUtils.MAX_USER_API_CALL_WAIT_MS, wasAsync); - + try { - byte responseData[] = runSyncCall(environment, packageName, methodName, requestData, timeoutMs); + byte responseData[] = + runSyncCall(environment, packageName, methodName, requestData, timeoutMs); long end = System.currentTimeMillis(); if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, String.format( - "Service bridge API call to package: %s, call: %s, of size: %s " + - "complete. Service bridge status code: %s; response " + - "content-length: %s. Took %s ms.", packageName, methodName, requestData.length, 200, - responseData.length, (end - start))); + logger.log( + Level.FINE, + String.format( + "Service bridge API call to package: %s, call: %s, of size: %s " + + "complete. Service bridge status code: %s; response " + + "content-length: %s. Took %s ms.", + packageName, + methodName, + requestData.length, + 200, + responseData.length, + (end - start))); } - + // TODO Remove HACK TO FIX USER_SERVICE ISSUE #164 // Disable with -DUserServiceLocalSchemeHost=false if ("user".equals(packageName)) { String userservicelocal = System.getProperty("UserServiceLocalSchemeHost"); String host = (String) environment.getAttributes().get("com.google.appengine.runtime.host"); - String https = (String) environment.getAttributes().get("com.google.appengine.runtime.https"); - if ((userservicelocal==null || Boolean.valueOf(userservicelocal)) - && host != null && host.length() > 0 - && https!=null && https.length() > 0) { + String https = + (String) environment.getAttributes().get("com.google.appengine.runtime.https"); + if ((userservicelocal == null || Boolean.valueOf(userservicelocal)) + && host != null + && host.length() > 0 + && https != null + && https.length() > 0) { try { if ("CreateLogoutURL".equals(methodName)) { CreateLogoutURLResponse response = new CreateLogoutURLResponse(); response.parseFrom(responseData); URI uri = new URI(response.getLogoutUrl()); - String query=uri.getQuery().replaceAll("https?://[^/]*\\.appspot\\.com", ("on".equalsIgnoreCase(https) ? "https://" : "http://")+host); - response.setLogoutUrl(new URI("on".equalsIgnoreCase(https) ? "https" : "http", uri.getUserInfo(), host, - uri.getPort(), uri.getPath(), query, uri.getFragment()).toASCIIString()); + String query = + uri.getQuery() + .replaceAll( + "https?://[^/]*\\.appspot\\.com", + ("on".equalsIgnoreCase(https) ? "https://" : "http://") + host); + response.setLogoutUrl( + new URI( + "on".equalsIgnoreCase(https) ? "https" : "http", + uri.getUserInfo(), + host, + uri.getPort(), + uri.getPath(), + query, + uri.getFragment()) + .toASCIIString()); return response.toByteArray(); } if ("CreateLoginURL".equals(methodName)) { CreateLoginURLResponse response = new CreateLoginURLResponse(); response.parseFrom(responseData); URI uri = new URI(response.getLoginUrl()); - String query=uri.getQuery().replaceAll("http?://[^/]*\\.appspot\\.com", ("on".equalsIgnoreCase(https) ? "https://" : "http://")+host); - response.setLoginUrl(new URI(uri.getScheme(),uri.getUserInfo(),uri.getHost(), - uri.getPort(), uri.getPath(), query, uri.getFragment()).toASCIIString()); + String query = + uri.getQuery() + .replaceAll( + "http?://[^/]*\\.appspot\\.com", + ("on".equalsIgnoreCase(https) ? "https://" : "http://") + host); + response.setLoginUrl( + new URI( + uri.getScheme(), + uri.getUserInfo(), + uri.getHost(), + uri.getPort(), + uri.getPath(), + query, + uri.getFragment()) + .toASCIIString()); return response.toByteArray(); } } catch (URISyntaxException e) { - logger.log(Level.WARNING,"Problem adjusting UserService URI",e); + logger.log(Level.WARNING, "Problem adjusting UserService URI", e); } } } return responseData; - } catch(Exception e) { + } catch (Exception e) { long end = System.currentTimeMillis(); int statusCode = 200; // default - if (e instanceof RPCFailedStatusException) + if (e instanceof RPCFailedStatusException) { statusCode = ((RPCFailedStatusException) e).getStatusCode(); - logger.log(Level.WARNING, String.format( - "Exception during service bridge API call to package: %s, call: %s, " + - "of size: %s bytes, status code: %d. Took %s ms. %s", packageName, methodName, - requestData.length, statusCode, (end - start), e.getClass().getSimpleName()), e); + } + logger.log( + Level.WARNING, + String.format( + "Exception during service bridge API call to package: %s, call: %s, " + + "of size: %s bytes, status code: %d. Took %s ms. %s", + packageName, + methodName, + requestData.length, + statusCode, + (end - start), + e.getClass().getSimpleName()), + e); throw e; } finally { environment.apiCallCompleted(); } } - - protected byte[] runSyncCall(VmApiProxyEnvironment environment, String packageName, - String methodName, byte[] requestData, int timeoutMs) { + protected byte[] runSyncCall( + VmApiProxyEnvironment environment, + String packageName, + String methodName, + byte[] requestData, + int timeoutMs) { HttpPost request = createRequest(environment, packageName, methodName, requestData, timeoutMs); try { // Create a new http context for each call as the default context is not thread safe. @@ -230,9 +271,10 @@ protected byte[] runSyncCall(VmApiProxyEnvironment environment, String packageNa // Check for HTTP error status and return early. if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { try (Scanner errorStreamScanner = - new Scanner(new BufferedInputStream(response.getEntity().getContent()));) { + new Scanner(new BufferedInputStream(response.getEntity().getContent())); ) { logger.warning("Error body: " + errorStreamScanner.useDelimiter("\\Z").next()); - throw new RPCFailedStatusException(packageName, methodName, response.getStatusLine().getStatusCode()); + throw new RPCFailedStatusException( + packageName, methodName, response.getStatusLine().getStatusCode()); } } try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent())) { @@ -320,8 +362,12 @@ RuntimeException constructApiException(String packageName, String methodName) { * @return an HttpPost object to send to the API. */ // - static HttpPost createRequest(VmApiProxyEnvironment environment, String packageName, - String methodName, byte[] requestData, int timeoutMs) { + static HttpPost createRequest( + VmApiProxyEnvironment environment, + String packageName, + String methodName, + byte[] requestData, + int timeoutMs) { // Wrap the payload in a RemoteApi Request. RemoteApiPb.Request remoteRequest = new RemoteApiPb.Request(); remoteRequest.setServiceName(packageName); @@ -335,12 +381,12 @@ static HttpPost createRequest(VmApiProxyEnvironment environment, String packageN // Set TCP connection timeouts. HttpParams params = new BasicHttpParams(); - params.setLongParameter(ConnManagerPNames.TIMEOUT, - timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); - params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, - timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); - params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, - timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); + params.setLongParameter( + ConnManagerPNames.TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); + params.setIntParameter( + CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); + params.setIntParameter( + CoreConnectionPNames.SO_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); // Performance tweaks. params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.TRUE); @@ -350,7 +396,8 @@ static HttpPost createRequest(VmApiProxyEnvironment environment, String packageN // The request deadline can be overwritten by the environment, read deadline if available. Double deadline = (Double) (environment.getAttributes().get(API_DEADLINE_KEY)); if (deadline == null) { - request.setHeader(RPC_DEADLINE_HEADER, + request.setHeader( + RPC_DEADLINE_HEADER, Double.toString(TimeUnit.SECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS))); } else { request.setHeader(RPC_DEADLINE_HEADER, Double.toString(deadline)); @@ -358,8 +405,10 @@ static HttpPost createRequest(VmApiProxyEnvironment environment, String packageN // If the incoming request has a dapper trace header: set it on outgoing API calls // so they are tied to the original request. - Object dapperHeader = environment.getAttributes() - .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey); + Object dapperHeader = + environment + .getAttributes() + .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey); if (dapperHeader instanceof String) { request.setHeader( VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey, (String) dapperHeader); @@ -368,16 +417,18 @@ static HttpPost createRequest(VmApiProxyEnvironment environment, String packageN // If the incoming request has a Cloud trace header: set it on outgoing API calls // so they are tied to the original request. // TODO(user): For now, this uses the incoming span id - use the one from the active span. - Object traceHeader = environment.getAttributes() - .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); + Object traceHeader = + environment + .getAttributes() + .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); if (traceHeader instanceof String) { request.setHeader( VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.headerKey, (String) traceHeader); } - ByteArrayEntity postPayload = new ByteArrayEntity(remoteRequest.toByteArray(), - ContentType.APPLICATION_OCTET_STREAM); + ByteArrayEntity postPayload = + new ByteArrayEntity(remoteRequest.toByteArray(), ContentType.APPLICATION_OCTET_STREAM); postPayload.setChunked(false); request.setEntity(postPayload); @@ -395,14 +446,11 @@ static HttpPost createRequest(VmApiProxyEnvironment environment, String packageN * @param logger the Logger used to create log messages. * @return ApiProxyException */ - private static ApiProxyException convertRemoteError(RemoteApiPb.Response remoteResponse, - String packageName, String methodName, Logger logger) { + private static ApiProxyException convertRemoteError( + RemoteApiPb.Response remoteResponse, String packageName, String methodName, Logger logger) { if (remoteResponse.hasRpcError()) { return convertApiResponseRpcErrorToException( - remoteResponse.getRpcError(), - packageName, - methodName, - logger); + remoteResponse.getRpcError(), packageName, methodName, logger); } // Otherwise it's an application error @@ -425,14 +473,24 @@ private static ApiProxyException convertApiResponseRpcErrorToException( int rpcCode = rpcError.getCode(); String errorDetail = rpcError.getDetail(); if (rpcCode > RemoteApiPb.RpcError.ErrorCode.values().length) { - logger.severe("Received unrecognized error code from server: " + rpcError.getCode() + - " details: " + errorDetail); + logger.severe( + "Received unrecognized error code from server: " + + rpcError.getCode() + + " details: " + + errorDetail); return new ApiProxy.UnknownException(packageName, methodName); } - RemoteApiPb.RpcError.ErrorCode errorCode = RemoteApiPb.RpcError.ErrorCode.values()[ - rpcError.getCode()]; - logger.warning("RPC failed, API=" + packageName + "." + methodName + " : " - + errorCode + " : " + errorDetail); + RemoteApiPb.RpcError.ErrorCode errorCode = + RemoteApiPb.RpcError.ErrorCode.values()[rpcError.getCode()]; + logger.warning( + "RPC failed, API=" + + packageName + + "." + + methodName + + " : " + + errorCode + + " : " + + errorDetail); // This is very similar to apphosting/utils/runtime/ApiProxyUtils.java#convertApiError, // which is for APIResponse. TODO(user): retire both in favor of gRPC. @@ -445,8 +503,7 @@ private static ApiProxyException convertApiResponseRpcErrorToException( logger.severe("Security violation: invalid request id used!"); return new ApiProxy.UnknownException(packageName, methodName); case CAPABILITY_DISABLED: - return new ApiProxy.CapabilityDisabledException( - errorDetail, packageName, methodName); + return new ApiProxy.CapabilityDisabledException(errorDetail, packageName, methodName); case OVER_QUOTA: return new ApiProxy.OverQuotaException(packageName, methodName); case REQUEST_TOO_LARGE: @@ -458,8 +515,7 @@ private static ApiProxyException convertApiResponseRpcErrorToException( case CANCELLED: return new ApiProxy.CancelledException(packageName, methodName); case FEATURE_DISABLED: - return new ApiProxy.FeatureNotEnabledException( - errorDetail, packageName, methodName); + return new ApiProxy.FeatureNotEnabledException(errorDetail, packageName, methodName); case DEADLINE_EXCEEDED: return new ApiProxy.ApiDeadlineExceededException(packageName, methodName); default: @@ -475,7 +531,8 @@ private class MakeSyncCall implements Callable { private final byte[] requestData; private final int timeoutMs; - public MakeSyncCall(VmApiProxyDelegate delegate, + public MakeSyncCall( + VmApiProxyDelegate delegate, VmApiProxyEnvironment environment, String packageName, String methodName, @@ -491,29 +548,25 @@ public MakeSyncCall(VmApiProxyDelegate delegate, @Override public byte[] call() throws Exception { - return delegate.makeApiCall(environment, - packageName, - methodName, - requestData, - timeoutMs, - true); + return delegate.makeApiCall( + environment, packageName, methodName, requestData, timeoutMs, true); } } @Override public Future makeAsyncCall( - VmApiProxyEnvironment environment, - String packageName, - String methodName, - byte[] request, - ApiConfig apiConfig) { + VmApiProxyEnvironment environment, + String packageName, + String methodName, + byte[] request, + ApiConfig apiConfig) { int timeoutMs = defaultTimeoutMs; if (apiConfig != null && apiConfig.getDeadlineInSeconds() != null) { timeoutMs = (int) (apiConfig.getDeadlineInSeconds() * 1000); } environment.aSyncApiCallAdded(VmRuntimeUtils.MAX_USER_API_CALL_WAIT_MS); - return executor.submit(new MakeSyncCall(this, environment, packageName, - methodName, request, timeoutMs)); + return executor.submit( + new MakeSyncCall(this, environment, packageName, methodName, request, timeoutMs)); } @Override diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java index f3a8eb9..c3e30bd 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package com.google.apphosting.vmruntime; import com.google.apphosting.api.ApiProxy; @@ -23,7 +21,6 @@ import com.google.apphosting.runtime.timer.Timer; import com.google.apphosting.utils.http.HttpRequest; - import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -95,27 +92,24 @@ public class VmApiProxyEnvironment implements ApiProxy.Environment { public static final String BACKEND_ID_KEY = "com.google.appengine.backend.id"; - public static final String INSTANCE_ID_KEY = "com.google.appengine.instance.id"; public static final String AFFINITY_KEY = "com.google.appengine.affinity"; public static final String REQUEST_THREAD_FACTORY_ATTR = - "com.google.appengine.api.ThreadManager.REQUEST_THREAD_FACTORY"; + "com.google.appengine.api.ThreadManager.REQUEST_THREAD_FACTORY"; public static final String BACKGROUND_THREAD_FACTORY_ATTR = - "com.google.appengine.api.ThreadManager.BACKGROUND_THREAD_FACTORY"; + "com.google.appengine.api.ThreadManager.BACKGROUND_THREAD_FACTORY"; // If the "X-AppEngine-Federated-Identity" header is included in the request this attribute // should be set to the boolean true, otherwise it should be set to false. - public static final String IS_FEDERATED_USER_KEY = - "com.google.appengine.api.users.UserService.is_federated_user"; + "com.google.appengine.api.users.UserService.is_federated_user"; // If the app is trusted AND the "X-AppEngine-Trusted-IP-Request" header is "1" this attribute // should be set the the boolean true, otherwise it should be set to false. - public static final String IS_TRUSTED_IP_KEY = "com.google.appengine.runtime.is_trusted_ip"; public static final String IS_TRUSTED_IP_HEADER = "X-AppEngine-Trusted-IP-Request"; @@ -142,84 +136,69 @@ public class VmApiProxyEnvironment implements ApiProxy.Environment { */ enum AttributeMapping { USER_ID( - "X-AppEngine-User-Id", - "com.google.appengine.api.users.UserService.user_id_key", - "", false), + "X-AppEngine-User-Id", "com.google.appengine.api.users.UserService.user_id_key", "", false), USER_ORGANIZATION( - "X-AppEngine-User-Organization", - "com.google.appengine.api.users.UserService.user_organization", - "", false), + "X-AppEngine-User-Organization", + "com.google.appengine.api.users.UserService.user_organization", + "", + false), FEDERATED_IDENTITY( - "X-AppEngine-Federated-Identity", - "com.google.appengine.api.users.UserService.federated_identity", - "", false), + "X-AppEngine-Federated-Identity", + "com.google.appengine.api.users.UserService.federated_identity", + "", + false), FEDERATED_PROVIDER( - "X-AppEngine-Federated-Provider", - "com.google.appengine.api.users.UserService.federated_authority", - "", false), + "X-AppEngine-Federated-Provider", + "com.google.appengine.api.users.UserService.federated_authority", + "", + false), DATACENTER( - "X-AppEngine-Datacenter", - "com.google.apphosting.api.ApiProxy.datacenter", - "", false), + "X-AppEngine-Datacenter", "com.google.apphosting.api.ApiProxy.datacenter", "", false), REQUEST_ID_HASH( - "X-AppEngine-Request-Id-Hash", - "com.google.apphosting.api.ApiProxy.request_id_hash", - null, false), + "X-AppEngine-Request-Id-Hash", + "com.google.apphosting.api.ApiProxy.request_id_hash", + null, + false), REQUEST_LOG_ID( - "X-AppEngine-Request-Log-Id", - "com.google.appengine.runtime.request_log_id", - null, false), - DAPPER_ID("X-Google-DapperTraceInfo", - "com.google.appengine.runtime.dapper_id", - null, false), - CLOUD_TRACE_CONTEXT("X-Cloud-Trace-Context", - "com.google.appengine.runtime.cloud_trace_context", - null, false), + "X-AppEngine-Request-Log-Id", "com.google.appengine.runtime.request_log_id", null, false), + DAPPER_ID("X-Google-DapperTraceInfo", "com.google.appengine.runtime.dapper_id", null, false), + CLOUD_TRACE_CONTEXT( + "X-Cloud-Trace-Context", "com.google.appengine.runtime.cloud_trace_context", null, false), DEFAULT_VERSION_HOSTNAME( - "X-AppEngine-Default-Version-Hostname", - "com.google.appengine.runtime.default_version_hostname", - null, false), + "X-AppEngine-Default-Version-Hostname", + "com.google.appengine.runtime.default_version_hostname", + null, + false), DEFAULT_NAMESPACE_HEADER( - "X-AppEngine-Default-Namespace", - "com.google.appengine.api.NamespaceManager.appsNamespace", - null, false), + "X-AppEngine-Default-Namespace", + "com.google.appengine.api.NamespaceManager.appsNamespace", + null, + false), CURRENT_NAMESPACE_HEADER( - "X-AppEngine-Current-Namespace", - "com.google.appengine.api.NamespaceManager.currentNamespace", - null, false), + "X-AppEngine-Current-Namespace", + "com.google.appengine.api.NamespaceManager.currentNamespace", + null, + false), // ########## Trusted app attributes below. ############## LOAS_PEER_USERNAME( - "X-AppEngine-LOAS-Peer-Username", - "com.google.net.base.peer.loas_peer_username", - "", true), - GAIA_ID( - "X-AppEngine-Gaia-Id", - "com.google.appengine.runtime.gaia_id", - "", true), + "X-AppEngine-LOAS-Peer-Username", "com.google.net.base.peer.loas_peer_username", "", true), + GAIA_ID("X-AppEngine-Gaia-Id", "com.google.appengine.runtime.gaia_id", "", true), GAIA_AUTHUSER( - "X-AppEngine-Gaia-Authuser", - "com.google.appengine.runtime.gaia_authuser", - "", true), - GAIA_SESSION( - "X-AppEngine-Gaia-Session", - "com.google.appengine.runtime.gaia_session", - "", true), + "X-AppEngine-Gaia-Authuser", "com.google.appengine.runtime.gaia_authuser", "", true), + GAIA_SESSION("X-AppEngine-Gaia-Session", "com.google.appengine.runtime.gaia_session", "", true), APPSERVER_DATACENTER( - "X-AppEngine-Appserver-Datacenter", - "com.google.appengine.runtime.appserver_datacenter", - "", true), + "X-AppEngine-Appserver-Datacenter", + "com.google.appengine.runtime.appserver_datacenter", + "", + true), APPSERVER_TASK_BNS( - "X-AppEngine-Appserver-Task-Bns", - "com.google.appengine.runtime.appserver_task_bns", - "", true), - HTTPS( - HTTPS_HEADER, - "com.google.appengine.runtime.https", - "off", false), - HOST( - "Host", - "com.google.appengine.runtime.host", - null, false),; + "X-AppEngine-Appserver-Task-Bns", + "com.google.appengine.runtime.appserver_task_bns", + "", + true), + HTTPS(HTTPS_HEADER, "com.google.appengine.runtime.https", "off", false), + HOST("Host", "com.google.appengine.runtime.host", null, false), + ; String headerKey; String attributeKey; @@ -237,7 +216,7 @@ enum AttributeMapping { * @param trustedAppOnly If true the attribute should only be set for trusted apps. */ AttributeMapping( - String headerKey, String attributeKey, Object defaultValue, boolean trustedAppOnly) { + String headerKey, String attributeKey, Object defaultValue, boolean trustedAppOnly) { this.headerKey = headerKey; this.attributeKey = attributeKey; this.defaultValue = defaultValue; @@ -254,8 +233,11 @@ enum AttributeMapping { * @param cache the metadata server cache. * @return If set the environment variable corresponding to envKey, the metadata entry otherwise. */ - public static String getEnvOrMetadata(Map environmentMap, VmMetadataCache cache, - String envKey, String metadataPath) { + public static String getEnvOrMetadata( + Map environmentMap, + VmMetadataCache cache, + String envKey, + String metadataPath) { String envValue = environmentMap.get(envKey); return envValue != null ? envValue : cache.getMetadata(metadataPath); } @@ -269,9 +251,8 @@ public static String getEnvOrMetadata(Map environmentMap, VmMeta * @param dftValue the default value * @return the System property or Env variable is true */ - public static String getSystemPropertyOrEnv(Map environmentMap, - String envKey, - String dftValue) { + public static String getSystemPropertyOrEnv( + Map environmentMap, String envKey, String dftValue) { return System.getProperty(envKey, environmentMap.getOrDefault(envKey, dftValue)); } @@ -284,9 +265,8 @@ public static String getSystemPropertyOrEnv(Map environmentMap, * @param dftValue the default value * @return true if the System property or Env variable is true */ - public static boolean getSystemPropertyOrEnvBoolean(Map environmentMap, - String envKey, - boolean dftValue) { + public static boolean getSystemPropertyOrEnvBoolean( + Map environmentMap, String envKey, boolean dftValue) { return Boolean.valueOf(getSystemPropertyOrEnv(environmentMap, envKey, valueOf(dftValue))); } @@ -301,12 +281,13 @@ public static boolean getSystemPropertyOrEnvBoolean(Map environm * @param appDir the canonical folder of the application. * @return the created Environment object which can be registered with the ApiProxy. */ - public static VmApiProxyEnvironment createDefaultContext(Map envMap, - VmMetadataCache cache, - String server, - Timer wallTimer, - Long millisUntilSoftDeadline, - String appDir) { + public static VmApiProxyEnvironment createDefaultContext( + Map envMap, + VmMetadataCache cache, + String server, + Timer wallTimer, + Long millisUntilSoftDeadline, + String appDir) { final String longAppId = getEnvOrMetadata(envMap, cache, LONG_APP_ID_KEY, PROJECT_ATTRIBUTE); final String partition = getEnvOrMetadata(envMap, cache, PARTITION_KEY, PARTITION_ATTRIBUTE); final String module = getEnvOrMetadata(envMap, cache, MODULE_NAME_KEY, BACKEND_ATTRIBUTE); @@ -317,14 +298,15 @@ public static VmApiProxyEnvironment createDefaultContext(Map env } final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); - final String appengineHostname = getEnvOrMetadata( - envMap, cache, APPENGINE_HOSTNAME_KEY, APPENGINE_HOSTNAME_ATTRIBUTE); + final String appengineHostname = + getEnvOrMetadata(envMap, cache, APPENGINE_HOSTNAME_KEY, APPENGINE_HOSTNAME_ATTRIBUTE); final String ticket = null; final String email = null; final boolean admin = false; final String authDomain = null; - final boolean useMvmAgent = Boolean.parseBoolean(getEnvOrMetadata( - envMap, cache, USE_MVM_AGENT_KEY, USE_MVM_AGENT_ATTRIBUTE)); + final boolean useMvmAgent = + Boolean.parseBoolean( + getEnvOrMetadata(envMap, cache, USE_MVM_AGENT_KEY, USE_MVM_AGENT_ATTRIBUTE)); Map attributes = new HashMap<>(); // Fill in default attributes values. @@ -341,9 +323,24 @@ public static VmApiProxyEnvironment createDefaultContext(Map env attributes.put(BACKEND_ID_KEY, module); attributes.put(INSTANCE_ID_KEY, instance); attributes.put(AFFINITY_KEY, affinity); - VmApiProxyEnvironment defaultEnvironment = new VmApiProxyEnvironment(server, ticket, longAppId, - partition, module, majorVersion, minorVersion, instance, appengineHostname, email, admin, - authDomain, useMvmAgent, wallTimer, millisUntilSoftDeadline, attributes); + VmApiProxyEnvironment defaultEnvironment = + new VmApiProxyEnvironment( + server, + ticket, + longAppId, + partition, + module, + majorVersion, + minorVersion, + instance, + appengineHostname, + email, + admin, + authDomain, + useMvmAgent, + wallTimer, + millisUntilSoftDeadline, + attributes); // Add the thread factories required by the threading API. attributes.put(REQUEST_THREAD_FACTORY_ATTR, new VmRequestThreadFactory(null)); // Since we register VmEnvironmentFactory with ApiProxy in VmRuntimeWebAppContext, @@ -363,13 +360,14 @@ public static VmApiProxyEnvironment createDefaultContext(Map env * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @return the created Environment object which can be registered with the ApiProxy. */ - public static VmApiProxyEnvironment createFromHeaders(Map envMap, - VmMetadataCache cache, - HttpRequest request, - String server, - Timer wallTimer, - Long millisUntilSoftDeadline, - VmApiProxyEnvironment defaultEnvironment) { + public static VmApiProxyEnvironment createFromHeaders( + Map envMap, + VmMetadataCache cache, + HttpRequest request, + String server, + Timer wallTimer, + Long millisUntilSoftDeadline, + VmApiProxyEnvironment defaultEnvironment) { final String longAppId = getEnvOrMetadata(envMap, cache, LONG_APP_ID_KEY, PROJECT_ATTRIBUTE); final String partition = getEnvOrMetadata(envMap, cache, PARTITION_KEY, PARTITION_ATTRIBUTE); final String module = getEnvOrMetadata(envMap, cache, MODULE_NAME_KEY, BACKEND_ATTRIBUTE); @@ -379,9 +377,10 @@ public static VmApiProxyEnvironment createFromHeaders(Map envMap final boolean useMvmAgent = defaultEnvironment.getUseMvmAgent(); final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); - final String ticket = getSystemPropertyOrEnvBoolean(envMap, USE_GLOBAL_TICKET_KEY, false) - ? null - : request.getHeader(TICKET_HEADER); + final String ticket = + getSystemPropertyOrEnvBoolean(envMap, USE_GLOBAL_TICKET_KEY, false) + ? null + : request.getHeader(TICKET_HEADER); final String email = request.getHeader(EMAIL_HEADER); boolean admin = false; String value = request.getHeader(IS_ADMIN_HEADER); @@ -407,7 +406,7 @@ public static VmApiProxyEnvironment createFromHeaders(Map envMap attributes.put(mapping.attributeKey, headerValue); } else if (mapping.defaultValue != null) { attributes.put(mapping.attributeKey, mapping.defaultValue); - } // else: The attribute is expected to be missing if the header is not set. + } // else: The attribute is expected to be missing if the header is not set. } // Fill in the special attributes that do not fit the simple mapping model. @@ -424,9 +423,24 @@ public static VmApiProxyEnvironment createFromHeaders(Map envMap attributes.put(IS_TRUSTED_IP_KEY, trustedIp); } - VmApiProxyEnvironment requestEnvironment = new VmApiProxyEnvironment(server, ticket, longAppId, - partition, module, majorVersion, minorVersion, instance, appengineHostname, email, admin, - authDomain, useMvmAgent, wallTimer, millisUntilSoftDeadline, attributes); + VmApiProxyEnvironment requestEnvironment = + new VmApiProxyEnvironment( + server, + ticket, + longAppId, + partition, + module, + majorVersion, + minorVersion, + instance, + appengineHostname, + email, + admin, + authDomain, + useMvmAgent, + wallTimer, + millisUntilSoftDeadline, + attributes); // Add the thread factories required by the threading API. attributes.put(REQUEST_THREAD_FACTORY_ATTR, new VmRequestThreadFactory(requestEnvironment)); // Since we register VmEnvironmentFactory with ApiProxy in VmRuntimeWebAppContext, @@ -437,7 +451,7 @@ public static VmApiProxyEnvironment createFromHeaders(Map envMap } private final String server; - private volatile String ticket; // request ticket is only valid until response is committed. + private volatile String ticket; // request ticket is only valid until response is committed. private volatile String globalTicket; // global ticket is always valid private final int serverPort; private final String partition; @@ -454,8 +468,8 @@ public static VmApiProxyEnvironment createFromHeaders(Map envMap private final boolean useMvmAgent; private final Map attributes; private ThreadLocal> threadLocalAttributes; - private final Timer wallTimer; // may be null if millisUntilSoftDeadline is null. - private final Long millisUntilSoftDeadline; // may be null (no deadline). + private final Timer wallTimer; // may be null if millisUntilSoftDeadline is null. + private final Long millisUntilSoftDeadline; // may be null (no deadline). final Semaphore pendingApiCallSemaphore; @@ -482,10 +496,22 @@ public static VmApiProxyEnvironment createFromHeaders(Map envMap * @param attributes map containing any attributes set on this environment. */ private VmApiProxyEnvironment( - String server, String ticket, String appId, String partition, String module, - String majorVersion, String minorVersion, String instance, String appengineHostname, - String email, boolean admin, String authDomain, boolean useMvmAgent, Timer wallTimer, - Long millisUntilSoftDeadline, Map attributes) { + String server, + String ticket, + String appId, + String partition, + String module, + String majorVersion, + String minorVersion, + String instance, + String appengineHostname, + String email, + boolean admin, + String authDomain, + boolean useMvmAgent, + Timer wallTimer, + Long millisUntilSoftDeadline, + Map attributes) { if (server == null || server.isEmpty()) { throw new IllegalArgumentException("proxy server host:port must be specified"); } @@ -494,13 +520,19 @@ private VmApiProxyEnvironment( } this.ticket = ticket; - if ((appId == null || appId.isEmpty()) || - (module == null || module.isEmpty()) || - (majorVersion == null || majorVersion.isEmpty()) || - (instance == null || instance.isEmpty())) { + if ((appId == null || appId.isEmpty()) + || (module == null || module.isEmpty()) + || (majorVersion == null || majorVersion.isEmpty()) + || (instance == null || instance.isEmpty())) { throw new IllegalArgumentException( - "When ticket == null, the following must be specified: appId=" + appId - + ", module=" + module + ", version=" + majorVersion + ", instance=" + instance); + "When ticket == null, the following must be specified: appId=" + + appId + + ", module=" + + module + + ", version=" + + majorVersion + + ", instance=" + + instance); } String escapedAppId = appId.replace(':', '_').replace('.', '_'); @@ -508,8 +540,10 @@ private VmApiProxyEnvironment( this.server = server; this.partition = partition; - String port = System.getenv(GAE_SERVER_PORT) == null ? - System.getProperty("GAE_SERVER_PORT", "80") : System.getenv(GAE_SERVER_PORT); + String port = + System.getenv(GAE_SERVER_PORT) == null + ? System.getProperty("GAE_SERVER_PORT", "80") + : System.getenv(GAE_SERVER_PORT); this.serverPort = Integer.decode(port); this.appId = partition + "~" + appId; this.module = module == null ? "default" : module; @@ -517,8 +551,9 @@ private VmApiProxyEnvironment( this.minorVersion = minorVersion == null ? "" : minorVersion; this.versionId = String.format("%s.%s", this.majorVersion, this.minorVersion); this.appengineHostname = appengineHostname; - this.l7UnsafeRedirectUrl = String.format("https://%s-dot-%s-dot-%s", - this.majorVersion, this.module, this.appengineHostname); + this.l7UnsafeRedirectUrl = + String.format( + "https://%s-dot-%s-dot-%s", this.majorVersion, this.module, this.appengineHostname); this.email = email == null ? "" : email; this.admin = admin; this.authDomain = authDomain == null ? "" : authDomain; @@ -537,8 +572,7 @@ private VmApiProxyEnvironment( } @Deprecated - public void addLogRecord(LogRecord record) { - } + public void addLogRecord(LogRecord record) {} @Deprecated public int flushLogs() { @@ -630,7 +664,7 @@ public boolean getUseMvmAgent() { @Override public String getRequestNamespace() { Object currentNamespace = - attributes.get(AttributeMapping.CURRENT_NAMESPACE_HEADER.attributeKey); + attributes.get(AttributeMapping.CURRENT_NAMESPACE_HEADER.attributeKey); if (currentNamespace instanceof String) { return (String) currentNamespace; } @@ -682,7 +716,7 @@ void aSyncApiCallAdded(long maxWaitMs) throws ApiProxyException { throw new ApiProxyException("Timed out while acquiring a pending API call semaphore."); } catch (InterruptedException e) { throw new ApiProxyException( - "Thread interrupted while acquiring a pending API call semaphore."); + "Thread interrupted while acquiring a pending API call semaphore."); } } @@ -727,12 +761,12 @@ public boolean waitForAllApiCallsToComplete(long maxWaitMs) { try { long startTime = System.currentTimeMillis(); if (pendingApiCallSemaphore.tryAcquire( - MAX_PENDING_API_CALLS, maxWaitMs, TimeUnit.MILLISECONDS)) { + MAX_PENDING_API_CALLS, maxWaitMs, TimeUnit.MILLISECONDS)) { // Release the acquired semaphores in finally {} to guarantee that they are returned. try { long remaining = maxWaitMs - (System.currentTimeMillis() - startTime); if (runningApiCallSemaphore.tryAcquire( - MAX_CONCURRENT_API_CALLS, remaining, TimeUnit.MILLISECONDS)) { + MAX_CONCURRENT_API_CALLS, remaining, TimeUnit.MILLISECONDS)) { runningApiCallSemaphore.release(MAX_CONCURRENT_API_CALLS); return true; } @@ -747,7 +781,9 @@ public boolean waitForAllApiCallsToComplete(long maxWaitMs) { } public String getTraceId() { - Object value = getAttributes().get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); + Object value = + getAttributes() + .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); if (!(value instanceof String)) { return null; } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmAppLogsWriter.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmAppLogsWriter.java index 249f793..70d9daa 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmAppLogsWriter.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmAppLogsWriter.java @@ -1,20 +1,18 @@ /** * Copyright 2010 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.apphosting.vmruntime; import com.google.apphosting.api.ApiProxy; @@ -71,8 +69,7 @@ */ @Deprecated class VmAppLogsWriter { - private static final Logger logger = - Logger.getLogger(VmAppLogsWriter.class.getName()); + private static final Logger logger = Logger.getLogger(VmAppLogsWriter.class.getName()); // (Some constants below package scope for testability) static final String LOG_CONTINUATION_SUFFIX = "\n"; @@ -116,15 +113,19 @@ class VmAppLogsWriter { * minutes. The initial log will stay cached until the second message * is logged. */ - public VmAppLogsWriter(List buffer, long maxBytesToFlush, int maxLogMessageLength, + public VmAppLogsWriter( + List buffer, + long maxBytesToFlush, + int maxLogMessageLength, int maxFlushSeconds) { this.buffer = buffer; this.maxSecondsBetweenFlush = maxFlushSeconds; if (maxLogMessageLength < MIN_MAX_LOG_MESSAGE_LENGTH) { - String message = String.format( - "maxLogMessageLength silly small (%s); setting maxLogMessageLength to %s", - maxLogMessageLength, MIN_MAX_LOG_MESSAGE_LENGTH); + String message = + String.format( + "maxLogMessageLength silly small (%s); setting maxLogMessageLength to %s", + maxLogMessageLength, MIN_MAX_LOG_MESSAGE_LENGTH); logger.warning(message); this.maxLogMessageLength = MIN_MAX_LOG_MESSAGE_LENGTH; } else { @@ -135,9 +136,10 @@ public VmAppLogsWriter(List buffer, long maxBytesToFlush, int ma // This should never happen, but putting here just in case. if (maxBytesToFlush < this.maxLogMessageLength) { - String message = String.format( - "maxBytesToFlush (%s) smaller than maxLogMessageLength (%s)", - maxBytesToFlush, this.maxLogMessageLength); + String message = + String.format( + "maxBytesToFlush (%s) smaller than maxLogMessageLength (%s)", + maxBytesToFlush, this.maxLogMessageLength); logger.warning(message); this.maxBytesToFlush = this.maxLogMessageLength; } else { @@ -156,7 +158,7 @@ public VmAppLogsWriter(List buffer, long maxBytesToFlush, int ma * this method may block. */ synchronized void addLogRecordAndMaybeFlush(LogRecord fullRecord) { - for (LogRecord record : split(fullRecord)){ + for (LogRecord record : split(fullRecord)) { UserAppLogLine logLine = new UserAppLogLine(); logLine.setLevel(record.getLevel().ordinal()); logLine.setTimestampUsec(record.getTimestamp()); @@ -165,8 +167,7 @@ synchronized void addLogRecordAndMaybeFlush(LogRecord fullRecord) { // enough for us. It uses the maximum possible size for varint // values, but the real size of strings. int maxEncodingSize = logLine.maxEncodingSize(); - if (maxBytesToFlush > 0 && - (currentByteCount + maxEncodingSize) > maxBytesToFlush) { + if (maxBytesToFlush > 0 && (currentByteCount + maxEncodingSize) > maxBytesToFlush) { logger.info(currentByteCount + " bytes of app logs pending, starting flush..."); waitForCurrentFlushAndStartNewFlush(); } @@ -181,8 +182,8 @@ synchronized void addLogRecordAndMaybeFlush(LogRecord fullRecord) { currentByteCount += maxEncodingSize; } - if (maxSecondsBetweenFlush > 0 && - stopwatch.elapsed(TimeUnit.SECONDS) >= maxSecondsBetweenFlush) { + if (maxSecondsBetweenFlush > 0 + && stopwatch.elapsed(TimeUnit.SECONDS) >= maxSecondsBetweenFlush) { waitForCurrentFlushAndStartNewFlush(); } } @@ -228,16 +229,19 @@ private void waitForCurrentFlush() { VmApiProxyDelegate.ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS + LOG_FLUSH_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { - logger.warning("Interruped while blocking on a log flush, setting interrupt bit and " + - "continuing. Some logs may be lost or occur out of order!"); + logger.warning( + "Interruped while blocking on a log flush, setting interrupt bit and " + + "continuing. Some logs may be lost or occur out of order!"); Thread.currentThread().interrupt(); } catch (TimeoutException e) { - logger.log(Level.WARNING, "Timeout waiting for log flush to complete. " - + "Log messages may have been lost/reordered!", e); - } catch (ExecutionException ex) { logger.log( Level.WARNING, - "A log flush request failed. Log messages may have been lost!", ex); + "Timeout waiting for log flush to complete. " + + "Log messages may have been lost/reordered!", + e); + } catch (ExecutionException ex) { + logger.log( + Level.WARNING, "A log flush request failed. Log messages may have been lost!", ex); } currentFlush = null; } @@ -277,19 +281,18 @@ private Future doFlush() { * that the message is continued in the following log message or is a * continuation of the previous log mesage. */ - - List split(LogRecord aRecord){ + List split(LogRecord aRecord) { // This method is public so it is testable. LinkedList theList = new LinkedList(); String message = aRecord.getMessage(); - if (null == message || message.length() <= maxLogMessageLength){ + if (null == message || message.length() <= maxLogMessageLength) { theList.add(aRecord); return theList; } String remaining = message; - while (remaining.length() > 0){ + while (remaining.length() > 0) { String nextMessage; - if (remaining.length() <= maxLogMessageLength){ + if (remaining.length() <= maxLogMessageLength) { nextMessage = remaining; remaining = ""; } else { @@ -298,7 +301,7 @@ List split(LogRecord aRecord){ // Try to cut the string at a friendly point int friendlyCutLength = remaining.lastIndexOf('\n', logCutLength); // But only if that yields a message of reasonable length - if (friendlyCutLength > logCutLengthDiv10){ + if (friendlyCutLength > logCutLengthDiv10) { cutLength = friendlyCutLength; cutAtNewline = true; } @@ -306,8 +309,8 @@ List split(LogRecord aRecord){ remaining = remaining.substring(cutLength + (cutAtNewline ? 1 : 0)); // Only prepend the continuation prefix if doing so would not push // the length of the next message over the limit. - if (remaining.length() > maxLogMessageLength || - remaining.length() + LOG_CONTINUATION_PREFIX_LENGTH <= maxLogMessageLength){ + if (remaining.length() > maxLogMessageLength + || remaining.length() + LOG_CONTINUATION_PREFIX_LENGTH <= maxLogMessageLength) { remaining = LOG_CONTINUATION_PREFIX + remaining; } } @@ -323,7 +326,6 @@ List split(LogRecord aRecord){ * * @param stopwatch The {@link Stopwatch} instance to use. */ - void setStopwatch(Stopwatch stopwatch) { this.stopwatch = stopwatch; } @@ -333,7 +335,6 @@ void setStopwatch(Stopwatch stopwatch) { * * This method is not simply visible for testing, it only exists for testing. */ - int getMaxLogMessageLength() { return maxLogMessageLength; } @@ -343,7 +344,6 @@ int getMaxLogMessageLength() { * * This code is not simply visible for testing, it only exists for testing. */ - long getByteCountBeforeFlushing() { return maxBytesToFlush; } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmEnvironmentFactory.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmEnvironmentFactory.java index df92afd..dd0b188 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmEnvironmentFactory.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmEnvironmentFactory.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime; import com.google.apphosting.api.ApiProxy; @@ -23,15 +22,15 @@ * with a thread local copy of the attributes, since they are mutable. */ public class VmEnvironmentFactory implements ApiProxy.EnvironmentFactory { - private final VmApiProxyEnvironment defaultEnvironment; + private final VmApiProxyEnvironment defaultEnvironment; - public VmEnvironmentFactory(VmApiProxyEnvironment defaultEnvironment) { - this.defaultEnvironment = defaultEnvironment; - } + public VmEnvironmentFactory(VmApiProxyEnvironment defaultEnvironment) { + this.defaultEnvironment = defaultEnvironment; + } - @Override - public ApiProxy.Environment newEnvironment() { - defaultEnvironment.setThreadLocalAttributes(); - return defaultEnvironment; - } + @Override + public ApiProxy.Environment newEnvironment() { + defaultEnvironment.setThreadLocalAttributes(); + return defaultEnvironment; + } } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmMetadataCache.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmMetadataCache.java index 06813c3..a74736a 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmMetadataCache.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmMetadataCache.java @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package com.google.apphosting.vmruntime; import java.io.BufferedReader; @@ -129,8 +127,11 @@ protected String getMetadataFromServer(String path) throws IOException { } else if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { return null; } - throw new IOException("Meta-data request for '" + path + "' failed with error: " - + connection.getResponseMessage()); + throw new IOException( + "Meta-data request for '" + + path + + "' failed with error: " + + connection.getResponseMessage()); } finally { if (reader != null) { try { diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestThreadFactory.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestThreadFactory.java index b354e2a..dfb21e5 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestThreadFactory.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestThreadFactory.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime; import static com.google.appengine.repackaged.com.google.common.base.Preconditions.checkArgument; @@ -29,8 +28,6 @@ import java.util.logging.Level; import java.util.logging.Logger; - - /** * Thread factory creating threads with a request specific thread local environment. * @@ -70,20 +67,24 @@ public VmRequestThreadFactory(Environment requestEnvironment) { */ @Override public Thread newThread(final Runnable runnable) { - checkState(requestEnvironment != null, + checkState( + requestEnvironment != null, "Request threads can only be created within the context of a running request."); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - if (runnable == null) { - return; - } - checkState(allowNewRequestThreadCreation, - "Cannot start new threads after the request thread stops."); - ApiProxy.setEnvironmentForCurrentThread(requestEnvironment); - runnable.run(); - } - }); + Thread thread = + new Thread( + new Runnable() { + @Override + public void run() { + if (runnable == null) { + return; + } + checkState( + allowNewRequestThreadCreation, + "Cannot start new threads after the request thread stops."); + ApiProxy.setEnvironmentForCurrentThread(requestEnvironment); + runnable.run(); + } + }); checkState( allowNewRequestThreadCreation, "Cannot create new threads after the request thread stops."); synchronized (mutex) { @@ -109,8 +110,9 @@ public void interruptRequestThreads() { synchronized (mutex) { for (Thread thread : createdThreads) { if (thread.isAlive()) { - logger.warning(String.format( - "Request thread %s is still alive, forcing interrupt.", thread.getName())); + logger.warning( + String.format( + "Request thread %s is still alive, forcing interrupt.", thread.getName())); } thread.interrupt(); } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestUtils.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestUtils.java index 94625d1..2a6a0a0 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestUtils.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRequestUtils.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime; /** diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeFileLogHandler.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeFileLogHandler.java index 4a8b61c..df3893e 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeFileLogHandler.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeFileLogHandler.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime; import com.google.apphosting.api.ApiProxy; @@ -33,7 +32,7 @@ * */ public class VmRuntimeFileLogHandler extends FileHandler { - + // This exists for testing purposes only. If set, the cloud logger may lose logs. public static final String LOG_DIRECTORY_PROPERTY = "com.google.apphosting.logs"; public static final String LOG_PATTERN_CONFIG_PROPERTY = @@ -41,8 +40,7 @@ public class VmRuntimeFileLogHandler extends FileHandler { // Log files to /var/log/app_engine/app.[0-2].log.json private static final String DEFAULT_LOG_DIRECTORY = "/var/log/app_engine"; private static final String DEFAULT_LOG_PATTERN = "app.%g.log.json"; - private static final String APP_ENGINE_LOG_CONFIG_PATTERN_ENV = - "APP_ENGINE_LOG_CONFIG_PATTERN"; + private static final String APP_ENGINE_LOG_CONFIG_PATTERN_ENV = "APP_ENGINE_LOG_CONFIG_PATTERN"; private static final int LOG_MAX_SIZE = 100 * 1024 * 1024; private static final int LOG_MAX_FILES = 3; public static final String JAVA_UTIL_LOGGING_CONFIG_PROPERTY = "java.util.logging.config.file"; @@ -59,17 +57,18 @@ private static String fileLogPattern() { if (pattern != null) { return pattern; } - - String directory = System.getProperty(LOG_DIRECTORY_PROPERTY,DEFAULT_LOG_DIRECTORY); - + + String directory = System.getProperty(LOG_DIRECTORY_PROPERTY, DEFAULT_LOG_DIRECTORY); + pattern = System.getProperty(LOG_PATTERN_CONFIG_PROPERTY); if (pattern != null) { - if (pattern.startsWith("/")) + if (pattern.startsWith("/")) { return pattern; - return directory+"/"+pattern; + } + return directory + "/" + pattern; } - - return directory+"/"+DEFAULT_LOG_PATTERN; + + return directory + "/" + DEFAULT_LOG_PATTERN; } /** @@ -90,7 +89,7 @@ public static void init() throws IOException { * Reloads logging to pick up changes to the java.util.logging.config.file system property. */ private static void reloadLoggingProperties(LogManager logManager) { - String logging=System.getProperty(VmRuntimeFileLogHandler.JAVA_UTIL_LOGGING_CONFIG_PROPERTY); + String logging = System.getProperty(VmRuntimeFileLogHandler.JAVA_UTIL_LOGGING_CONFIG_PROPERTY); if (logging == null) { return; } diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeUtils.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeUtils.java index 960197d..ad99d48 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeUtils.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmRuntimeUtils.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime; import static com.google.appengine.repackaged.com.google.common.base.MoreObjects.firstNonNull; @@ -24,7 +23,6 @@ import com.google.apphosting.utils.http.HttpRequest; import com.google.apphosting.utils.http.HttpResponse; - import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -126,7 +124,6 @@ public static void handleSkipAdminCheck(HttpRequest request) { /** * Set the Environment system property to Development or Production. */ - static void setEnvironmentSystemProperty(String partition) { if ("dev".equals(partition)) { System.setProperty( @@ -148,7 +145,7 @@ public static void installSystemProperties( SystemProperty.applicationId.key(), AppId.parse(environment.getAppId()).getLongAppId()); System.setProperty(SystemProperty.applicationVersion.key(), environment.getVersionId()); System.setProperty("appengine.jetty.also_log_to_apiproxy", "true"); - if (appEngineWebXml!=null) { + if (appEngineWebXml != null) { for (Map.Entry entry : appEngineWebXml.getSystemProperties().entrySet()) { System.setProperty(entry.getKey(), entry.getValue()); } @@ -199,7 +196,7 @@ public static boolean waitForAsyncApiCalls( * @return If environment variables API_HOST or API_PORT port are set the host and/or port is * calculated from them. Otherwise the default host:port is used. */ - public static String getApiServerAddress(){ + public static String getApiServerAddress() { String server = firstNonNull(System.getenv("API_HOST"), VM_API_PROXY_HOST); String port = firstNonNull(System.getenv("API_PORT"), "" + VM_API_PROXY_PORT); return server + ":" + port; diff --git a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmTimer.java b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmTimer.java index 14f877b..aa90e3f 100755 --- a/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmTimer.java +++ b/appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmTimer.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime; import com.google.apphosting.runtime.timer.AbstractIntervalTimer; diff --git a/appengine-managed-runtime/src/test/java/com/google/apphosting/vmruntime/VmApiProxyDelegateTest.java b/appengine-managed-runtime/src/test/java/com/google/apphosting/vmruntime/VmApiProxyDelegateTest.java index 8ab2126..db676f3 100644 --- a/appengine-managed-runtime/src/test/java/com/google/apphosting/vmruntime/VmApiProxyDelegateTest.java +++ b/appengine-managed-runtime/src/test/java/com/google/apphosting/vmruntime/VmApiProxyDelegateTest.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.google.apphosting.vmruntime; import static org.hamcrest.CoreMatchers.instanceOf; @@ -54,7 +53,6 @@ * Tests the delegate for making AppEngine API calls in a Google Compute Engine VM. * */ - public class VmApiProxyDelegateTest extends TestCase { private static final String TICKET = "test-ticket"; public static final String TEST_PACKAGE_NAME = "test package"; @@ -64,35 +62,46 @@ public class VmApiProxyDelegateTest extends TestCase { public static Map createErrorToExceptionMap() { return new ImmutableMap.Builder() - .put(RemoteApiPb.RpcError.ErrorCode.UNKNOWN, + .put( + RemoteApiPb.RpcError.ErrorCode.UNKNOWN, new ApiProxy.UnknownException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.CALL_NOT_FOUND, + .put( + RemoteApiPb.RpcError.ErrorCode.CALL_NOT_FOUND, new ApiProxy.CallNotFoundException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.PARSE_ERROR, + .put( + RemoteApiPb.RpcError.ErrorCode.PARSE_ERROR, new ApiProxy.ArgumentException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.SECURITY_VIOLATION, + .put( + RemoteApiPb.RpcError.ErrorCode.SECURITY_VIOLATION, new ApiProxy.UnknownException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.OVER_QUOTA, + .put( + RemoteApiPb.RpcError.ErrorCode.OVER_QUOTA, new ApiProxy.OverQuotaException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.REQUEST_TOO_LARGE, + .put( + RemoteApiPb.RpcError.ErrorCode.REQUEST_TOO_LARGE, new ApiProxy.RequestTooLargeException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) .put( RemoteApiPb.RpcError.ErrorCode.CAPABILITY_DISABLED, - new ApiProxy.CapabilityDisabledException(TEST_ERROR_MESSAGE, TEST_PACKAGE_NAME, - TEST_METHOD_NAME)) + new ApiProxy.CapabilityDisabledException( + TEST_ERROR_MESSAGE, TEST_PACKAGE_NAME, TEST_METHOD_NAME)) .put( RemoteApiPb.RpcError.ErrorCode.FEATURE_DISABLED, - new ApiProxy.FeatureNotEnabledException(TEST_ERROR_MESSAGE, TEST_PACKAGE_NAME, - TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.BAD_REQUEST, + new ApiProxy.FeatureNotEnabledException( + TEST_ERROR_MESSAGE, TEST_PACKAGE_NAME, TEST_METHOD_NAME)) + .put( + RemoteApiPb.RpcError.ErrorCode.BAD_REQUEST, new ApiProxy.ArgumentException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.RESPONSE_TOO_LARGE, + .put( + RemoteApiPb.RpcError.ErrorCode.RESPONSE_TOO_LARGE, new ApiProxy.ResponseTooLargeException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.CANCELLED, + .put( + RemoteApiPb.RpcError.ErrorCode.CANCELLED, new ApiProxy.CancelledException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.REPLAY_ERROR, + .put( + RemoteApiPb.RpcError.ErrorCode.REPLAY_ERROR, new ApiProxy.UnknownException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) - .put(RemoteApiPb.RpcError.ErrorCode.DEADLINE_EXCEEDED, + .put( + RemoteApiPb.RpcError.ErrorCode.DEADLINE_EXCEEDED, new ApiProxy.ApiDeadlineExceededException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)) .build(); } @@ -149,14 +158,20 @@ private void callDelegateWithSuccess(boolean sync) throws Exception { } else { ApiConfig apiConfig = new ApiConfig(); apiConfig.setDeadlineInSeconds(timeoutInSeconds); - result = delegate.makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, pbData, - apiConfig).get(); + result = + delegate + .makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, pbData, apiConfig) + .get(); } assertTrue(Arrays.equals(pbData, result)); } - private void callDelegateWithOneError(boolean sync, RemoteApiPb.RpcError rpcError, - RemoteApiPb.ApplicationError appError, ApiProxyException expectedException) throws Exception { + private void callDelegateWithOneError( + boolean sync, + RemoteApiPb.RpcError rpcError, + RemoteApiPb.ApplicationError appError, + ApiProxyException expectedException) + throws Exception { // Create the response for the mock connection. RemoteApiPb.Response response = new RemoteApiPb.Response(); if (appError != null) { @@ -192,8 +207,11 @@ private void callDelegateWithOneError(boolean sync, RemoteApiPb.RpcError rpcErro try { ApiConfig apiConfig = new ApiConfig(); apiConfig.setDeadlineInSeconds(timeoutInSeconds); - result = delegate.makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, - requestData, apiConfig).get(); + result = + delegate + .makeAsyncCall( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, requestData, apiConfig) + .get(); fail(); } catch (ExecutionException exception) { // ExecutionException is expected, and make sure the cause is expected as well. @@ -206,8 +224,9 @@ private void callDelegateWithOneError(boolean sync, RemoteApiPb.RpcError rpcErro private void callDelegateWithHttpError(boolean sync, ApiProxyException expectedException) throws Exception { HttpClient mockClient = createMockHttpClient(); - HttpResponse mockHttpResponse = createMockHttpResponse("Error from RPC proxy".getBytes(), - HttpURLConnection.HTTP_UNAVAILABLE); + HttpResponse mockHttpResponse = + createMockHttpResponse( + "Error from RPC proxy".getBytes(), HttpURLConnection.HTTP_UNAVAILABLE); when(mockClient.execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class))) .thenReturn(mockHttpResponse); @@ -231,8 +250,11 @@ private void callDelegateWithHttpError(boolean sync, ApiProxyException expectedE try { ApiConfig apiConfig = new ApiConfig(); apiConfig.setDeadlineInSeconds(timeoutInSeconds); - result = delegate.makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, - requestData, apiConfig).get(); + result = + delegate + .makeAsyncCall( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, requestData, apiConfig) + .get(); fail(); } catch (ExecutionException exception) { // ExecutionException is expected, and make sure the cause is expected as well. @@ -269,8 +291,11 @@ private void callDelegateWithConnectionError(boolean sync, ApiProxyException exp try { ApiConfig apiConfig = new ApiConfig(); apiConfig.setDeadlineInSeconds(timeoutInSeconds); - result = delegate.makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, - requestData, apiConfig).get(); + result = + delegate + .makeAsyncCall( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, requestData, apiConfig) + .get(); fail(); } catch (ExecutionException exception) { // ExecutionException is expected, and make sure the cause is expected as well. @@ -306,8 +331,11 @@ private void callDelegateWithParsingError(boolean sync, ApiProxyException expect } } else { try { - result = delegate.makeAsyncCall(environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, - requestData, new ApiConfig()).get(); + result = + delegate + .makeAsyncCall( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, requestData, new ApiConfig()) + .get(); fail(); } catch (ExecutionException exception) { // ExecutionException is expected, and make sure the cause is expected as well. @@ -351,33 +379,33 @@ public void testMakeAsyncCall_Success() throws Exception { } public void testMakeSyncCall_HttpError() throws Exception { - callDelegateWithHttpError(true, - new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); + callDelegateWithHttpError( + true, new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); } public void testMakeAsyncCall_HttpError() throws Exception { - callDelegateWithHttpError(false, - new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); + callDelegateWithHttpError( + false, new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); } public void testMakeSyncCall_ConnectionError() throws Exception { - callDelegateWithConnectionError(true, - new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); + callDelegateWithConnectionError( + true, new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); } public void testMakeAsyncCall_ConnectionError() throws Exception { - callDelegateWithConnectionError(false, - new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); + callDelegateWithConnectionError( + false, new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); } public void testMakeSyncCall_ParsingError() throws Exception { - callDelegateWithParsingError(true, - new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); + callDelegateWithParsingError( + true, new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); } public void testMakeAsyncCall_ParsingError() throws Exception { - callDelegateWithParsingError(false, - new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); + callDelegateWithParsingError( + false, new ApiProxy.RPCFailedException(TEST_PACKAGE_NAME, TEST_METHOD_NAME)); } public void testMakeSyncCall_AllErrors() throws Exception { @@ -398,23 +426,31 @@ public void testUnknownRpcError() throws Exception { public void testCreateRequest() throws Exception { VmApiProxyEnvironment environment = createMockEnvironment(); - environment.getAttributes().put(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey, - "abc123"); + environment + .getAttributes() + .put(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey, "abc123"); // assertFalse(environment.getForceReuseApiConnection()); int timeoutMs = 17 * 1000; byte[] apiRequestData = new byte[] {1, 2, 3, 4}; - HttpPost request = VmApiProxyDelegate.createRequest(environment, TEST_PACKAGE_NAME, - TEST_METHOD_NAME, apiRequestData, timeoutMs); - assertEquals(request.getFirstHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey) - .getValue(), "abc123"); + HttpPost request = + VmApiProxyDelegate.createRequest( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, apiRequestData, timeoutMs); + assertEquals( + request + .getFirstHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey) + .getValue(), + "abc123"); assertEquals(request.getEntity().getContentType().getValue(), "application/octet-stream"); - assertEquals(request.getFirstHeader(VmApiProxyDelegate.RPC_STUB_ID_HEADER).getValue(), + assertEquals( + request.getFirstHeader(VmApiProxyDelegate.RPC_STUB_ID_HEADER).getValue(), VmApiProxyDelegate.REQUEST_STUB_ID); - assertEquals(request.getFirstHeader(VmApiProxyDelegate.RPC_METHOD_HEADER).getValue(), + assertEquals( + request.getFirstHeader(VmApiProxyDelegate.RPC_METHOD_HEADER).getValue(), VmApiProxyDelegate.REQUEST_STUB_METHOD); - assertEquals(request.getFirstHeader(VmApiProxyDelegate.RPC_DEADLINE_HEADER).getValue(), + assertEquals( + request.getFirstHeader(VmApiProxyDelegate.RPC_DEADLINE_HEADER).getValue(), Double.toString(timeoutMs / 1000)); // Disable keep-alive, workaround for b/. @@ -445,12 +481,17 @@ public void testCreateRequest() throws Exception { public void testCreateRequest_DapperHeaderForwarding() throws Exception { VmApiProxyEnvironment environment = createMockEnvironment(); - environment.getAttributes().put(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey, + environment + .getAttributes() + .put(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey, "abc123"); + HttpPost request = + VmApiProxyDelegate.createRequest( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, new byte[0], 0); + assertEquals( + request + .getFirstHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey) + .getValue(), "abc123"); - HttpPost request = VmApiProxyDelegate.createRequest(environment, TEST_PACKAGE_NAME, - TEST_METHOD_NAME, new byte[0], 0); - assertEquals(request.getFirstHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey) - .getValue(), "abc123"); } public void testCreateRequest_DeadlineFromEnvironment() throws Exception { @@ -458,9 +499,11 @@ public void testCreateRequest_DeadlineFromEnvironment() throws Exception { final Double deadline = 10.0; environment.getAttributes().put(VmApiProxyDelegate.API_DEADLINE_KEY, deadline); - HttpPost request = VmApiProxyDelegate.createRequest(environment, TEST_PACKAGE_NAME, - TEST_METHOD_NAME, new byte[0], 0); - assertEquals(request.getFirstHeader(VmApiProxyDelegate.RPC_DEADLINE_HEADER).getValue(), + HttpPost request = + VmApiProxyDelegate.createRequest( + environment, TEST_PACKAGE_NAME, TEST_METHOD_NAME, new byte[0], 0); + assertEquals( + request.getFirstHeader(VmApiProxyDelegate.RPC_DEADLINE_HEADER).getValue(), Double.toString(deadline)); } diff --git a/jetty9-base/src/main/java/com/google/apphosting/jetty9/GoogleRequestCustomizer.java b/jetty9-base/src/main/java/com/google/apphosting/jetty9/GoogleRequestCustomizer.java index 720692f..b0b9dc8 100644 --- a/jetty9-base/src/main/java/com/google/apphosting/jetty9/GoogleRequestCustomizer.java +++ b/jetty9-base/src/main/java/com/google/apphosting/jetty9/GoogleRequestCustomizer.java @@ -1,30 +1,31 @@ package com.google.apphosting.jetty9; -import java.net.InetSocketAddress; - import org.eclipse.jetty.http.HttpScheme; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.util.annotation.Name; +import java.net.InetSocketAddress; + public class GoogleRequestCustomizer implements HttpConfiguration.Customizer { public static final String HTTPS_HEADER = "X-AppEngine-Https"; public static final String USERIP_HEADER = "X-AppEngine-User-IP"; - + private final int httpPort; private final int httpsPort; - + public GoogleRequestCustomizer() { - this(80,443); + this(80, 443); } - public GoogleRequestCustomizer(@Name("httpPort")int httpPort, @Name("httpsPort") int httpsPort) { + + public GoogleRequestCustomizer(@Name("httpPort") int httpPort, @Name("httpsPort") int httpsPort) { super(); this.httpPort = httpPort; this.httpsPort = httpsPort; } - + @Override public void customize(Connector connector, HttpConfiguration channelConfig, Request request) { String https = request.getHeader(HTTPS_HEADER); @@ -39,8 +40,8 @@ public void customize(Connector connector, HttpConfiguration channelConfig, Requ } String userip = request.getHeader(USERIP_HEADER); - if (userip!=null) { - request.setRemoteAddr(InetSocketAddress.createUnresolved(userip,request.getRemotePort())); + if (userip != null) { + request.setRemoteAddr(InetSocketAddress.createUnresolved(userip, request.getRemotePort())); } } } diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SaveSessionFilter.java b/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SaveSessionFilter.java index 494fbbe..dee4ec9 100755 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SaveSessionFilter.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SaveSessionFilter.java @@ -1,20 +1,18 @@ /** * Copyright 2011 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.apphosting.runtime.jetty9; import java.io.IOException; diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SessionManager.java b/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SessionManager.java index faf3767..b62a1fc 100755 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SessionManager.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/runtime/jetty9/SessionManager.java @@ -11,8 +11,6 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - - package com.google.apphosting.runtime.jetty9; import static com.google.appengine.repackaged.com.google.common.io.BaseEncoding.base64Url; @@ -45,7 +43,6 @@ import com.google.apphosting.runtime.SessionData; import com.google.apphosting.runtime.SessionStore; - /** * Implements the Jetty {@link AbstractSessionManager} and, as an inner class, * {@link HashSessionIdManager} for our context. The session manager has to check the provided @@ -75,7 +72,6 @@ public class SessionManager extends AbstractSessionManager { // SecureRandom class. public static class SessionIdManager extends HashSessionIdManager { - public SessionIdManager() { super(new SecureRandom()); } @@ -95,7 +91,6 @@ public String newSessionId(long seedTerm) { return generateNewId(); } - public String generateNewId() { byte randomBytes[] = new byte[16]; _random.nextBytes(randomBytes); @@ -106,7 +101,6 @@ public String generateNewId() { logger.fine("Created a random session identifier: " + id); return id; } - } /** @@ -119,12 +113,10 @@ public String generateNewId() { */ public class AppEngineSession extends AbstractSession { - private final SessionData sessionData; private String key; private volatile boolean dirty; - /** * Create a new brand new session for the specified request. This constructor saves the new * session to the datastore and memcache. @@ -140,8 +132,8 @@ public AppEngineSession(HttpServletRequest request) { /** * Create an object for an existing session */ - public AppEngineSession(long created, long accessed, String sessionId, - SessionData sessionData) { + public AppEngineSession( + long created, long accessed, String sessionId, SessionData sessionData) { super(SessionManager.this, created, accessed, sessionId); this.sessionData = sessionData; key = SESSION_PREFIX + sessionId; @@ -161,10 +153,12 @@ public void renewId(HttpServletRequest request) { deleteSession(); // generate a new id - String newClusterId = ((SessionIdManager) getSessionManager().getSessionIdManager()) - .newSessionId(request.hashCode()); - String newNodeId = ((SessionIdManager) getSessionManager().getSessionIdManager()) - .getNodeId(newClusterId, request); + String newClusterId = + ((SessionIdManager) getSessionManager().getSessionIdManager()) + .newSessionId(request.hashCode()); + String newNodeId = + ((SessionIdManager) getSessionManager().getSessionIdManager()) + .getNodeId(newClusterId, request); // change the ids and recreate the key setClusterId(newClusterId); @@ -199,7 +193,6 @@ protected void save(boolean force) { for (int attemptNum = 0; attemptNum < 10; attemptNum++) { try { synchronized (this) { - if (dirty || force) { for (SessionStore sessionStore : sessionStoresInWriteOrder) { sessionStore.saveSession(key, sessionData); @@ -224,11 +217,11 @@ protected void save(boolean force) { logger.log(Level.WARNING, String.format("Session %s timeout while saving", getId())); delay *= 2; } - logger.log(Level.SEVERE, - String.format("Session %s not saved: too many attempts", getId())); + logger.log( + Level.SEVERE, String.format("Session %s not saved: too many attempts", getId())); } catch (DeadlineExceededException e) { - logger.log(Level.SEVERE, - String.format("Session %s not saved: too many timeouts", getId()), e); + logger.log( + Level.SEVERE, String.format("Session %s not saved: too many timeouts", getId()), e); } } } @@ -251,7 +244,8 @@ public synchronized void setAttribute(String name, Object value) { @Override public Object doPutOrRemove(String name, Object value) { - return value == null ? sessionData.getValueMap().remove(name) + return value == null + ? sessionData.getValueMap().remove(name) : sessionData.getValueMap().put(name, value); } @@ -279,8 +273,8 @@ public void clearAttributes() { } unbindValue(key, value); - ((SessionManager) getSessionManager()).doSessionAttributeListeners(this, key, value, - null); + ((SessionManager) getSessionManager()) + .doSessionAttributeListeners(this, key, value, null); } } if (sessionData.getValueMap() != null) { @@ -315,8 +309,8 @@ protected boolean access(long accessTime) { } else if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("Session %s accessed early, not marking dirty.", getId())); } - sessionData - .setExpirationTime(System.currentTimeMillis() + getSessionExpirationInMilliseconds()); + sessionData.setExpirationTime( + System.currentTimeMillis() + getSessionExpirationInMilliseconds()); // Handle session being invalid, update number of requests inside session. return super.access(accessTime); } @@ -431,8 +425,10 @@ SessionData loadSession(String sessionId) { if (data != null) { if (System.currentTimeMillis() > data.getExpirationTime()) { if (logger.isLoggable(Level.FINE)) { - logger.fine(String.format("Session %s expired %d seconds ago, ignoring", sessionId, - (System.currentTimeMillis() - data.getExpirationTime()) / 1000)); + logger.fine( + String.format( + "Session %s expired %d seconds ago, ignoring", + sessionId, (System.currentTimeMillis() - data.getExpirationTime()) / 1000)); } return null; } @@ -475,8 +471,8 @@ private LogRecord createWarningLogRecord(String message, Throwable ex) { ex.printStackTrace(printWriter); } - return new LogRecord(LogRecord.Level.warn, System.currentTimeMillis() * 1000, - stringWriter.toString()); + return new LogRecord( + LogRecord.Level.warn, System.currentTimeMillis() * 1000, stringWriter.toString()); } @Override @@ -512,14 +508,13 @@ protected void shutdownSessions() throws Exception { * Not used */ @Override - public void renewSessionId(String oldClusterId, String oldNodeId, String newClusterId, - String newNodeId) { + public void renewSessionId( + String oldClusterId, String oldNodeId, String newClusterId, String newNodeId) { // Not used. See instead AppEngineSession.renewId } - /** * Call any session id listeners registered. Usually done by renewSessionId() method, but that is * not used in appengine. @@ -533,5 +528,4 @@ public void callSessionIdListeners(AbstractSession session, String oldId) { l.sessionIdChanged(event, oldId); } } - } diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthentication.java b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthentication.java index 1066657..7f33146 100755 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthentication.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthentication.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; import com.google.appengine.api.users.User; @@ -64,8 +63,7 @@ * */ class AppEngineAuthentication { - private static final Logger log = Logger.getLogger( - AppEngineAuthentication.class.getName()); + private static final Logger log = Logger.getLogger(AppEngineAuthentication.class.getName()); /** * URLs that begin with this prefix are reserved for internal use by @@ -177,8 +175,8 @@ public Authentication validateRequest( } // Untrusted inbound ip for a login page, 307 the user to a server that we can trust. if (!checker.isTrustedRemoteAddr(remoteAddr)) { - String redirectUrl = getThreadLocalEnvironment().getL7UnsafeRedirectUrl() - + request.getRequestURI(); + String redirectUrl = + getThreadLocalEnvironment().getL7UnsafeRedirectUrl() + request.getRequestURI(); if (request.getQueryString() != null) { redirectUrl += "?" + request.getQueryString(); } @@ -196,8 +194,11 @@ public Authentication validateRequest( // the case where the user logs in, but as a role that isn't // allowed to see /*. They should still be able to log out. if (isLoginOrErrorPage(uri) && !DeferredAuthentication.isDeferred(response)) { - log.fine("Got " + uri + ", returning DeferredAuthentication to " - + "imply authentication is in progress."); + log.fine( + "Got " + + uri + + ", returning DeferredAuthentication to " + + "imply authentication is in progress."); return new DeferredAuthentication(this); } @@ -258,8 +259,11 @@ protected HttpSession renewSession(HttpServletRequest request, HttpServletRespon * This seems to only be used by JaspiAuthenticator, all other Authenticators return true. */ @Override - public boolean secureResponse(ServletRequest servletRequest, ServletResponse servletResponse, - boolean isAuthMandatory, Authentication.User user) { + public boolean secureResponse( + ServletRequest servletRequest, + ServletResponse servletResponse, + boolean isAuthMandatory, + Authentication.User user) { return true; } @@ -275,7 +279,6 @@ private VmApiProxyEnvironment getThreadLocalEnvironment() { } return null; } - } /** @@ -305,8 +308,8 @@ public String getName() { } @Override - public UserIdentity login(String unusedUsername, Object unusedCredentials, - ServletRequest request) { + public UserIdentity login( + String unusedUsername, Object unusedCredentials, ServletRequest request) { AppEngineUserIdentity appEngineUserIdentity = loadUser(); return appEngineUserIdentity; } @@ -319,7 +322,7 @@ public UserIdentity login(String unusedUsername, Object unusedCredentials, private AppEngineUserIdentity loadUser() { UserService userService = UserServiceFactory.getUserService(); User engineUser = userService.getCurrentUser(); - if (engineUser == null){ + if (engineUser == null) { return null; } return new AppEngineUserIdentity(new AppEnginePrincipal(engineUser)); @@ -374,7 +377,6 @@ public String getName() { } @Override - public boolean equals(Object other) { if (other instanceof AppEnginePrincipal) { return user.equals(((AppEnginePrincipal) other).user); @@ -384,7 +386,6 @@ public boolean equals(Object other) { } @Override - public String toString() { return user.toString(); } diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/TestMetadataServer.java b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/TestMetadataServer.java index 95cba7d..f78e960 100644 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/TestMetadataServer.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/TestMetadataServer.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; import static com.google.apphosting.vmruntime.VmApiProxyEnvironment.AFFINITY_ATTRIBUTE; @@ -58,9 +57,7 @@ public class TestMetadataServer extends AbstractLifeCycle implements Runnable { public static final String AFFINITY = "true"; public static final String APPENGINE_HOSTNAME = "testhostname"; - - public static void main(String... args) throws Exception - { + public static void main(String... args) throws Exception { TestMetadataServer test = new TestMetadataServer(); test.start(); Thread.sleep(5000); @@ -71,7 +68,7 @@ public static void main(String... args) throws Exception private HashMap responses = new HashMap(); private boolean run = true; - public TestMetadataServer() { + public TestMetadataServer() { addMetadata("STOP", "STOP"); addMetadata(PROJECT_ATTRIBUTE, PROJECT); addMetadata(PARTITION_ATTRIBUTE, PARTITION); @@ -83,19 +80,17 @@ public TestMetadataServer() { addMetadata(USE_MVM_AGENT_ATTRIBUTE, Boolean.toString(false)); } - public void setUseMVM(boolean useMVM) - { + public void setUseMVM(boolean useMVM) { addMetadata(USE_MVM_AGENT_ATTRIBUTE, Boolean.toString(useMVM)); } - + @Override - public void doStart() throws Exception - { + public void doStart() throws Exception { serverSocket = new ServerSocket(0); int metadataPort = serverSocket.getLocalPort(); System.setProperty("metadata_server", "127.0.0.1:" + metadataPort); logger.fine("Listening for metadata requests at port: " + metadataPort); - + Thread metadataThread = new Thread(this); metadataThread.setName("Metadata server"); metadataThread.setDaemon(true); @@ -104,7 +99,7 @@ public void doStart() throws Exception @Override public void doStop() throws IOException { - String path="STOP"; + String path = "STOP"; BufferedReader reader = null; HttpURLConnection connection = null; try { @@ -124,9 +119,14 @@ public void doStop() throws IOException { } if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { return; - } - throw new IOException("Meta-data request for '" + path + "' failed with error: " - + connection.getResponseCode()+" "+connection.getResponseMessage()); + } + throw new IOException( + "Meta-data request for '" + + path + + "' failed with error: " + + connection.getResponseCode() + + " " + + connection.getResponseMessage()); } finally { if (reader != null) { try { @@ -150,9 +150,7 @@ public void doStop() throws IOException { public void addMetadata(String path, String value) { responses.put(PATH_PREFIX + path, value); } - - - + /** * Starts a single threaded metadata server. */ @@ -163,10 +161,10 @@ public void run() { final Socket clientSocket = serverSocket.accept(); BufferedWriter responseWriter = null; try { - BufferedReader requestDataReader - = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - responseWriter - = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); + BufferedReader requestDataReader = + new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + responseWriter = + new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); String httpGetLine = requestDataReader.readLine(); String[] getLineSplit = httpGetLine.split(" "); if (getLineSplit.length < 2) { @@ -205,7 +203,6 @@ public void run() { if (serverSocket != null) { serverSocket.close(); logger.fine("CLOSING metadata requests at port: " + serverSocket.getLocalPort()); - } } catch (IOException e) { logger.log(Level.WARNING, "got Exception when closing the server socket.", e); diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeInterceptor.java b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeInterceptor.java index 5100164..fe49e0b 100644 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeInterceptor.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeInterceptor.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.google.apphosting.vmruntime.jetty9; import com.google.apphosting.utils.config.AppEngineWebXml; @@ -34,7 +33,11 @@ */ class VmRuntimeInterceptor implements HttpOutput.Interceptor { - public enum ClearTicket {NEVER, ON_COMMIT, ON_COMPLETE} + public enum ClearTicket { + NEVER, + ON_COMMIT, + ON_COMPLETE + } private static ClearTicket dftClearTicket = ClearTicket.ON_COMPLETE; @@ -51,8 +54,11 @@ public static void setDftClearTicket(ClearTicket dftClearTicket) { } public static void init(AppEngineWebXml appEngineWebXml) { - String clearTicket = VmApiProxyEnvironment.getSystemPropertyOrEnv(System.getenv(), - VmApiProxyEnvironment.CLEAR_REQUEST_TICKET_KEY, ClearTicket.ON_COMPLETE.name()); + String clearTicket = + VmApiProxyEnvironment.getSystemPropertyOrEnv( + System.getenv(), + VmApiProxyEnvironment.CLEAR_REQUEST_TICKET_KEY, + ClearTicket.ON_COMPLETE.name()); dftClearTicket = ClearTicket.valueOf(clearTicket.toUpperCase()); } diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTrustedAddressChecker.java b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTrustedAddressChecker.java index 5a7bee2..85298fa 100755 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTrustedAddressChecker.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTrustedAddressChecker.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; /** diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContext.java b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContext.java index 86283f9..2e84942 100755 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContext.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContext.java @@ -11,40 +11,8 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package com.google.apphosting.vmruntime.jetty9; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; -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; - -import javax.servlet.AsyncEvent; -import javax.servlet.AsyncListener; -import javax.servlet.ServletRequest; -import javax.servlet.ServletRequestEvent; -import javax.servlet.ServletRequestListener; -import javax.servlet.http.HttpSession; - -import org.eclipse.jetty.http.HttpScheme; -import org.eclipse.jetty.quickstart.PreconfigureDescriptorProcessor; -import org.eclipse.jetty.quickstart.QuickStartDescriptorGenerator; -import org.eclipse.jetty.security.ConstraintSecurityHandler; -import org.eclipse.jetty.server.HttpOutput; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.server.session.AbstractSessionManager; -import org.eclipse.jetty.util.URIUtil; -import org.eclipse.jetty.util.log.JavaUtilLog; -import org.eclipse.jetty.util.resource.Resource; -import org.eclipse.jetty.webapp.WebAppContext; - import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Transaction; @@ -72,13 +40,42 @@ import com.google.apphosting.vmruntime.VmRuntimeUtils; import com.google.apphosting.vmruntime.VmTimer; +import org.eclipse.jetty.http.HttpScheme; +import org.eclipse.jetty.quickstart.PreconfigureDescriptorProcessor; +import org.eclipse.jetty.quickstart.QuickStartDescriptorGenerator; +import org.eclipse.jetty.security.ConstraintSecurityHandler; +import org.eclipse.jetty.server.HttpOutput; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.session.AbstractSessionManager; +import org.eclipse.jetty.util.URIUtil; +import org.eclipse.jetty.util.log.JavaUtilLog; +import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.webapp.WebAppContext; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.servlet.AsyncEvent; +import javax.servlet.AsyncListener; +import javax.servlet.ServletRequest; +import javax.servlet.ServletRequestEvent; +import javax.servlet.ServletRequestListener; +import javax.servlet.http.HttpSession; + /** * WebAppContext for VM Runtimes. This class extends the "normal" AppEngineWebAppContext with * functionality that installs a request specific thread local environment on each incoming * request. */ public class VmRuntimeWebAppContext extends WebAppContext - implements VmRuntimeTrustedAddressChecker { + implements VmRuntimeTrustedAddressChecker { private static final Logger logger = Logger.getLogger(VmRuntimeWebAppContext.class.getName()); @@ -86,9 +83,13 @@ public class VmRuntimeWebAppContext extends WebAppContext // So we mark them as Jetty system classes, which cannot be overridden. private static final String[] SYSTEM_CLASSES = { // The trailing dot means these are all Java packages, not individual classes. - "com.google.appengine.api.", "com.google.appengine.tools.", "com.google.apphosting.", - "com.google.cloud.sql.jdbc.", "com.google.protos.cloud.sql.", - "com.google.storage.onestore.",}; + "com.google.appengine.api.", + "com.google.appengine.tools.", + "com.google.apphosting.", + "com.google.cloud.sql.jdbc.", + "com.google.protos.cloud.sql.", + "com.google.storage.onestore.", + }; // constant. If it's much larger than this we may need to // restructure the code a bit. protected static final int MAX_RESPONSE_SIZE = 32 * 1024 * 1024; @@ -106,32 +107,34 @@ public class VmRuntimeWebAppContext extends WebAppContext static { // Set SPI classloader priority to prefer the WebAppClassloader. - System.setProperty(ServiceFactoryFactory.USE_THREAD_CONTEXT_CLASSLOADER_PROPERTY, - Boolean.TRUE.toString()); + System.setProperty( + ServiceFactoryFactory.USE_THREAD_CONTEXT_CLASSLOADER_PROPERTY, Boolean.TRUE.toString()); // Use thread context class loader for memcache deserialization. - System.setProperty(MemcacheSerialization.USE_THREAD_CONTEXT_CLASSLOADER_PROPERTY, - Boolean.TRUE.toString()); + System.setProperty( + MemcacheSerialization.USE_THREAD_CONTEXT_CLASSLOADER_PROPERTY, Boolean.TRUE.toString()); } // List of Jetty configuration only needed if the quickstart process has been // executed, so we do not need the webinf, wedxml, fragment and annotation configurations // because they have been executed via the SDK. - private static final String[] quickstartConfigurationClasses = - {org.eclipse.jetty.quickstart.QuickStartConfiguration.class.getCanonicalName(), - org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), - org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.JettyWebXmlConfiguration.class.getCanonicalName()}; + private static final String[] quickstartConfigurationClasses = { + org.eclipse.jetty.quickstart.QuickStartConfiguration.class.getCanonicalName(), + org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), + org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.JettyWebXmlConfiguration.class.getCanonicalName() + }; // List of all the standard Jetty configurations that need to be executed when there // is no quickstart-web.xml. - private static final String[] preconfigurationClasses = - {org.eclipse.jetty.webapp.WebInfConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.WebXmlConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.MetaInfConfiguration.class.getCanonicalName(), - org.eclipse.jetty.webapp.FragmentConfiguration.class.getCanonicalName(), - org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), - org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), - org.eclipse.jetty.annotations.AnnotationConfiguration.class.getCanonicalName()}; + private static final String[] preconfigurationClasses = { + org.eclipse.jetty.webapp.WebInfConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.WebXmlConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.MetaInfConfiguration.class.getCanonicalName(), + org.eclipse.jetty.webapp.FragmentConfiguration.class.getCanonicalName(), + org.eclipse.jetty.plus.webapp.EnvConfiguration.class.getCanonicalName(), + org.eclipse.jetty.plus.webapp.PlusConfiguration.class.getCanonicalName(), + org.eclipse.jetty.annotations.AnnotationConfiguration.class.getCanonicalName() + }; public String getQuickstartWebXml() { return quickstartWebXml; @@ -184,8 +187,8 @@ protected void doStart() throws Exception { if (quickstartWebXml == null) { addEventListener(new ContextListener()); } else { - getMetaData().addDescriptorProcessor(preconfigProcessor = - new PreconfigureDescriptorProcessor()); + getMetaData() + .addDescriptorProcessor(preconfigProcessor = new PreconfigureDescriptorProcessor()); } super.doStart(); @@ -203,7 +206,7 @@ protected void startWebapp() throws Exception { } descriptor.getFile().createNewFile(); QuickStartDescriptorGenerator generator = - new QuickStartDescriptorGenerator(this, preconfigProcessor.getXML()); + new QuickStartDescriptorGenerator(this, preconfigProcessor.getXML()); try (FileOutputStream fos = new FileOutputStream(descriptor.getFile())) { generator.generateQuickStartWebXml(fos); } finally { @@ -212,7 +215,6 @@ protected void startWebapp() throws Exception { } } - @Override protected void stopWebapp() throws Exception { if (quickstartWebXml == null) { @@ -234,9 +236,11 @@ DatastoreService getDatastoreService() { * @return A List of SessionStores in write order. */ private static List createSessionStores(AppEngineWebXml appEngineWebXml) { - DatastoreSessionStore datastoreSessionStore = appEngineWebXml.getAsyncSessionPersistence() - ? new DeferredDatastoreSessionStore(appEngineWebXml.getAsyncSessionPersistenceQueueName()) - : new DatastoreSessionStore(); + DatastoreSessionStore datastoreSessionStore = + appEngineWebXml.getAsyncSessionPersistence() + ? new DeferredDatastoreSessionStore( + appEngineWebXml.getAsyncSessionPersistenceQueueName()) + : new DatastoreSessionStore(); // Write session data to the datastore before we write to memcache. return Arrays.asList(datastoreSessionStore, new MemcacheSessionStore()); } @@ -271,8 +275,8 @@ public VmRuntimeWebAppContext() { // Configure the Jetty SecurityHandler to understand our method of authentication // (via the UserService). Only the default ConstraintSecurityHandler is supported. - AppEngineAuthentication - .configureSecurityHandler((ConstraintSecurityHandler) getSecurityHandler(), this); + AppEngineAuthentication.configureSecurityHandler( + (ConstraintSecurityHandler) getSecurityHandler(), this); setMaxFormContentSize(MAX_RESPONSE_SIZE); setConfigurationClasses(preconfigurationClasses); @@ -299,9 +303,14 @@ public VmRuntimeWebAppContext() { */ public void init(String appengineWebXmlFile) throws AppEngineConfigException, IOException { String appDir = getBaseResource().getFile().getCanonicalPath(); - defaultEnvironment = VmApiProxyEnvironment.createDefaultContext(System.getenv(), metadataCache, - VmRuntimeUtils.getApiServerAddress(), wallclockTimer, VmRuntimeUtils.ONE_DAY_IN_MILLIS, - appDir); + defaultEnvironment = + VmApiProxyEnvironment.createDefaultContext( + System.getenv(), + metadataCache, + VmRuntimeUtils.getApiServerAddress(), + wallclockTimer, + VmRuntimeUtils.ONE_DAY_IN_MILLIS, + appDir); ApiProxy.setEnvironmentForCurrentThread(defaultEnvironment); if (ApiProxy.getEnvironmentFactory() == null) { // Need the check above since certain unit tests initialize the context multiple times. @@ -313,7 +322,7 @@ public void init(String appengineWebXmlFile) throws AppEngineConfigException, IO File appWebXml = new File(appDir, appengineWebXmlFile); if (appWebXml.exists()) { AppEngineWebXmlReader appEngineWebXmlReader = - new AppEngineWebXmlReader(appDir, appengineWebXmlFile); + new AppEngineWebXmlReader(appDir, appengineWebXmlFile); appEngineWebXml = appEngineWebXmlReader.readAppEngineWebXml(); } VmRuntimeUtils.installSystemProperties(defaultEnvironment, appEngineWebXml); @@ -349,7 +358,7 @@ public RequestContext getRequestContext(Request baseRequest) { return null; } RequestContext requestContext = - (RequestContext) baseRequest.getAttribute(RequestContext.class.getName()); + (RequestContext) baseRequest.getAttribute(RequestContext.class.getName()); if (requestContext == null) { // No instance found, so create a new environment requestContext = new RequestContext(baseRequest); @@ -363,9 +372,15 @@ class RequestContext extends HttpServletRequestAdapter { RequestContext(Request request) { super(request); - requestSpecificEnvironment = VmApiProxyEnvironment.createFromHeaders(System.getenv(), - metadataCache, this, VmRuntimeUtils.getApiServerAddress(), wallclockTimer, - VmRuntimeUtils.ONE_DAY_IN_MILLIS, defaultEnvironment); + requestSpecificEnvironment = + VmApiProxyEnvironment.createFromHeaders( + System.getenv(), + metadataCache, + this, + VmRuntimeUtils.getApiServerAddress(), + wallclockTimer, + VmRuntimeUtils.ONE_DAY_IN_MILLIS, + defaultEnvironment); if (requestSpecificEnvironment.isRequestTicket()) { final HttpOutput httpOutput = request.getResponse().getHttpOutput(); final HttpOutput.Interceptor nextOutput = httpOutput.getInterceptor(); @@ -379,16 +394,19 @@ VmApiProxyEnvironment getRequestSpecificEnvironment() { @Override public String toString() { - return String.format("RequestContext@%x %s==%s", hashCode(), request.getRequestURI(), - requestSpecificEnvironment); + return String.format( + "RequestContext@%x %s==%s", + hashCode(), request.getRequestURI(), requestSpecificEnvironment); } } public class ContextListener - implements ContextHandler.ContextScopeListener, ServletRequestListener { + implements ContextHandler.ContextScopeListener, ServletRequestListener { @Override - public void enterScope(org.eclipse.jetty.server.handler.ContextHandler.Context context, - Request baseRequest, Object reason) { + public void enterScope( + org.eclipse.jetty.server.handler.ContextHandler.Context context, + Request baseRequest, + Object reason) { RequestContext requestContext = getRequestContext(baseRequest); if (requestContext == null) { logger.fine("enterScope no request"); @@ -430,32 +448,32 @@ public void requestDestroyed(ServletRequestEvent sre) { logger.fine("requestDestroyed " + getRequestContext(baseRequest)); } if (request.isAsyncStarted()) { - request.getAsyncContext().addListener(new AsyncListener() { - @Override - public void onTimeout(AsyncEvent event) throws IOException { - } - - @Override - public void onStartAsync(AsyncEvent event) throws IOException { - } - - @Override - public void onError(AsyncEvent event) throws IOException { - } - - @Override - public void onComplete(AsyncEvent event) throws IOException { - complete(baseRequest); - } - }); + request + .getAsyncContext() + .addListener( + new AsyncListener() { + @Override + public void onTimeout(AsyncEvent event) throws IOException {} + + @Override + public void onStartAsync(AsyncEvent event) throws IOException {} + + @Override + public void onError(AsyncEvent event) throws IOException {} + + @Override + public void onComplete(AsyncEvent event) throws IOException { + complete(baseRequest); + } + }); } else { complete(baseRequest); } } @Override - public void exitScope(org.eclipse.jetty.server.handler.ContextHandler.Context context, - Request baseRequest) { + public void exitScope( + org.eclipse.jetty.server.handler.ContextHandler.Context context, Request baseRequest) { if (logger.isLoggable(Level.FINE)) { if (baseRequest == null) { logger.fine("exitScope"); @@ -490,8 +508,8 @@ private void complete(Request baseRequest) { } // Interrupt all API calls - VmRuntimeUtils.interruptRequestThreads(env, - VmRuntimeUtils.MAX_REQUEST_THREAD_INTERRUPT_WAIT_TIME_MS); + VmRuntimeUtils.interruptRequestThreads( + env, VmRuntimeUtils.MAX_REQUEST_THREAD_INTERRUPT_WAIT_TIME_MS); env.waitForAllApiCallsToComplete(VmRuntimeUtils.MAX_REQUEST_THREAD_API_CALL_WAIT_MS); } @@ -500,14 +518,20 @@ void handleAbandonedTxns(Collection txns) { // transaction is started so we can print it here. for (Transaction txn : txns) { try { - logger.warning("Request completed without committing or rolling back transaction with id " - + txn.getId() + ". Transaction will be rolled back."); + logger.warning( + "Request completed without committing or rolling back transaction with id " + + txn.getId() + + ". Transaction will be rolled back."); txn.rollback(); } catch (Exception e) { // We swallow exceptions so that there is no risk of our cleanup // impacting the actual result of the request. - logger.log(Level.WARNING, "Swallowing an exception we received while trying to rollback " - + "abandoned transaction with id " + txn.getId(), e); + logger.log( + Level.WARNING, + "Swallowing an exception we received while trying to rollback " + + "abandoned transaction with id " + + txn.getId(), + e); } } } diff --git a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppDeployer.java b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppDeployer.java index c1766a8..227159a 100644 --- a/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppDeployer.java +++ b/jetty9-compat-base/src/main/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppDeployer.java @@ -1,26 +1,20 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; -import java.io.File; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.annotation.Name; @@ -29,68 +23,73 @@ import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; -public class VmRuntimeWebAppDeployer extends AbstractLifeCycle -{ +import java.io.File; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class VmRuntimeWebAppDeployer extends AbstractLifeCycle { private final ContextHandlerCollection contexts; private final String webapp; private final Map properties; private ContextHandler handler; - + public VmRuntimeWebAppDeployer( - @Name("contexts") ContextHandlerCollection contexts, - @Name("webapp") String webapp) { - this(contexts,webapp,new HashMap()); + @Name("contexts") ContextHandlerCollection contexts, @Name("webapp") String webapp) { + this(contexts, webapp, new HashMap()); } public VmRuntimeWebAppDeployer( @Name("contexts") ContextHandlerCollection contexts, @Name("webapp") String webapp, - @Name("properties") Map properties) { - this.contexts=contexts; - this.webapp=webapp; + @Name("properties") Map properties) { + this.contexts = contexts; + this.webapp = webapp; this.properties = properties; } @Override protected void doStart() throws Exception { - + Resource resource = Resource.newResource(webapp); File file = resource.getFile(); - if (!resource.exists()) - throw new IllegalStateException("WebApp resouce does not exist "+resource); + if (!resource.exists()) { + throw new IllegalStateException("WebApp resouce does not exist " + resource); + } - String lcName=file.getName().toLowerCase(Locale.ENGLISH); + String lcName = file.getName().toLowerCase(Locale.ENGLISH); if (lcName.endsWith(".xml")) { - XmlConfiguration xmlc = new XmlConfiguration(resource.getURI().toURL()); - xmlc.getIdMap().put("Server", contexts.getServer()); - xmlc.getProperties().put("jetty.home",System.getProperty("jetty.home",".")); - xmlc.getProperties().put("jetty.base",System.getProperty("jetty.base",".")); - xmlc.getProperties().put("jetty.webapp",file.getCanonicalPath()); - xmlc.getProperties().put("jetty.webapps",file.getParentFile().getCanonicalPath()); - xmlc.getProperties().putAll(properties); - handler = (ContextHandler)xmlc.configure(); + XmlConfiguration xmlc = new XmlConfiguration(resource.getURI().toURL()); + xmlc.getIdMap().put("Server", contexts.getServer()); + xmlc.getProperties().put("jetty.home", System.getProperty("jetty.home", ".")); + xmlc.getProperties().put("jetty.base", System.getProperty("jetty.base", ".")); + xmlc.getProperties().put("jetty.webapp", file.getCanonicalPath()); + xmlc.getProperties().put("jetty.webapps", file.getParentFile().getCanonicalPath()); + xmlc.getProperties().putAll(properties); + handler = (ContextHandler) xmlc.configure(); } else { - WebAppContext wac=new WebAppContext(); + WebAppContext wac = new WebAppContext(); wac.setWar(webapp); wac.setContextPath("/"); } - + contexts.addHandler(handler); - if (contexts.isRunning()) + if (contexts.isRunning()) { handler.start(); + } } @Override protected void doStop() throws Exception { - if (handler.isRunning()) + if (handler.isRunning()) { handler.stop(); + } contexts.removeHandler(handler); - handler=null; + handler = null; } - - public Map getProperties() - { + + public Map getProperties() { return properties; } } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/runtime/jetty9/SessionManagerTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/runtime/jetty9/SessionManagerTest.java index 60a9d06..0b19aee 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/runtime/jetty9/SessionManagerTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/runtime/jetty9/SessionManagerTest.java @@ -1,20 +1,18 @@ /** * Copyright 2015 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.apphosting.runtime.jetty9; import static org.easymock.EasyMock.createMock; @@ -69,7 +67,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - /** * Tests for SessionManager and its inner classes. * @@ -269,50 +266,48 @@ public void testGetSessionFromMemcache() throws EntityNotFoundException { assertEquals(session.getId(), session2.getId()); assertEquals("bar", session2.getAttribute("foo")); } - - + public void testRenewSessionId() throws Exception { HttpServletRequest request = makeMockRequest(true); replay(request); AppEngineSession session = manager.newSession(request); session.setAttribute("foo", "bar"); session.save(); - String oldId = session.getId(); - byte[] bytes = (byte[])memcache.get(SessionManager.SESSION_PREFIX + oldId); + String oldId = session.getId(); + byte[] bytes = (byte[]) memcache.get(SessionManager.SESSION_PREFIX + oldId); assertNotNull(bytes); - SessionData data = (SessionData)SessionManagerUtil.deserialize(bytes); + SessionData data = (SessionData) SessionManagerUtil.deserialize(bytes); assertEquals("bar", data.getValueMap().get("foo")); - - //renew session id + + //renew session id session.renewId(request); //Ensure we deleted the session with the old id AppEngineSession sessionx = manager.getSession(oldId); assertNull(sessionx); assertNull(memcache.get(SessionManager.SESSION_PREFIX + oldId)); - + //Ensure we changed the id - String newId = session.getId(); + String newId = session.getId(); assertNotSame(oldId, newId); - + //Ensure we stored the session with the new id AppEngineSession session2 = manager.getSession(newId); assertNotSame(session, session2); - assertEquals("bar", session2.getAttribute("foo")); - bytes = (byte[])memcache.get(SessionManager.SESSION_PREFIX + newId); + assertEquals("bar", session2.getAttribute("foo")); + bytes = (byte[]) memcache.get(SessionManager.SESSION_PREFIX + newId); assertNotNull(bytes); - data = (SessionData)SessionManagerUtil.deserialize(bytes); + data = (SessionData) SessionManagerUtil.deserialize(bytes); assertEquals("bar", data.getValueMap().get("foo")); - + //Test we can store attributes session2.setAttribute("one", "two"); session2.save(); - bytes = (byte[])memcache.get(SessionManager.SESSION_PREFIX + newId); + bytes = (byte[]) memcache.get(SessionManager.SESSION_PREFIX + newId); assertNotNull(bytes); - data = (SessionData)SessionManagerUtil.deserialize(bytes); + data = (SessionData) SessionManagerUtil.deserialize(bytes); assertEquals("two", data.getValueMap().get("one")); } - private AppEngineSession createSession() { NamespaceManager.set(startNamespace()); @@ -321,14 +316,14 @@ private AppEngineSession createSession() { NamespaceManager.set(testNamespace()); HttpServletRequest request = makeMockRequest(true); - return localManager.newSession(request); + return localManager.newSession(request); } private HttpSession retrieveSession(AppEngineSession session) { NamespaceManager.set(startNamespace()); SessionManager manager = new SessionManager(Arrays.asList(new DatastoreSessionStore(), new MemcacheSessionStore())); - try { + try { return manager.getSession(session.getId()); } finally { NamespaceManager.set(testNamespace()); @@ -477,8 +472,8 @@ public void testDatastoreTimeouts() throws EntityNotFoundException { ApiProxy.setDelegate(newDelegate); HttpServletRequest request = makeMockRequest(true); - replay(request); - AppEngineSession session = manager.newSession(request); + replay(request); + AppEngineSession session = manager.newSession(request); session.setAttribute("foo", "bar"); newDelegate.setTimeouts(3); session.save(); @@ -499,8 +494,8 @@ public void testMemcacheOnlyLifecycle() { manager = new SessionManager(Collections.singletonList(new MemcacheSessionStore())); HttpServletRequest request = makeMockRequest(true); - replay(request); -AppEngineSession session = manager.newSession(request); + replay(request); + AppEngineSession session = manager.newSession(request); session.setAttribute("foo", "bar"); session.save(); assertNotNull(memcache.get(SessionManager.SESSION_PREFIX + session.getId())); @@ -510,23 +505,22 @@ public void testMemcacheOnlyLifecycle() { } /** TODO Debug this - public void testDatastoreOnlyLifecycle() throws EntityNotFoundException { - manager = - new SessionManager(Collections.singletonList(new DatastoreSessionStore())); - HttpServletRequest request = makeMockRequest(true); - replay(request); - - AppEngineSession session = manager.newSession(request); - session.setAttribute("foo", "bar"); - session.save(); - Key key = KeyFactory.createKey("_ah_SESSION", SessionManager.SESSION_PREFIX + session.getId()); - datastore.get(key); - HttpSession session2 = manager.getSession(session.getId()); - assertEquals(session.getId(), session2.getId()); - assertEquals("bar", session2.getAttribute("foo")); - } - */ - + * public void testDatastoreOnlyLifecycle() throws EntityNotFoundException { + * manager = + * new SessionManager(Collections.singletonList(new DatastoreSessionStore())); + * HttpServletRequest request = makeMockRequest(true); + * replay(request); + * + * AppEngineSession session = manager.newSession(request); + * session.setAttribute("foo", "bar"); + * session.save(); + * Key key = KeyFactory.createKey("_ah_SESSION", SessionManager.SESSION_PREFIX + session.getId()); + * datastore.get(key); + * HttpSession session2 = manager.getSession(session.getId()); + * assertEquals(session.getId(), session2.getId()); + * assertEquals("bar", session2.getAttribute("foo")); + * } + */ public void testDeferredDatastoreSessionStore() throws InterruptedException, IOException, ClassNotFoundException, EntityNotFoundException { helper.tearDown(); @@ -543,8 +537,8 @@ public void testDeferredDatastoreSessionStore() new SessionManager( Collections.singletonList(new DeferredDatastoreSessionStore(null))); HttpServletRequest request = makeMockRequest(true); - replay(request); - AppEngineSession session = manager.newSession(request); + replay(request); + AppEngineSession session = manager.newSession(request); // Wait for the session creation task. assertTrue(latch.awaitAndReset(10, TimeUnit.SECONDS)); session.setAttribute("foo", "bar"); @@ -575,4 +569,4 @@ private HttpServletRequest makeMockRequest(boolean forSession) { return mockRequest; } -} \ No newline at end of file +} diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/ApiRequest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/ApiRequest.java index 95eb29e..3bab730 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/ApiRequest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/ApiRequest.java @@ -1,54 +1,56 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; import com.google.apphosting.vmruntime.VmApiProxyEnvironment; - /** - * Simple class holding information about a single API request. - */ - public class ApiRequest { - public final VmApiProxyEnvironment requestEnvironment; - public final String packageName; - public final String methodName; - public final byte[] requestData; - - public ApiRequest(VmApiProxyEnvironment environment, String packageName, String methodName, - byte[] requestData) { - this.requestEnvironment = environment; - this.packageName = packageName; - this.methodName = methodName; - this.requestData = requestData; - } - - public String getPackageName() { - return packageName; - } - - public String getMethodName() { - return methodName; - } - - public byte[] getRequestData() { - return requestData; - } - - protected boolean waitForAllApiCalls() { - // Only for testing logging. The runtime should wait for all other API calls automatically. - return requestEnvironment.waitForAllApiCallsToComplete(1000); - } - } \ No newline at end of file +/** + * Simple class holding information about a single API request. + */ +public class ApiRequest { + public final VmApiProxyEnvironment requestEnvironment; + public final String packageName; + public final String methodName; + public final byte[] requestData; + + public ApiRequest( + VmApiProxyEnvironment environment, + String packageName, + String methodName, + byte[] requestData) { + this.requestEnvironment = environment; + this.packageName = packageName; + this.methodName = methodName; + this.requestData = requestData; + } + + public String getPackageName() { + return packageName; + } + + public String getMethodName() { + return methodName; + } + + public byte[] getRequestData() { + return requestData; + } + + protected boolean waitForAllApiCalls() { + // Only for testing logging. The runtime should wait for all other API calls automatically. + return requestEnvironment.waitForAllApiCallsToComplete(1000); + } +} diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthenticationTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthenticationTest.java index 416dcc0..ef4a6d3 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthenticationTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AppEngineAuthenticationTest.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; @@ -29,13 +28,17 @@ import junit.framework.TestCase; -import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpURI; +import org.eclipse.jetty.http.HttpVersion; +import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Response; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.util.MultiMap; import org.eclipse.jetty.util.security.Constraint; import java.io.ByteArrayOutputStream; @@ -44,11 +47,6 @@ import javax.servlet.DispatcherType; import javax.servlet.ServletException; -import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpURI; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http.MetaData; -import org.eclipse.jetty.util.MultiMap; /** * Tests for AppEngineAuthentication. @@ -70,7 +68,7 @@ public boolean isTrustedRemoteAddr(String remoteAddr) { return true; } } - + /** * Version of ConstraintSecurityHandler that allows doStart to be called from outside of package. */ @@ -136,15 +134,15 @@ public void tearDown() throws Exception { private String runRequest(String path, Request request, Response response) throws IOException, ServletException { //request.setMethod(/*HttpMethod.GET,*/ "GET"); - HttpURI uri =new HttpURI("http", SERVER_NAME,9999, path); + HttpURI uri = new HttpURI("http", SERVER_NAME, 9999, path); HttpFields httpf = new HttpFields(); MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf); request.setMetaData(metadata); // request.setServerName(SERVER_NAME); - // request.setAuthority(SERVER_NAME,9999); - //// request.setPathInfo(path); - //// request.setURIPathQuery(path); + // request.setAuthority(SERVER_NAME,9999); + //// request.setPathInfo(path); + //// request.setURIPathQuery(path); request.setDispatcherType(DispatcherType.REQUEST); doReturn(response).when(request).getResponse(); @@ -155,18 +153,19 @@ private String runRequest(String path, Request request, Response response) } return new String(output.toByteArray()); } + private String runRequest2(String path, Request request, Response response) throws IOException, ServletException { //request.setMethod(/*HttpMethod.GET,*/ "GET"); - HttpURI uri =new HttpURI("http", SERVER_NAME,9999, path); + HttpURI uri = new HttpURI("http", SERVER_NAME, 9999, path); HttpFields httpf = new HttpFields(); MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf); - // request.setMetaData(metadata); + // request.setMetaData(metadata); // request.setServerName(SERVER_NAME); - // request.setAuthority(SERVER_NAME,9999); - //// request.setPathInfo(path); - //// request.setURIPathQuery(path); + // request.setAuthority(SERVER_NAME,9999); + //// request.setPathInfo(path); + //// request.setURIPathQuery(path); request.setDispatcherType(DispatcherType.REQUEST); doReturn(response).when(request).getResponse(); @@ -177,6 +176,7 @@ private String runRequest2(String path, Request request, Response response) } return new String(output.toByteArray()); } + public void testUserNotRequired() throws Exception { Request request = spy(new Request(null, null)); Response response = mock(Response.class); @@ -197,7 +197,8 @@ public void testUserNotRequired_WithUser() throws Exception { public void testUserNotRequired_WithAdmin() throws Exception { // Add a logged in admin. - helper.setEnvIsLoggedIn(true) + helper + .setEnvIsLoggedIn(true) .setEnvIsAdmin(true) .setEnvEmail(ADMIN_EMAIL) .setEnvAuthDomain(TEST_ENV_DOMAIN) @@ -213,18 +214,19 @@ public void testUserRequired_NoUser() throws Exception { String path = "/user/blah"; Request request = spy(new Request(null, null)); //request.setServerPort(9999); - HttpURI uri =new HttpURI("http", SERVER_NAME,9999, path); + HttpURI uri = new HttpURI("http", SERVER_NAME, 9999, path); HttpFields httpf = new HttpFields(); MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf); request.setMetaData(metadata); - // request.setAuthority(SERVER_NAME,9999); + // request.setAuthority(SERVER_NAME,9999); Response response = mock(Response.class); String output = runRequest(path, request, response); // Verify that the servlet never was run (there is no output). assertEquals("", output); // Verify that the request was redirected to the login url. - String loginUrl = UserServiceFactory.getUserService() - .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path)); + String loginUrl = + UserServiceFactory.getUserService() + .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path)); verify(response).sendRedirect(loginUrl); } @@ -239,27 +241,28 @@ public void testUserRequired_NoUserButLoginUrl() throws Exception { public void testUserRequired_PreserveQueryParams() throws Exception { String path = "/user/blah"; - + Request request = new Request(null, null); // request.setServerPort(9999); - HttpURI uri =new HttpURI("http", SERVER_NAME,9999, path,"foo=baqr","foo=bar","foo=barff"); + HttpURI uri = new HttpURI("http", SERVER_NAME, 9999, path, "foo=baqr", "foo=bar", "foo=barff"); HttpFields httpf = new HttpFields(); MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf); request.setMetaData(metadata); - MultiMap queryParameters = new MultiMap<> (); + MultiMap queryParameters = new MultiMap<>(); queryParameters.add("ffo", "bar"); request.setQueryParameters(queryParameters); - request = spy(request); + request = spy(request); - /// request.setAuthority(SERVER_NAME,9999); + /// request.setAuthority(SERVER_NAME,9999); request.setQueryString("foo=bar"); Response response = mock(Response.class); String output = runRequest2(path, request, response); // Verify that the servlet never was run (there is no output). assertEquals("", output); // Verify that the request was redirected to the login url. - String loginUrl = UserServiceFactory.getUserService() - .createLoginURL(String.format("http://%s%s?foo=bar", SERVER_NAME + ":9999", path)); + String loginUrl = + UserServiceFactory.getUserService() + .createLoginURL(String.format("http://%s%s?foo=bar", SERVER_NAME + ":9999", path)); verify(response).sendRedirect(loginUrl); } @@ -290,24 +293,26 @@ public void testAdminRequired_NoUser() throws Exception { String path = "/admin/blah"; Request request = spy(new Request(null, null)); //request.setServerPort(9999); - HttpURI uri =new HttpURI("http", SERVER_NAME,9999, path); + HttpURI uri = new HttpURI("http", SERVER_NAME, 9999, path); HttpFields httpf = new HttpFields(); MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf); request.setMetaData(metadata); - // request.setAuthority(SERVER_NAME,9999); + // request.setAuthority(SERVER_NAME,9999); Response response = mock(Response.class); String output = runRequest(path, request, response); // Verify that the servlet never was run (there is no output). assertEquals("", output); // Verify that the request was redirected to the login url. - String loginUrl = UserServiceFactory.getUserService() - .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path)); + String loginUrl = + UserServiceFactory.getUserService() + .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path)); verify(response).sendRedirect(loginUrl); } public void testAdminRequired_WithAdmin() throws Exception { // Add a logged in admin. - helper.setEnvIsLoggedIn(true) + helper + .setEnvIsLoggedIn(true) .setEnvIsAdmin(true) .setEnvEmail(ADMIN_EMAIL) .setEnvAuthDomain(TEST_ENV_DOMAIN) diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AsyncServletTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AsyncServletTest.java index 5d3f7e1..8b0ebfa 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AsyncServletTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AsyncServletTest.java @@ -1,39 +1,37 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; - import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertThat; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.RequestEntity; + import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.RequestEntity; - -public class AsyncServletTest extends VmRuntimeTestBase{ +public class AsyncServletTest extends VmRuntimeTestBase { /** * Test that blob upload requests are intercepted by the blob upload filter. @@ -47,59 +45,59 @@ public void testAsyncPost() throws Exception { httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(300000); PostMethod post = new PostMethod(createUrl("/test-async").toString()); post.addRequestHeader("Content-Type", "text/plain"); - post.setRequestEntity(new RequestEntity() { - @Override - public void writeRequest(OutputStream out) throws IOException { - out.write(postData.getBytes(StandardCharsets.ISO_8859_1)); - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public String getContentType() { - return "text/plain"; - } - - @Override - public long getContentLength() { - return postData.length(); - } - }); - + post.setRequestEntity( + new RequestEntity() { + @Override + public void writeRequest(OutputStream out) throws IOException { + out.write(postData.getBytes(StandardCharsets.ISO_8859_1)); + } + + @Override + public boolean isRepeatable() { + return true; + } + + @Override + public String getContentType() { + return "text/plain"; + } + + @Override + public long getContentLength() { + return postData.length(); + } + }); + int httpCode = httpClient.executeMethod(post); assertThat(httpCode, equalTo(200)); - - String body=post.getResponseBodyAsString(); - + + String body = post.getResponseBodyAsString(); + List order = Arrays.asList(body.split(",")); - - assertThat(order.get(0),startsWith("CONSTRUCT:")); - String env0=order.get(0).split(":")[1]; - assertThat(order.get(1),startsWith("INIT:")); + assertThat(order.get(0), startsWith("CONSTRUCT:")); + String env0 = order.get(0).split(":")[1]; + + assertThat(order.get(1), startsWith("INIT:")); assertThat(order.get(1), endsWith(env0)); - assertThat(order.get(2),startsWith("REQUEST:")); - String env2=order.get(2).split(":")[1]; - assertThat(env2,not(equalTo(env0))); + assertThat(order.get(2), startsWith("REQUEST:")); + String env2 = order.get(2).split(":")[1]; + assertThat(env2, not(equalTo(env0))); - assertThat(order.get(3),startsWith("ON_DATA_AVAILABLE:")); + assertThat(order.get(3), startsWith("ON_DATA_AVAILABLE:")); assertThat(order.get(3), endsWith(env2)); - assertThat(order.get(4),startsWith("ON_ALL_DATA_READ:")); + assertThat(order.get(4), startsWith("ON_ALL_DATA_READ:")); assertThat(order.get(4), endsWith(env2)); - assertThat(order.get(5),startsWith("ASYNC:")); + assertThat(order.get(5), startsWith("ASYNC:")); assertThat(order.get(5), endsWith(env2)); - assertThat(order.get(6),startsWith("STARTED:")); + assertThat(order.get(6), startsWith("STARTED:")); assertThat(order.get(6), endsWith(env2)); - assertThat(order.get(7),startsWith("ON_WRITE_POSSIBLE:")); + assertThat(order.get(7), startsWith("ON_WRITE_POSSIBLE:")); assertThat(order.get(7), endsWith(env2)); - } } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AuthServlet.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AuthServlet.java index 5002201..80fda32 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AuthServlet.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/AuthServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; import java.io.IOException; diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/FakeableVmApiProxyDelegate.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/FakeableVmApiProxyDelegate.java index f87d50d..56ce582 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/FakeableVmApiProxyDelegate.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/FakeableVmApiProxyDelegate.java @@ -1,12 +1,12 @@ /** * Copyright 2015 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. @@ -32,13 +32,17 @@ public class FakeableVmApiProxyDelegate extends VmApiProxyDelegate { public LinkedList requests = new LinkedList<>(); public boolean ignoreLogging = true; - public FakeableVmApiProxyDelegate() { - } + public FakeableVmApiProxyDelegate() {} @Override - protected byte[] runSyncCall(VmApiProxyEnvironment environment, String packageName, - String methodName, byte[] requestData, int timeoutMs) throws ApiProxy.ApiProxyException { - // Lots of tests triggers logging. Ignore calls to the logservice by default. Tests + protected byte[] runSyncCall( + VmApiProxyEnvironment environment, + String packageName, + String methodName, + byte[] requestData, + int timeoutMs) + throws ApiProxy.ApiProxyException { + // Lots of tests triggers logging. Ignore calls to the logservice by default. Tests // verifying logging behavior can enable the log api capture calling setIgnoreLogging(false). if (ignoreLogging && "logservice".equals(packageName)) { return new ApiBasePb.VoidProto().toByteArray(); @@ -49,7 +53,7 @@ protected byte[] runSyncCall(VmApiProxyEnvironment environment, String packageNa requests.add(new ApiRequest(environment, packageName, methodName, requestData)); if (responses.isEmpty()) { throw new RuntimeException( - "Got unexpected ApiProxy call to: " + packageName + "/" + methodName); + "Got unexpected ApiProxy call to: " + packageName + "/" + methodName); } return responses.removeFirst().toByteArray(); } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/JettyRunner.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/JettyRunner.java index 7b698cc..9da79da 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/JettyRunner.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/JettyRunner.java @@ -64,14 +64,14 @@ class JettyRunner extends AbstractLifeCycle implements Runnable { public JettyRunner() { this(-1); - } + } public JettyRunner(int port) { - this("webapps/testwebapp",port); - } + this("webapps/testwebapp", port); + } public JettyRunner(String webapp, int port) { - this.webapp=webapp; + this.webapp = webapp; this.port = port; } @@ -87,15 +87,14 @@ public Server getServer() { return server; } - public void setAppEngineWebXml (String appengineWebXml) - { + public void setAppEngineWebXml(String appengineWebXml) { this.appengineWebXml = appengineWebXml; } - - - public void waitForStarted(long timeout,TimeUnit units) throws InterruptedException { - if (!started.await(timeout, units) || !server.isStarted()) - throw new IllegalStateException("server state="+server.getState()); + + public void waitForStarted(long timeout, TimeUnit units) throws InterruptedException { + if (!started.await(timeout, units) || !server.isStarted()) { + throw new IllegalStateException("server state=" + server.getState()); + } Log.getLogger(Server.class).info("Waited!"); } @@ -104,8 +103,8 @@ public void waitForStarted(long timeout,TimeUnit units) throws InterruptedExcept public void doStart() throws Exception { try { // find projectDir - File project = new File(System.getProperty("user.dir", ".")).getAbsoluteFile() - .getCanonicalFile(); + File project = + new File(System.getProperty("user.dir", ".")).getAbsoluteFile().getCanonicalFile(); File target = new File(project, "jetty9-compat-base/target"); while (!target.exists()) { project = project.getParentFile(); @@ -115,7 +114,9 @@ public void doStart() throws Exception { target = new File(project, "jetty9-compat-base/target"); } - File jetty_base = new File(System.getProperty("jetty.base", new File(target, "jetty-base").getAbsolutePath())); + File jetty_base = + new File( + System.getProperty("jetty.base", new File(target, "jetty-base").getAbsolutePath())); Assert.assertTrue(target.isDirectory()); Assert.assertTrue(jetty_base.isDirectory()); @@ -124,7 +125,6 @@ public void doStart() throws Exception { logs.mkdirs(); logs.deleteOnExit(); - // Set GAE SystemProperties setSystemProperties(logs); @@ -133,7 +133,8 @@ public void doStart() throws Exception { server = new Server(threadpool); HttpConfiguration httpConfig = new HttpConfiguration(); if (port >= 0) { - ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); + ServerConnector connector = + new ServerConnector(server, new HttpConnectionFactory(httpConfig)); connector.setPort(port); server.addConnector(connector); } else { @@ -144,8 +145,9 @@ public void doStart() throws Exception { // Basic jetty.xml handler setup HandlerCollection handlers = new HandlerCollection(); - ContextHandlerCollection contexts = new ContextHandlerCollection(); // TODO is a context handler collection needed for a single context? - handlers.setHandlers(new Handler[]{contexts, new DefaultHandler()}); + ContextHandlerCollection contexts = + new ContextHandlerCollection(); // TODO is a context handler collection needed for a single context? + handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()}); server.setHandler(handlers); // Configuration as done by gae.mod/gae.ini @@ -170,7 +172,8 @@ public void doStart() throws Exception { RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.addHandler(requestLogHandler); - NCSARequestLog requestLog = new NCSARequestLog(logs.getCanonicalPath() + "/request.yyyy_mm_dd.log"); + NCSARequestLog requestLog = + new NCSARequestLog(logs.getCanonicalPath() + "/request.yyyy_mm_dd.log"); requestLogHandler.setRequestLog(requestLog); requestLog.setRetainDays(2); requestLog.setAppend(true); @@ -184,25 +187,27 @@ public void doStart() throws Exception { context.setContextPath("/"); context.setConfigurationClasses(preconfigurationClasses); - // Needed to initialize JSP! - context.addBean(new AbstractLifeCycle() { - @Override - public void doStop() throws Exception { - } - - @Override - public void doStart() throws Exception { - JettyJasperInitializer jspInit = new JettyJasperInitializer(); - jspInit.onStartup(Collections.emptySet(), context.getServletContext()); - } - }, true); + context.addBean( + new AbstractLifeCycle() { + @Override + public void doStop() throws Exception {} + + @Override + public void doStart() throws Exception { + JettyJasperInitializer jspInit = new JettyJasperInitializer(); + jspInit.onStartup(Collections.emptySet(), context.getServletContext()); + } + }, + true); // find the sibling testwebapp target File webAppLocation = new File(target, webapp); - File logging = new File(webAppLocation, "WEB-INF/logging.properties").getCanonicalFile() - .getAbsoluteFile(); + File logging = + new File(webAppLocation, "WEB-INF/logging.properties") + .getCanonicalFile() + .getAbsoluteFile(); System.setProperty(JAVA_UTIL_LOGGING_CONFIG_PROPERTY, logging.toPath().toString()); Assert.assertTrue(webAppLocation.toString(), webAppLocation.isDirectory()); @@ -233,9 +238,10 @@ public void doStop() throws Exception { public void run() { try { start(); - if (Log.getLogger(Server.class).isDebugEnabled()) + if (Log.getLogger(Server.class).isDebugEnabled()) { server.dumpStdErr(); - server.join(); + } + server.join(); } catch (Exception e) { e.printStackTrace(); } @@ -248,21 +254,22 @@ public void run() { */ protected void setSystemProperties(File logs) throws IOException { - String log_file_pattern = logs.getAbsolutePath()+"/log.%g"; - + String log_file_pattern = logs.getAbsolutePath() + "/log.%g"; + System.setProperty(VmRuntimeFileLogHandler.LOG_PATTERN_CONFIG_PROPERTY, log_file_pattern); - System.setProperty("jetty.appengineport", me.alexpanov.net.FreePortFinder.findFreeLocalPort() + ""); + System.setProperty( + "jetty.appengineport", me.alexpanov.net.FreePortFinder.findFreeLocalPort() + ""); System.setProperty("jetty.appenginehost", "localhost"); System.setProperty("jetty.appengine.forwarded", "true"); System.setProperty("jetty.home", JETTY_HOME_PATTERN); - System.setProperty("GAE_SERVER_PORT", ""+port); + System.setProperty("GAE_SERVER_PORT", "" + port); } - + public static void main(String... args) throws Exception { TestMetadataServer meta = new TestMetadataServer(); try { meta.start(); - new JettyRunner(8080).run(); + new JettyRunner(8080).run(); } finally { meta.stop(); } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/LoggingTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/LoggingTest.java index 2409791..0d9715d 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/LoggingTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/LoggingTest.java @@ -1,22 +1,20 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; - import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @@ -31,64 +29,67 @@ import com.google.gson.Gson; -public class LoggingTest extends VmRuntimeTestBase{ +public class LoggingTest extends VmRuntimeTestBase { public void testGet() throws Exception { //runner.dump(); - + HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); - String query=Long.toHexString(System.nanoTime()); - GetMethod get = new GetMethod(createUrl("/testLogging?nano="+query).toString()); + String query = Long.toHexString(System.nanoTime()); + GetMethod get = new GetMethod(createUrl("/testLogging?nano=" + query).toString()); int httpCode = httpClient.executeMethod(get); assertThat(httpCode, equalTo(200)); - - String body=get.getResponseBodyAsString(); + + String body = get.getResponseBodyAsString(); assertThat(body, equalTo("FINE\nSEVERE\nfalse\n\n")); - - File logs = runner.getLogDir(); - File log = new File(logs,"log.0"); - + + File logs = runner.getLogDir(); + File log = new File(logs, "log.0"); + assertTrue(log.exists()); // Look for the log entry with our query string - try(BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(log), StandardCharsets.ISO_8859_1));) { + try (BufferedReader in = + new BufferedReader( + new InputStreamReader(new FileInputStream(log), StandardCharsets.ISO_8859_1)); ) { String line; - while((line=in.readLine())!=null){ - if (line.contains(query)) + while ((line = in.readLine()) != null) { + if (line.contains(query)) { break; + } } JsonData data = new Gson().fromJson(line, JsonData.class); - assertThat(data.severity,equalTo("INFO")); - assertThat(data.message,org.hamcrest.Matchers.containsString("LogTest Hello nano="+query)); - - line=in.readLine(); + assertThat(data.severity, equalTo("INFO")); + assertThat(data.message, org.hamcrest.Matchers.containsString("LogTest Hello nano=" + query)); + + line = in.readLine(); data = new Gson().fromJson(line, JsonData.class); - assertThat(data.severity,equalTo("ERROR")); - assertThat(data.message,org.hamcrest.Matchers.containsString("LoggingServlet doGet: not null")); - - line=in.readLine(); + assertThat(data.severity, equalTo("ERROR")); + assertThat( + data.message, org.hamcrest.Matchers.containsString("LoggingServlet doGet: not null")); + + line = in.readLine(); data = new Gson().fromJson(line, JsonData.class); - assertThat(data.severity,equalTo("ERROR")); - assertThat(data.message,org.hamcrest.Matchers.containsString("LoggingServlet doGet: null")); - + assertThat(data.severity, equalTo("ERROR")); + assertThat(data.message, org.hamcrest.Matchers.containsString("LoggingServlet doGet: null")); } } - // Something that JSON can parser the JSON into public static class JsonData { - public static class LogTimestamp { - public long seconds; - public long nanos; - } - public LogTimestamp timestamp; - public String severity; - public String thread; - public String message; - public String traceId; + public static class LogTimestamp { + public long seconds; + public long nanos; + } + + public LogTimestamp timestamp; + public String severity; + public String thread; + public String message; + public String traceId; } } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/NoAppWebXmlTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/NoAppWebXmlTest.java index b865052..b297c9d 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/NoAppWebXmlTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/NoAppWebXmlTest.java @@ -15,7 +15,6 @@ */ package com.google.apphosting.vmruntime.jetty9; - import java.util.Arrays; import static junit.framework.TestCase.assertTrue; diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/TestAsyncContext.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/TestAsyncContext.java index d19db04..25ccc91 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/TestAsyncContext.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/TestAsyncContext.java @@ -25,43 +25,40 @@ public class TestAsyncContext { Server server = new Server(); LocalConnector connector = new LocalConnector(server); VmRuntimeWebAppContext context = new VmRuntimeWebAppContext(); - + @Before public void before() throws Exception { context.setResourceBase("src/test/resources/webapp"); server.addConnector(connector); server.setHandler(context); - + context.setContextPath("/"); context.addServlet(TestServlet.class, "/"); context.init("WEB-INF/appengine-web.xml"); - + server.start(); } - + @After public void after() throws Exception { server.stop(); } - + @Test public void testSimpleGet() throws Exception { - String response=connector.getResponses( - "GET / HTTP/1.0\r\n"+ - "\r\n"); - System.err.println("response="+response); + String response = connector.getResponses("GET / HTTP/1.0\r\n" + "\r\n"); + System.err.println("response=" + response); } - public static class TestServlet extends HttpServlet - { + public static class TestServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + Environment env = ApiProxy.getCurrentEnvironment(); System.err.println(env); Assert.assertNotNull(env); super.doGet(req, resp); } - } } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyAuthTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyAuthTest.java index 6e6c634..eb0fed8 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyAuthTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyAuthTest.java @@ -151,24 +151,28 @@ public void testAuth_UntrustedInboundIp() throws Exception { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); GetMethod get = new GetMethod(createUrlForHostIP("/admin/test-auth").toString()); - get.addRequestHeader(VmApiProxyEnvironment.REAL_IP_HEADER, "127.0.0.2"); // Force untrusted dev IP + get.addRequestHeader( + VmApiProxyEnvironment.REAL_IP_HEADER, "127.0.0.2"); // Force untrusted dev IP get.setFollowRedirects(false); int httpCode = httpClient.executeMethod(get); assertEquals(307, httpCode); - assertEquals("https://testversion-dot-testbackend-dot-testhostname/admin/test-auth", - get.getResponseHeader("Location").getValue()); + assertEquals( + "https://testversion-dot-testbackend-dot-testhostname/admin/test-auth", + get.getResponseHeader("Location").getValue()); } public void testAuth_UntrustedInboundIpWithQuery() throws Exception { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); GetMethod get = new GetMethod(createUrlForHostIP("/admin/test-auth?foo=bar").toString()); - get.addRequestHeader(VmApiProxyEnvironment.REAL_IP_HEADER, "127.0.0.2"); // Force untrusted dev IP + get.addRequestHeader( + VmApiProxyEnvironment.REAL_IP_HEADER, "127.0.0.2"); // Force untrusted dev IP get.setFollowRedirects(false); int httpCode = httpClient.executeMethod(get); assertEquals(307, httpCode); - assertEquals("https://testversion-dot-testbackend-dot-testhostname/admin/test-auth?foo=bar", - get.getResponseHeader("Location").getValue()); + assertEquals( + "https://testversion-dot-testbackend-dot-testhostname/admin/test-auth?foo=bar", + get.getResponseHeader("Location").getValue()); } public void testAuth_TrustedRealIP() throws Exception { @@ -193,7 +197,8 @@ public void testAuth_UntrustedRealIP() throws Exception { get.setFollowRedirects(false); int httpCode = httpClient.executeMethod(get); assertEquals(307, httpCode); - assertEquals("https://testversion-dot-testbackend-dot-testhostname/admin/test-auth", - get.getResponseHeader("Location").getValue()); + assertEquals( + "https://testversion-dot-testbackend-dot-testhostname/admin/test-auth", + get.getResponseHeader("Location").getValue()); } } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSink2Test.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSink2Test.java index 4601705..813ddb0 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSink2Test.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSink2Test.java @@ -87,14 +87,29 @@ public void testAbandonTransaction() throws Exception { * @throws Exception */ public void testBlobUpload() throws Exception { - String postData = "--==boundary\r\n" + "Content-Type: message/external-body; " - + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; " - + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n" - + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n" - + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" - + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" - + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n" - + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--"; + String postData = + "--==boundary\r\n" + + "Content-Type: message/external-body; " + + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + + "Content-Disposition: form-data; " + + "name=upload-0; filename=\"file-0.jpg\"\r\n" + + "\r\n" + + "Content-Type: image/jpeg\r\n" + + "Content-Length: 1024\r\n" + + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n" + + "Content-Disposition: form-data; " + + "name=upload-0; filename=\"file-0.jpg\"\r\n" + + "\r\n" + + "\r\n" + + "--==boundary\r\n" + + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + + "Content-Disposition: form-data; name=text1\r\n" + + "Content-Length: 10\r\n" + + "\r\n" + + "Testing.\r\n" + + "\r\n" + + "\r\n" + + "--==boundary--"; HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); @@ -106,8 +121,8 @@ public void testBlobUpload() throws Exception { assertEquals(302, httpCode); Header redirUrl = blobPost.getResponseHeader("Location"); - assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0", - redirUrl.getValue()); + assertEquals( + "http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0", redirUrl.getValue()); } /** @@ -122,8 +137,11 @@ public void testCountMemcache() throws Exception { ApiProxy.setDelegate(fakeApiProxy); for (int i = 1; i <= 5; i++) { - MemcacheIncrementResponse responsePb = MemcacheIncrementResponse.newBuilder() - .setIncrementStatus(IncrementStatusCode.OK).setNewValue(i).build(); + MemcacheIncrementResponse responsePb = + MemcacheIncrementResponse.newBuilder() + .setIncrementStatus(IncrementStatusCode.OK) + .setNewValue(i) + .build(); fakeApiProxy.addApiResponse(responsePb); String[] lines = fetchUrl(createUrl("/count?type=memcache")); assertEquals(1, lines.length); diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSinkTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSinkTest.java index b59fbf9..107d09e 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSinkTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettyKitchenSinkTest.java @@ -35,15 +35,13 @@ */ public class VmRuntimeJettyKitchenSinkTest extends VmRuntimeTestBase { - - - @Override - protected void setUp() throws Exception { - appengineWebXml = "WEB-INF/sessions-disabled-appengine-web.xml"; - super.setUp(); - } + @Override + protected void setUp() throws Exception { + appengineWebXml = "WEB-INF/sessions-disabled-appengine-web.xml"; + super.setUp(); + } - /** + /** * Test that non compiled jsp files can be served. * * @throws Exception @@ -51,8 +49,8 @@ protected void setUp() throws Exception { public void testJspNotCompiled() throws Exception { int iter = 0; int end = 6; - String[] lines - = fetchUrl(createUrl(String.format("/hello_not_compiled.jsp?start=%d&end=%d", iter, end))); + String[] lines = + fetchUrl(createUrl(String.format("/hello_not_compiled.jsp?start=%d&end=%d", iter, end))); String iterationFormat = "

    Iteration %d

    "; for (String line : lines) { System.out.println(line); @@ -81,10 +79,11 @@ public void testWelcomeServlet() throws Exception { */ public void testApiProxyInstall() throws Exception { assertNotNull(ApiProxy.getDelegate()); - assertEquals(VmApiProxyDelegate.class.getCanonicalName(), - ApiProxy.getDelegate().getClass().getCanonicalName()); + assertEquals( + VmApiProxyDelegate.class.getCanonicalName(), + ApiProxy.getDelegate().getClass().getCanonicalName()); } - + /** * Test that the thread local environment is set up on each request. * @@ -92,10 +91,8 @@ public void testApiProxyInstall() throws Exception { */ public void testEnvironmentInstall() throws Exception { String[] lines = fetchUrl(createUrl("/CurrentEnvironmentAccessor")); - List expectedLines = Arrays.asList( - "testpartition~google.com:test-project", - "testbackend", - "testversion.0"); + List expectedLines = + Arrays.asList("testpartition~google.com:test-project", "testbackend", "testversion.0"); assertEquals(expectedLines, Arrays.asList(lines)); } @@ -110,7 +107,7 @@ public void testHealthOK() throws Exception { assertEquals(1, lines.length); assertEquals("ok", lines[0].trim()); } - + /** * Test that all AppEngine specific system properties are set up when the * VmRuntimeFilter is initialized. @@ -136,9 +133,9 @@ public void testWarmup() throws Exception { String[] lines = fetchUrl(createUrl("/_ah/warmup")); // fetchUrl() fails on non-OK return codes. assertEquals(0, lines.length); } - + /** - * Test that sessions are disabled. Disabling sessions means that the default HashSessionManager + * Test that sessions are disabled. Disabling sessions means that the default HashSessionManager * is being used, which keeps sessions in memory only. Enabling sessions uses the appengine SessionManager * which will use Datastore and memcache as persistent backing stores. * @@ -148,7 +145,9 @@ public void testSessions() throws Exception { for (int i = 1; i <= 5; i++) { String[] lines = fetchUrl(createUrl("/count?type=session")); assertEquals(1, lines.length); - assertEquals("1", lines[0]); // We're not passing in any session cookie so each request is a fresh session. + assertEquals( + "1", + lines[0]); // We're not passing in any session cookie so each request is a fresh session. } } @@ -158,7 +157,7 @@ public void testSsl_NoSSL() throws Exception { GetMethod get = new GetMethod(createUrl("/test-ssl").toString()); int httpCode = httpClient.executeMethod(get); assertEquals(200, httpCode); - String expected = "false:http:http://localhost:"+port+"/test-ssl"; + String expected = "false:http:http://localhost:" + port + "/test-ssl"; assertEquals(expected, get.getResponseBodyAsString()); } @@ -179,13 +178,13 @@ public void testWithUntrustedInboundIp() throws Exception { int httpCode = httpClient.executeMethod(get); assertEquals(200, httpCode); } - + protected int fetchResponseCode(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); return connection.getResponseCode(); } - + public void testShutDown() throws Exception { int code = fetchResponseCode(createUrl("/_ah/health")); @@ -198,5 +197,5 @@ public void testShutDown() throws Exception { code = fetchResponseCode(createUrl("/_ah/health")); assertEquals(HttpServletResponse.SC_BAD_GATEWAY, code); - } + } } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettySessionTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettySessionTest.java index 49d4e30..4fb95ee 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettySessionTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeJettySessionTest.java @@ -47,7 +47,7 @@ public class VmRuntimeJettySessionTest extends VmRuntimeTestBase { @Override protected void setUp() throws Exception { - appengineWebXml = "WEB-INF/sessions-enabled-appengine-web.xml"; + appengineWebXml = "WEB-INF/sessions-enabled-appengine-web.xml"; super.setUp(); } @@ -57,15 +57,13 @@ protected int fetchResponseCode(URL url) throws IOException { return connection.getResponseCode(); } - - public void testSsl_NoSSL() throws Exception { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); GetMethod get = new GetMethod(createUrl("/test-ssl").toString()); int httpCode = httpClient.executeMethod(get); assertEquals(200, httpCode); - String expected = "false:http:http://localhost:"+port+"/test-ssl"; + String expected = "false:http:http://localhost:" + port + "/test-ssl"; assertEquals(expected, get.getResponseBodyAsString()); } @@ -98,33 +96,33 @@ public void testWelcomeServlet() throws Exception { assertTrue(Arrays.asList(lines).contains("Hello, World!")); } -// public void testHealthCheckInterval() throws Exception { -// // Test that it was not healthy without IsLastSuccessful query string. -// int code = fetchResponseCode(createUrl("/_ah/health")); -// assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, code); -// -// // Test that it will be healthy if the last IsLastSuccessful query string was less than -// // VmRuntimeWebAppContext.checkIntervalSec ago. -// String[] lines = fetchUrl(createUrl("/_ah/health?IsLastSuccessful=yes")); -// assertEquals(1, lines.length); -// assertEquals("ok", lines[0].trim()); -// -// Thread.sleep((VmRuntimeWebAppContext.checkIntervalSec - 1) * 1000); -// -// code = fetchResponseCode(createUrl("/_ah/health")); -// assertEquals(HttpServletResponse.SC_OK, code); -// -// // Test that it will be unhealthy if the last IsLastSuccessful query string was more than -// // VmRuntimeWebAppContext.checkIntervalSec ago. -// lines = fetchUrl(createUrl("/_ah/health?IsLastSuccessful=yes")); -// assertEquals(1, lines.length); -// assertEquals("ok", lines[0].trim()); -// -// Thread.sleep(VmRuntimeWebAppContext.checkIntervalSec * 1000); -// -// code = fetchResponseCode(createUrl("/_ah/health")); -// assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, code); -// } + // public void testHealthCheckInterval() throws Exception { + // // Test that it was not healthy without IsLastSuccessful query string. + // int code = fetchResponseCode(createUrl("/_ah/health")); + // assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, code); + // + // // Test that it will be healthy if the last IsLastSuccessful query string was less than + // // VmRuntimeWebAppContext.checkIntervalSec ago. + // String[] lines = fetchUrl(createUrl("/_ah/health?IsLastSuccessful=yes")); + // assertEquals(1, lines.length); + // assertEquals("ok", lines[0].trim()); + // + // Thread.sleep((VmRuntimeWebAppContext.checkIntervalSec - 1) * 1000); + // + // code = fetchResponseCode(createUrl("/_ah/health")); + // assertEquals(HttpServletResponse.SC_OK, code); + // + // // Test that it will be unhealthy if the last IsLastSuccessful query string was more than + // // VmRuntimeWebAppContext.checkIntervalSec ago. + // lines = fetchUrl(createUrl("/_ah/health?IsLastSuccessful=yes")); + // assertEquals(1, lines.length); + // assertEquals("ok", lines[0].trim()); + // + // Thread.sleep(VmRuntimeWebAppContext.checkIntervalSec * 1000); + // + // code = fetchResponseCode(createUrl("/_ah/health")); + // assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, code); + // } /** * Create a datastore put response with the minimal fields required to make * the put succeed. @@ -157,11 +155,11 @@ public void testSessions() throws Exception { // Add responses for session create. fakeApiProxy.addApiResponse(createDatastorePutResponse()); fakeApiProxy.addApiResponse( - MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build()); + MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build()); // Add responses for session save. fakeApiProxy.addApiResponse(createDatastorePutResponse()); fakeApiProxy.addApiResponse( - MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build()); + MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build()); // Make a call to count and save the session cookie. HttpClient httpClient = new HttpClient(); @@ -173,19 +171,22 @@ public void testSessions() throws Exception { assertEquals("1", firstGet.getResponseBodyAsString().trim()); // Parse the memcache put request so we can respond to the next get request. - MemcacheSetRequest setRequest - = MemcacheSetRequest.parseFrom(fakeApiProxy.getLastRequest().getRequestData()); + MemcacheSetRequest setRequest = + MemcacheSetRequest.parseFrom(fakeApiProxy.getLastRequest().getRequestData()); assertEquals(1, setRequest.getItemCount()); - Item responsePayload = Item.newBuilder() - .setKey(setRequest.getItem(0).getKey()).setValue(setRequest.getItem(0).getValue()).build(); - MemcacheGetResponse getResponse - = MemcacheGetResponse.newBuilder().addItem(responsePayload).build(); + Item responsePayload = + Item.newBuilder() + .setKey(setRequest.getItem(0).getKey()) + .setValue(setRequest.getItem(0).getValue()) + .build(); + MemcacheGetResponse getResponse = + MemcacheGetResponse.newBuilder().addItem(responsePayload).build(); fakeApiProxy.addApiResponse(getResponse); // Add responses for session save. fakeApiProxy.addApiResponse(createDatastorePutResponse()); fakeApiProxy.addApiResponse( - MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build()); + MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build()); // Make a call to count with the session cookie. GetMethod secondGet = new GetMethod(url.toString()); @@ -194,5 +195,4 @@ public void testSessions() throws Exception { // Check the count, should be "2" for the second request. assertEquals("2", secondGet.getResponseBodyAsString().trim()); } - } diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTestBase.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTestBase.java index 9fd32c7..d43da42 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTestBase.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeTestBase.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.vmruntime.jetty9; import static com.google.apphosting.vmruntime.VmMetadataCache.DEFAULT_META_DATA_SERVER; @@ -43,13 +42,14 @@ * Test methods that are Jetty version independent should be implemented in this class. */ @Ignore -public class VmRuntimeTestBase extends TestCase { +public class VmRuntimeTestBase extends TestCase { protected static final Logger logger = Logger.getLogger(VmRuntimeTestBase.class.getName()); private static final String HOME_FOLDER = System.getProperty("HOME_FOLDER", "jetty_home"); - public static final String JETTY_HOME_PATTERN = ""//TestUtil.getRunfilesDir() - + "com/google/apphosting/vmruntime/jetty9/" + HOME_FOLDER; - + public static final String JETTY_HOME_PATTERN = + "" //TestUtil.getRunfilesDir() + + "com/google/apphosting/vmruntime/jetty9/" + + HOME_FOLDER; // Wait at the most 30 seconds for Jetty to come up. private static final int JETTY_START_DELAY = 45; @@ -82,7 +82,6 @@ protected URL createUrl(String servletPath) throws MalformedURLException { return new URL("http://localhost:" + port + servletPath); } - /** * Creates a URL for accessing the Jetty instance under test, accessed by host ip. * @@ -139,10 +138,10 @@ protected void setUp() throws Exception { metadataServer = new TestMetadataServer(); metadataServer.setUseMVM(Boolean.valueOf(getUseMvmAgent())); metadataServer.start(); - + // Start jetty using the Runnable configured by the sub class. runner = new JettyRunner(port); - + runner.setAppEngineWebXml(appengineWebXml); Thread jettyRunnerThread = new Thread(runner); jettyRunnerThread.setName("JettyRunnerThread"); @@ -159,17 +158,17 @@ protected void tearDown() throws Exception { Thread.sleep(50); } - protected HttpURLConnection openConnection(String path) throws IOException { + protected HttpURLConnection openConnection(String path) throws IOException { String server = System.getProperty("metadata_server", DEFAULT_META_DATA_SERVER); URL url = new URL(String.format(META_DATA_PATTERN, server, path)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Metadata-Flavor", "Google"); return conn; } - /** Timeout in milliseconds to retrieve data from the server. */ + /** Timeout in milliseconds to retrieve data from the server. */ private static final int TIMEOUT_MILLIS = 120 * 1000; - - protected String getMetadataFromServer(String path) throws IOException { + + protected String getMetadataFromServer(String path) throws IOException { BufferedReader reader = null; HttpURLConnection connection = null; try { @@ -188,8 +187,11 @@ protected String getMetadataFromServer(String path) throws IOException { } else if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { return null; } - throw new IOException("Meta-data request for '" + path + "' failed with error: " - + connection.getResponseMessage()); + throw new IOException( + "Meta-data request for '" + + path + + "' failed with error: " + + connection.getResponseMessage()); } finally { if (reader != null) { try { @@ -203,5 +205,4 @@ protected String getMetadataFromServer(String path) throws IOException { } } } - -} \ No newline at end of file +} diff --git a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContextTest.java b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContextTest.java index f55004f..1eb4473 100644 --- a/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContextTest.java +++ b/jetty9-compat-base/src/test/java/com/google/apphosting/vmruntime/jetty9/VmRuntimeWebAppContextTest.java @@ -13,20 +13,22 @@ */ package com.google.apphosting.vmruntime.jetty9; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + import com.google.apphosting.api.ApiProxy; -import com.google.apphosting.vmruntime.VmApiProxyDelegate; import com.google.apphosting.vmruntime.VmApiProxyEnvironment; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.resource.Resource; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -35,12 +37,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import static com.google.apphosting.vmruntime.VmRuntimeFileLogHandler.JAVA_UTIL_LOGGING_CONFIG_PROPERTY; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - /** * Test VmRuntimeWebAppContext directly, without using VmRuntimeTestBase * @@ -63,7 +59,8 @@ public void before() throws Exception { jetty.start(); server = jetty.getServer(); connector = (LocalConnector) server.getConnectors()[0]; - context = (VmRuntimeWebAppContext) server.getChildHandlersByClass(VmRuntimeWebAppContext.class)[0]; + context = + (VmRuntimeWebAppContext) server.getChildHandlersByClass(VmRuntimeWebAppContext.class)[0]; } @After @@ -93,9 +90,16 @@ public void testNoRequestTicket() throws Exception { context.addServlet(new ServletHolder("test", servlet), "/*"); String response = connector.getResponses("GET / HTTP/1.0\r\n\r\n"); assertThat(response, Matchers.containsString("200 OK")); - assertThat(response, Matchers.containsString("initial ticket=google_com_test-project/testbackend.testversion.frontend1")); - assertThat(response, Matchers.containsString("committed ticket=google_com_test-project/testbackend.testversion.frontend1")); - assertEquals("google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); + assertThat( + response, + Matchers.containsString( + "initial ticket=google_com_test-project/testbackend.testversion.frontend1")); + assertThat( + response, + Matchers.containsString( + "committed ticket=google_com_test-project/testbackend.testversion.frontend1")); + assertEquals( + "google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); } @Test @@ -104,8 +108,11 @@ public void testRequestTicketClearNever() throws Exception { VmRuntimeInterceptor.setDftClearTicket(VmRuntimeInterceptor.ClearTicket.NEVER); ReportProxyServlet servlet = new ReportProxyServlet(); context.addServlet(new ServletHolder("test", servlet), "/*"); - String response = connector.getResponses("GET / HTTP/1.0\r\n" + - VmApiProxyEnvironment.TICKET_HEADER + ": request-ticket\r\n\r\n"); + String response = + connector.getResponses( + "GET / HTTP/1.0\r\n" + + VmApiProxyEnvironment.TICKET_HEADER + + ": request-ticket\r\n\r\n"); assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("initial ticket=request-ticket")); assertThat(response, Matchers.containsString("committed ticket=request-ticket")); @@ -118,12 +125,19 @@ public void testRequestTicketClearOnCommit() throws Exception { VmRuntimeInterceptor.setDftClearTicket(VmRuntimeInterceptor.ClearTicket.ON_COMMIT); ReportProxyServlet servlet = new ReportProxyServlet(); context.addServlet(new ServletHolder("test", servlet), "/*"); - String response = connector.getResponses("GET / HTTP/1.0\r\n" + - VmApiProxyEnvironment.TICKET_HEADER + ": request-ticket\r\n\r\n"); + String response = + connector.getResponses( + "GET / HTTP/1.0\r\n" + + VmApiProxyEnvironment.TICKET_HEADER + + ": request-ticket\r\n\r\n"); assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("initial ticket=request-ticket")); - assertThat(response, Matchers.containsString("committed ticket=google_com_test-project/testbackend.testversion.frontend1")); - assertEquals("google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); + assertThat( + response, + Matchers.containsString( + "committed ticket=google_com_test-project/testbackend.testversion.frontend1")); + assertEquals( + "google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); } @Test @@ -132,12 +146,16 @@ public void testRequestTicketClearOnComplete() throws Exception { VmRuntimeInterceptor.setDftClearTicket(VmRuntimeInterceptor.ClearTicket.ON_COMPLETE); ReportProxyServlet servlet = new ReportProxyServlet(); context.addServlet(new ServletHolder("test", servlet), "/*"); - String response = connector.getResponses("GET / HTTP/1.0\r\n" + - VmApiProxyEnvironment.TICKET_HEADER + ": request-ticket\r\n\r\n"); + String response = + connector.getResponses( + "GET / HTTP/1.0\r\n" + + VmApiProxyEnvironment.TICKET_HEADER + + ": request-ticket\r\n\r\n"); assertThat(response, Matchers.containsString("200 OK")); assertThat(response, Matchers.containsString("initial ticket=request-ticket")); assertThat(response, Matchers.containsString("committed ticket=request-ticket")); - assertEquals("google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); + assertEquals( + "google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); } @Test @@ -145,12 +163,22 @@ public void testRequestTicketUseGlobal() throws Exception { System.setProperty(VmApiProxyEnvironment.USE_GLOBAL_TICKET_KEY, "TRUE"); ReportProxyServlet servlet = new ReportProxyServlet(); context.addServlet(new ServletHolder("test", servlet), "/*"); - String response = connector.getResponses("GET / HTTP/1.0\r\n" + - VmApiProxyEnvironment.TICKET_HEADER + ": request-ticket\r\n\r\n"); + String response = + connector.getResponses( + "GET / HTTP/1.0\r\n" + + VmApiProxyEnvironment.TICKET_HEADER + + ": request-ticket\r\n\r\n"); assertThat(response, Matchers.containsString("200 OK")); - assertThat(response, Matchers.containsString("initial ticket=google_com_test-project/testbackend.testversion.frontend1")); - assertThat(response, Matchers.containsString("committed ticket=google_com_test-project/testbackend.testversion.frontend1")); - assertEquals("google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); + assertThat( + response, + Matchers.containsString( + "initial ticket=google_com_test-project/testbackend.testversion.frontend1")); + assertThat( + response, + Matchers.containsString( + "committed ticket=google_com_test-project/testbackend.testversion.frontend1")); + assertEquals( + "google_com_test-project/testbackend.testversion.frontend1", servlet.getAfterClose()); } private static class ReportProxyServlet extends HttpServlet { @@ -162,7 +190,8 @@ public synchronized String getAfterClose() { } @Override - protected synchronized void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { + protected synchronized void doGet(HttpServletRequest req, HttpServletResponse response) + throws ServletException, IOException { VmApiProxyEnvironment env = (VmApiProxyEnvironment) ApiProxy.getCurrentEnvironment(); response.setContentType("text/plain;charset=iso-8859-1"); diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AsyncServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AsyncServlet.java index 5bc64a9..fc073c5 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AsyncServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AsyncServlet.java @@ -1,5 +1,8 @@ package com.google.apphosting.tests.usercode.testservlets; +import com.google.apphosting.api.ApiProxy; +import com.google.apphosting.api.ApiProxy.Environment; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Queue; @@ -21,164 +24,170 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import com.google.apphosting.api.ApiProxy; -import com.google.apphosting.api.ApiProxy.Environment; - public class AsyncServlet extends HttpServlet { - private enum Env {CONSTRUCT,INIT,REQUEST,ASYNC,TIMEOUT,ON_DATA_AVAILABLE,ON_ALL_DATA_READ,STARTED, ON_WRITE_POSSIBLE}; + private enum Env { + CONSTRUCT, + INIT, + REQUEST, + ASYNC, + TIMEOUT, + ON_DATA_AVAILABLE, + ON_ALL_DATA_READ, + STARTED, + ON_WRITE_POSSIBLE + } + private Queue order = new ConcurrentLinkedQueue<>(); private ConcurrentMap environment = new ConcurrentHashMap<>(); public AsyncServlet() { - environment.put(Env.CONSTRUCT,ApiProxy.getCurrentEnvironment()); + environment.put(Env.CONSTRUCT, ApiProxy.getCurrentEnvironment()); } - - + @Override public void init(ServletConfig servletConfig) throws ServletException { - environment.put(Env.INIT,ApiProxy.getCurrentEnvironment()); + environment.put(Env.INIT, ApiProxy.getCurrentEnvironment()); } @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { - if (req.getDispatcherType()==DispatcherType.REQUEST) { + if (req.getDispatcherType() == DispatcherType.REQUEST) { // #1A POST request dispatched order.clear(); order.add(Env.CONSTRUCT); order.add(Env.INIT); order.add(Env.REQUEST); - environment.put(Env.REQUEST,ApiProxy.getCurrentEnvironment()); + environment.put(Env.REQUEST, ApiProxy.getCurrentEnvironment()); - final AsyncContext async = req.startAsync(); + final AsyncContext async = req.startAsync(); final ServletInputStream in = req.getInputStream(); - in.setReadListener(new ReadListener() { - - @Override - public void onError(Throwable t) { - t.printStackTrace(); - } - - @Override - public void onDataAvailable() throws IOException { - // #2A Read data available - if (!order.contains(Env.ON_DATA_AVAILABLE)) - order.add(Env.ON_DATA_AVAILABLE); - environment.put(Env.ON_DATA_AVAILABLE,ApiProxy.getCurrentEnvironment()); - while(in.isReady()) { - if (in.read()<0) - break; - } - } - - @Override - public void onAllDataRead() throws IOException { - // #3B all data read - order.add(Env.ON_ALL_DATA_READ); - environment.put(Env.ON_ALL_DATA_READ,ApiProxy.getCurrentEnvironment()); - async.dispatch(); // Dispatch back to servlet - } - }); - }else { - doGet(req,resp); + in.setReadListener( + new ReadListener() { + + @Override + public void onError(Throwable t) { + t.printStackTrace(); + } + + @Override + public void onDataAvailable() throws IOException { + // #2A Read data available + if (!order.contains(Env.ON_DATA_AVAILABLE)) { + order.add(Env.ON_DATA_AVAILABLE); + } + environment.put(Env.ON_DATA_AVAILABLE, ApiProxy.getCurrentEnvironment()); + while (in.isReady()) { + if (in.read() < 0) { + break; + } + } + } + + @Override + public void onAllDataRead() throws IOException { + // #3B all data read + order.add(Env.ON_ALL_DATA_READ); + environment.put(Env.ON_ALL_DATA_READ, ApiProxy.getCurrentEnvironment()); + async.dispatch(); // Dispatch back to servlet + } + }); + } else { + doGet(req, resp); } } - + @Override - protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) + throws ServletException, IOException { final AsyncContext async = req.startAsync(); - - if (req.getDispatcherType()==DispatcherType.REQUEST) { + + if (req.getDispatcherType() == DispatcherType.REQUEST) { // #1A GET Request Dispatch order.clear(); order.add(Env.CONSTRUCT); order.add(Env.INIT); order.add(Env.REQUEST); - environment.put(Env.REQUEST,ApiProxy.getCurrentEnvironment()); + environment.put(Env.REQUEST, ApiProxy.getCurrentEnvironment()); async.setTimeout(100); - async.addListener(new AsyncListener() { - @Override - public void onTimeout(AsyncEvent event) throws IOException { - // #2B #3B Timeout - order.add(Env.TIMEOUT); - environment.put(Env.TIMEOUT,ApiProxy.getCurrentEnvironment()); - async.dispatch(); // Dispatch back to servlet - } - - @Override - public void onStartAsync(AsyncEvent event) throws IOException { - } - - @Override - public void onError(AsyncEvent event) throws IOException { - event.getThrowable().printStackTrace(); - } - - @Override - public void onComplete(AsyncEvent event) throws IOException { - } - }); - } else if (req.getDispatcherType()==DispatcherType.ASYNC) { + async.addListener( + new AsyncListener() { + @Override + public void onTimeout(AsyncEvent event) throws IOException { + // #2B #3B Timeout + order.add(Env.TIMEOUT); + environment.put(Env.TIMEOUT, ApiProxy.getCurrentEnvironment()); + async.dispatch(); // Dispatch back to servlet + } + + @Override + public void onStartAsync(AsyncEvent event) throws IOException {} + + @Override + public void onError(AsyncEvent event) throws IOException { + event.getThrowable().printStackTrace(); + } + + @Override + public void onComplete(AsyncEvent event) throws IOException {} + }); + } else if (req.getDispatcherType() == DispatcherType.ASYNC) { // #4 ASYNC dispatch to servlet order.add(Env.ASYNC); - environment.put(Env.ASYNC,ApiProxy.getCurrentEnvironment()); - async.start(new Runnable(){ - - @Override - public void run() { - try - { - // #5 run started Thread - order.add(Env.STARTED); - environment.put(Env.STARTED,ApiProxy.getCurrentEnvironment()); - final ServletOutputStream out = async.getResponse().getOutputStream(); - out.setWriteListener(new WriteListener() { - - @Override - public void onWritePossible() throws IOException { - - while (out.isReady()) - { - if (order.contains(Env.ON_WRITE_POSSIBLE)) - { - async.complete(); - return; - } - - // #6 on Write Possible - order.add(Env.ON_WRITE_POSSIBLE); - environment.put(Env.ON_WRITE_POSSIBLE,ApiProxy.getCurrentEnvironment()); - StringBuilder b=new StringBuilder(); - for (Env e : order) - { - Environment env = environment.get(e); - if (b.length()>0) - b.append(','); - b.append(e).append(':').append(env); - } - String o=b.toString(); - resp.setContentType("text/plain"); - resp.setStatus(200); - out.write(o.getBytes(StandardCharsets.ISO_8859_1)); - } - } - - @Override - public void onError(Throwable t) { + environment.put(Env.ASYNC, ApiProxy.getCurrentEnvironment()); + async.start( + new Runnable() { + + @Override + public void run() { + try { + // #5 run started Thread + order.add(Env.STARTED); + environment.put(Env.STARTED, ApiProxy.getCurrentEnvironment()); + final ServletOutputStream out = async.getResponse().getOutputStream(); + out.setWriteListener( + new WriteListener() { + + @Override + public void onWritePossible() throws IOException { + + while (out.isReady()) { + if (order.contains(Env.ON_WRITE_POSSIBLE)) { + async.complete(); + return; + } + + // #6 on Write Possible + order.add(Env.ON_WRITE_POSSIBLE); + environment.put(Env.ON_WRITE_POSSIBLE, ApiProxy.getCurrentEnvironment()); + StringBuilder b = new StringBuilder(); + for (Env e : order) { + Environment env = environment.get(e); + if (b.length() > 0) { + b.append(','); + } + b.append(e).append(':').append(env); + } + String o = b.toString(); + resp.setContentType("text/plain"); + resp.setStatus(200); + out.write(o.getBytes(StandardCharsets.ISO_8859_1)); + } + } + + @Override + public void onError(Throwable t) { + t.printStackTrace(); + } + }); + + } catch (Exception t) { t.printStackTrace(); } - }); - - }catch(Exception t){ - t.printStackTrace(); - } - - } - }); - } + } + }); + } } - - - } diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AuthServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AuthServlet.java index 7f5a400..02c1f82 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AuthServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/AuthServlet.java @@ -1,20 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import java.io.IOException; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BackendsApiServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BackendsApiServlet.java index b123eb0..5ac8290 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BackendsApiServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BackendsApiServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import com.google.appengine.api.backends.BackendService; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BlockingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BlockingServlet.java index 3a6bf16..07c01ff 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BlockingServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/BlockingServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import java.io.IOException; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CheckPermissionServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CheckPermissionServlet.java index 9dc7f9d..9817832 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CheckPermissionServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CheckPermissionServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import java.io.IOException; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderPrintingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderPrintingServlet.java index 44a13e9..bfdf10d 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderPrintingServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderPrintingServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import java.io.IOException; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderTestServlet.java index 6734d34..616b857 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderTestServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ClassLoaderTestServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import java.io.File; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CountServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CountServlet.java index 696be3a..5f63fe7 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CountServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CountServlet.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import com.google.appengine.api.datastore.DatastoreService; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurlServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurlServlet.java index 2212960..97a4c3c 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurlServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurlServlet.java @@ -1,29 +1,28 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; -import java.io.IOException; -import java.net.URL; - -import com.google.appengine.api.urlfetch.URLFetchService; -import com.google.appengine.api.urlfetch.URLFetchServiceFactory; import com.google.appengine.api.urlfetch.HTTPHeader; 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 java.io.IOException; +import java.net.URL; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurrentEnvironmentServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurrentEnvironmentServlet.java index e8a39e3..84d7a67 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurrentEnvironmentServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/CurrentEnvironmentServlet.java @@ -1,12 +1,12 @@ /** * Copyright 2015 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. diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DataViewerTestDataServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DataViewerTestDataServlet.java index e772a91..0fcda90 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DataViewerTestDataServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DataViewerTestDataServlet.java @@ -1,12 +1,12 @@ /** * Copyright 2015 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. diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreConfigPrintingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreConfigPrintingServlet.java index 8fc9aed..3d3b956 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreConfigPrintingServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreConfigPrintingServlet.java @@ -1,12 +1,12 @@ /** * Copyright 2015 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. diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreUnappliedJobsReportServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreUnappliedJobsReportServlet.java index abc50c1..6c3633f 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreUnappliedJobsReportServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DatastoreUnappliedJobsReportServlet.java @@ -1,12 +1,12 @@ /** * Copyright 2015 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. diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DefaultDatastoreConfigServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DefaultDatastoreConfigServlet.java index 69e969e..fc9d19b 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DefaultDatastoreConfigServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DefaultDatastoreConfigServlet.java @@ -1,12 +1,12 @@ /** * Copyright 2015 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. diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DoNothingFilter.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DoNothingFilter.java index be13ec7..67ef4d9 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DoNothingFilter.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DoNothingFilter.java @@ -1,19 +1,18 @@ /** * Copyright 2015 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.apphosting.tests.usercode.testservlets; import java.io.IOException; diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DumpServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DumpServlet.java index 35385d1..22818a2 100644 --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DumpServlet.java +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/DumpServlet.java @@ -11,7 +11,6 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. */ - package com.google.apphosting.tests.usercode.testservlets; import java.io.IOException; @@ -49,26 +48,33 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) out.printf("getServletContextName=%s%n", getServletContext().getServletContextName()); out.printf("virtualServerName=%s%n", getServletContext().getVirtualServerName()); out.printf("contextPath=%s%n", getServletContext().getContextPath()); - out.printf("version=%d.%d%n", getServletContext().getMajorVersion(), - getServletContext().getMinorVersion()); - out.printf("effectiveVersion=%d.%d%n", getServletContext().getEffectiveMajorVersion(), + out.printf( + "version=%d.%d%n", + getServletContext().getMajorVersion(), getServletContext().getMinorVersion()); + out.printf( + "effectiveVersion=%d.%d%n", + getServletContext().getEffectiveMajorVersion(), getServletContext().getEffectiveMinorVersion()); out.println(""); out.println("

    Request Fields:

    "); out.println("
    ");
    -    out.printf("remoteHost/Addr:port=%s/%s:%d%n", request.getRemoteHost(), request.getRemoteAddr(),
    -        request.getRemotePort());
    -    out.printf("localName/Addr:port=%s/%s:%d%n", request.getLocalName(), request.getLocalAddr(),
    -        request.getLocalPort());
    -    out.printf("scheme=%s method=%s protocol=%s%n", request.getScheme(), request.getMethod(),
    -        request.getProtocol());
    +    out.printf(
    +        "remoteHost/Addr:port=%s/%s:%d%n",
    +        request.getRemoteHost(), request.getRemoteAddr(), request.getRemotePort());
    +    out.printf(
    +        "localName/Addr:port=%s/%s:%d%n",
    +        request.getLocalName(), request.getLocalAddr(), request.getLocalPort());
    +    out.printf(
    +        "scheme=%s method=%s protocol=%s%n",
    +        request.getScheme(), request.getMethod(), request.getProtocol());
         out.printf("serverName:serverPort=%s:%d%n", request.getServerName(), request.getServerPort());
         out.printf("requestURI=%s%n", request.getRequestURI());
         out.printf("requestURL=%s%n", request.getRequestURL().toString());
    -    out.printf("contextPath|servletPath|pathInfo=%s|%s|%s%n", request.getContextPath(),
    -        request.getServletPath(), request.getPathInfo());
    -    out.printf("session/new=%s/%b%n", request.getSession(true).getId(),
    -        request.getSession().isNew());
    +    out.printf(
    +        "contextPath|servletPath|pathInfo=%s|%s|%s%n",
    +        request.getContextPath(), request.getServletPath(), request.getPathInfo());
    +    out.printf(
    +        "session/new=%s/%b%n", request.getSession(true).getId(), request.getSession().isNew());
         out.println("
    "); out.println("

    Request Headers:

    "); out.println("
    ");
    @@ -86,12 +92,12 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
           out.printf("s.id()=%s%n", session.getId());
           out.printf("s.new()=%b%n", session.isNew());
           out.printf("s.last()=%b%n", session.getLastAccessedTime());
    -      for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
    +      for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) {
             String n = e.nextElement();
             out.printf("%s=%s%n", n, session.getAttribute(n));
           }
     
    -      for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
    +      for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
             String n = e.nextElement();
             session.setAttribute(n, request.getParameter(n));
           }
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EchoServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EchoServlet.java
    index 195ee08..f224e70 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EchoServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EchoServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EnvironmentVariablePrintingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EnvironmentVariablePrintingServlet.java
    index 993863e..792afd9 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EnvironmentVariablePrintingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/EnvironmentVariablePrintingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ErrorGenerationServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ErrorGenerationServlet.java
    index 56ab969..9482fc1 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ErrorGenerationServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ErrorGenerationServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ExceptionInInitServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ExceptionInInitServlet.java
    index dd69912..d050a49 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ExceptionInInitServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ExceptionInInitServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FailInitializationServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FailInitializationServlet.java
    index 83c85d2..f50b398 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FailInitializationServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FailInitializationServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingNioServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingNioServlet.java
    index 87a022e..be3368a 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingNioServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingNioServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingServlet.java
    index 9da0656..6ab9125 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/FileReadingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/GetEnvironmentAttributesServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/GetEnvironmentAttributesServlet.java
    index 6d2bd78..0010702 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/GetEnvironmentAttributesServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/GetEnvironmentAttributesServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/HttpServletTest.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/HttpServletTest.java
    index b2fc2bc..2fde523 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/HttpServletTest.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/HttpServletTest.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/InitServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/InitServlet.java
    index 63c4569..fb4a0a7 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/InitServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/InitServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/JarFileReadingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/JarFileReadingServlet.java
    index b4c167f..de9a081 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/JarFileReadingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/JarFileReadingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoadOnStartupServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoadOnStartupServlet.java
    index 39ecf21..c487493 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoadOnStartupServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoadOnStartupServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -37,7 +37,7 @@
      * during initialization as it does when servicing a request.  Exceptions are
      * allowed since some attributes only make sense in the context of a user
      * request.  This is an attempt to avoid future incidences of
    - * bugs 
    + * bugs
      *
      */
     public class LoadOnStartupServlet extends HttpServlet {
    @@ -49,7 +49,8 @@ public class LoadOnStartupServlet extends HttpServlet {
     
       private static final ApiProxy.Environment INIT_ENV = ApiProxy.getCurrentEnvironment();
       public static final String HTTP_SERVLET_REQUEST = "com.google.appengine.http_servlet_request";
    -  public static final String MODULES_CONTROLLER_ATTRIBUTE_KEY = "com.google.appengine.dev.modules_controller";
    +  public static final String MODULES_CONTROLLER_ATTRIBUTE_KEY =
    +      "com.google.appengine.dev.modules_controller";
     
       /**
        * Attributes that don't need to be present in the init environment
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LocalDatastoreSmoketestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LocalDatastoreSmoketestServlet.java
    index 7a2c85f..ab39cff 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LocalDatastoreSmoketestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LocalDatastoreSmoketestServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogServlet.java
    index 8dd21f4..6ee31f1 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogSourceLocationServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogSourceLocationServlet.java
    index 043c7e1..48fde99 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogSourceLocationServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogSourceLocationServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogViewerServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogViewerServlet.java
    index 50eef06..400f33f 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogViewerServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LogViewerServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.log.AppLogLine;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoggingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoggingServlet.java
    index 1c7d702..093f73b 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoggingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoggingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -40,8 +40,8 @@ public class LoggingServlet extends HttpServlet {
       protected void doGet(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException {
     
    -    getServletContext().log("LogTest Hello "+req.getQueryString());
    -    
    +    getServletContext().log("LogTest Hello " + req.getQueryString());
    +
         resp.setContentType("text/plain");
         if (req.getParameter("printLogs") != null) {
           LogService ls = LogServiceFactory.getLogService();
    @@ -60,7 +60,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
           resp.getWriter().println(logger2.getLevel());
           resp.getWriter().println(configRan);
           logger2.severe("not null");
    -      logger2.severe((String)null);
    +      logger2.severe((String) null);
         }
       }
     
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoginServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoginServlet.java
    index e768a67..5226488 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoginServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/LoginServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MemoryServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MemoryServlet.java
    index f8303c4..72a2a22 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MemoryServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MemoryServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MulticoreTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MulticoreTestServlet.java
    index e58aff9..de707c8 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MulticoreTestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/MulticoreTestServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/OpenFilesServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/OpenFilesServlet.java
    index 74cd5b3..133f0af 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/OpenFilesServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/OpenFilesServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PermGenTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PermGenTestServlet.java
    index a6fd79b..629972e 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PermGenTestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PermGenTestServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintHeaders.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintHeaders.java
    index d711907..80ef2c8 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintHeaders.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintHeaders.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintParams.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintParams.java
    index 400571c..0cfb4d6 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintParams.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintParams.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintPathInfo.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintPathInfo.java
    index 8b26cd2..92e70b1 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintPathInfo.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintPathInfo.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintQueryParams.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintQueryParams.java
    index 00ac937..ece3660 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintQueryParams.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PrintQueryParams.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PublicRootPlugin.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PublicRootPlugin.java
    index 2341cc2..955707e 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PublicRootPlugin.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/PublicRootPlugin.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -19,11 +19,11 @@
     //import com.google.appengine.tools.development.ServiceProvider;
     
     //@ServiceProvider(AppYaml.Plugin.class)
    -public class PublicRootPlugin {//implements AppYaml.Plugin {
    -//  public AppYaml process(AppYaml yaml) {
    -//    if ("public".equals(yaml.getRuntime())) {
    -//      yaml.setPublic_root("/public");
    -//    }
    -//    return yaml;
    -//  }
    +public class PublicRootPlugin { //implements AppYaml.Plugin {
    +  //  public AppYaml process(AppYaml yaml) {
    +  //    if ("public".equals(yaml.getRuntime())) {
    +  //      yaml.setPublic_root("/public");
    +  //    }
    +  //    return yaml;
    +  //  }
     }
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/QueryIssuingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/QueryIssuingServlet.java
    index c23a039..e32a663 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/QueryIssuingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/QueryIssuingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RandomServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RandomServlet.java
    index 20c7310..c6ff7af 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RandomServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RandomServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ReflectionServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ReflectionServlet.java
    index 604605b..0d65fa4 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ReflectionServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ReflectionServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.lang.reflect.Method;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RemainingMillisServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RemainingMillisServlet.java
    index 541207b..284bbd6 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RemainingMillisServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RemainingMillisServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.utils.SystemProperty;
    @@ -50,8 +49,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOExce
         }
     
         res.setContentType("text/plain");
    -    res
    -        .getWriter()
    +    res.getWriter()
             .println("You are the bread and the knife, " + "the crystal goblet and the wine.");
     
         // Unfortunately, if we're using this servlet to test the DevAppServer we can't continue
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RequestDispatcherServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RequestDispatcherServlet.java
    index f7a3f2a..c4e4440 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RequestDispatcherServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/RequestDispatcherServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceBundlePrintingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceBundlePrintingServlet.java
    index c72ab0c..08f0d02 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceBundlePrintingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceBundlePrintingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceLoadingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceLoadingServlet.java
    index fbfcc3d..6547f6a 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceLoadingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResourceLoadingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResponseHeadersServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResponseHeadersServlet.java
    index d5b31fd..9798cb0 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResponseHeadersServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ResponseHeadersServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SAAJTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SAAJTestServlet.java
    index bfd1fcc..0c50de3 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SAAJTestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SAAJTestServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SearchServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SearchServlet.java
    index 3c96e18..15270ed 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SearchServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SearchServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.search.Document;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServeBlobServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServeBlobServlet.java
    index 456a7d5..5935669 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServeBlobServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServeBlobServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServerInfoServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServerInfoServlet.java
    index e57668e..83fc42c 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServerInfoServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServerInfoServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServersStartServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServersStartServlet.java
    index ee2f5bb..6d1bb2e 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServersStartServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServersStartServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.LifecycleManager;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServletContextResourceServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServletContextResourceServlet.java
    index 893002a..1303e9a 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServletContextResourceServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ServletContextResourceServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SessionUsingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SessionUsingServlet.java
    index 19b1621..645ab77 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SessionUsingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SessionUsingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ShutdownServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ShutdownServlet.java
    index cc6b68b..98d7795 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ShutdownServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ShutdownServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepAtInitServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepAtInitServlet.java
    index 8141c7a..50e00ab 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepAtInitServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepAtInitServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import javax.servlet.ServletException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepServlet.java
    index 8b5ad52..8149fa8 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SleepServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.apphosting.api.ApiBasePb.Integer32Proto;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SslTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SslTestServlet.java
    index 4c660c7..af68b9d 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SslTestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SslTestServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import java.io.IOException;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SystemPropertyPrintingServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SystemPropertyPrintingServlet.java
    index a0790f2..7f0f5b7 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SystemPropertyPrintingServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/SystemPropertyPrintingServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TagLibClassLoaderServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TagLibClassLoaderServlet.java
    index f58eaa1..b8ad15e 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TagLibClassLoaderServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TagLibClassLoaderServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TaskQueueServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TaskQueueServlet.java
    index 511196a..2816b02 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TaskQueueServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TaskQueueServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -334,11 +334,7 @@ private static String toString(Map map) {
           return " ";
         }
         for (Map.Entry entry : map.entrySet()) {
    -      sb
    -          .append(entry.getKey())
    -          .append(SEPARATOR)
    -          .append(entry.getValue())
    -          .append(SEPARATOR);
    +      sb.append(entry.getKey()).append(SEPARATOR).append(entry.getValue()).append(SEPARATOR);
         }
         return sb.toString();
       }
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestBlobUploadServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestBlobUploadServlet.java
    index dbe3045..382f677 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestBlobUploadServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestBlobUploadServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -124,12 +124,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx
     
         // Verify blob keys are present.
         if (blobs.size() == 1) {
    -      BlobKey blobKey =
    -          blobs
    -              .entrySet()
    -              .iterator()
    -              .next()
    -              .getValue();
    +      BlobKey blobKey = blobs.entrySet().iterator().next().getValue();
           resp.sendRedirect("/serve-blob?key=" + blobKey.getKeyString());
         } else {
           resp.sendError(
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestDatagramSocketServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestDatagramSocketServlet.java
    index 7aa744e..5ad30fb 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestDatagramSocketServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestDatagramSocketServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.socket.SocketServicePb.AcceptReply;
    @@ -412,8 +411,7 @@ protected void join(InetAddress inetaddr) throws IOException {}
         protected void leave(InetAddress inetaddr) throws IOException {}
     
         @Override
    -    protected void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException {
    -    }
    +    protected void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException {}
     
         @Override
         protected void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException {}
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestInetAddressServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestInetAddressServlet.java
    index 29b01ab..e630667 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestInetAddressServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestInetAddressServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.socket.SocketServicePb.ResolveReply;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestMetadataServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestMetadataServlet.java
    index 262ecaa..e8c56af 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestMetadataServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestMetadataServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.NamespaceManager;
    @@ -73,15 +72,7 @@ public void testMetadata(DatastoreService ds, HttpServletResponse response) thro
         Query q = new Query(Query.KIND_METADATA_KIND);
         q.addFilter(
             Entity.KEY_RESERVED_PROPERTY, Query.FilterOperator.LESS_THAN_OR_EQUAL, makeKindKey("M"));
    -    assertEquals(
    -        "",
    -        "Fun",
    -        ds
    -            .prepare(q)
    -            .asSingleEntity()
    -            .getKey()
    -            .getName(),
    -        response);
    +    assertEquals("", "Fun", ds.prepare(q).asSingleEntity().getKey().getName(), response);
       }
     
       private void populate(DatastoreService ds, String namespace) {
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServlet.java
    index 0ba3722..0ba0bef 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServletContextListener.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServletContextListener.java
    index 67963b3..450db14 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServletContextListener.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestServletContextListener.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestSocketServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestSocketServlet.java
    index 6047a96..99f089e 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestSocketServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TestSocketServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets;
     
     import com.google.appengine.api.socket.SocketServicePb.AcceptReply;
    @@ -391,9 +390,7 @@ protected void connect(InetAddress address, int port) throws IOException {}
          * @see java.net.SocketImpl#connect(java.net.SocketAddress, int)
          */
         @Override
    -    protected void connect(SocketAddress address, int timeout) throws IOException {
    -
    -    }
    +    protected void connect(SocketAddress address, int timeout) throws IOException {}
     
         /* (non-Javadoc)
          * @see java.net.SocketImpl#bind(java.net.InetAddress, int)
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadPoolExecutorServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadPoolExecutorServlet.java
    index a2bdd7e..4b5dbf4 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadPoolExecutorServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadPoolExecutorServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadServlet.java
    index 1bc7fc2..5efc2eb 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/ThreadServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TimeZoneServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TimeZoneServlet.java
    index 48f1e72..de1ba4a 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TimeZoneServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TimeZoneServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TransactionAbandoningServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TransactionAbandoningServlet.java
    index 986238d..14c5a4a 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TransactionAbandoningServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/TransactionAbandoningServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/URLTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/URLTestServlet.java
    index 3c7843f..fc22bc0 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/URLTestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/URLTestServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/UrlOverSocketsTestServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/UrlOverSocketsTestServlet.java
    index 57739fa..4166829 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/UrlOverSocketsTestServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/UrlOverSocketsTestServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -141,7 +141,8 @@ public byte[] makeResponse(UrlMethod method, byte[] request) {
                   SendRequest requestProto = new SendRequest();
                   requestProto.parseFrom(request);
                   return new SendReply()
    -                  .setDataSent(requestProto.getDataAsBytes().length).toByteArray();
    +                  .setDataSent(requestProto.getDataAsBytes().length)
    +                  .toByteArray();
                 }
               }),
           Receive(
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/appstats/AppstatsMonitoredServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/appstats/AppstatsMonitoredServlet.java
    index c269d32..893d7e9 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/appstats/AppstatsMonitoredServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/appstats/AppstatsMonitoredServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/filterinit/FailInitializationFilter.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/filterinit/FailInitializationFilter.java
    index a889224..2a2d693 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/filterinit/FailInitializationFilter.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/filterinit/FailInitializationFilter.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/logging/LogTest.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/logging/LogTest.java
    index 17a2dd8..11ea0f7 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/logging/LogTest.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/logging/LogTest.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -43,8 +43,8 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
     
         getServletContext().log("LogTest Hello");
    -    getServletContext().log("LogTest Exception ",new Throwable());
    -    
    +    getServletContext().log("LogTest Exception ", new Throwable());
    +
         String configFile = System.getProperty("java.util.logging.config.file");
     
         if (configFile == null) {
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiClientServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiClientServlet.java
    index 489ed4e..d18f0e3 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiClientServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiClientServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -15,7 +15,6 @@
      */
     package com.google.apphosting.tests.usercode.testservlets.remoteapi;
     
    -
     import java.io.IOException;
     
     import javax.servlet.http.HttpServlet;
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiInsideAppEngineExample.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiInsideAppEngineExample.java
    index 0e65412..0958c14 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiInsideAppEngineExample.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiInsideAppEngineExample.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -23,13 +23,12 @@
     import java.io.IOException;
     
     /**
    - * App Engine client example code 
    + * App Engine client example code
      * illustrating how to use Remote API from within an App Engine app.  If this
      * code is not compiling you must update the documentation with any changes you
      * make to this file.
      *
      */
    -
     class RemoteApiInsideAppEngineExample {
       private final RemoteApiOptions options;
     
    @@ -38,7 +37,8 @@ class RemoteApiInsideAppEngineExample {
         // once during construction and then store the credentials for reuse.
         this.options =
             new RemoteApiOptions()
    -            .server("<your target app>.appspot.com", 443).credentials(username, password);
    +            .server("<your target app>.appspot.com", 443)
    +            .credentials(username, password);
         RemoteApiInstaller installer = new RemoteApiInstaller();
         installer.install(options);
         try {
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiSharedTests.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiSharedTests.java
    index c9c95bd..3e8dcb9 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiSharedTests.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/remoteapi/RemoteApiSharedTests.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    @@ -176,10 +176,11 @@ private RemoteApiSharedTests(
        * cases passed.
        */
       public void runTests() throws IOException {
    -    RemoteApiOptions options = new RemoteApiOptions()
    -        .server(server, port)
    -        .credentials(username, password)
    -        .remoteApiPath(remoteApiPath);
    +    RemoteApiOptions options =
    +        new RemoteApiOptions()
    +            .server(server, port)
    +            .credentials(username, password)
    +            .remoteApiPath(remoteApiPath);
     
         // Once we install the RemoteApi, all keys will start using the remote app id.  We'll store some
         // keys with the local app id first.
    @@ -222,12 +223,13 @@ public void runTests() throws IOException {
       private void doTest(LocalKeysHolder localKeysHolder, LocalEntitiesHolder localEntitiesHolder) {
         DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
     
    -    List tests = Lists.newLinkedList(
    -        new PutAndGetTester(),
    -        new PutAndGetInTransactionTester(),
    -        new QueryTester(),
    -        new DeleteTester(),
    -        new XgTransactionTester());
    +    List tests =
    +        Lists.newLinkedList(
    +            new PutAndGetTester(),
    +            new PutAndGetInTransactionTester(),
    +            new QueryTester(),
    +            new DeleteTester(),
    +            new XgTransactionTester());
     
         // Run each test once with local keys and once with remote keys.
         for (RemoteApiUnitTest test : tests) {
    @@ -662,4 +664,4 @@ private Entity quietGet(DatastoreService ds, Key key) {
       private String getFreshKindName() {
         return "testkind" + UUID.randomUUID();
       }
    -}
    \ No newline at end of file
    +}
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/Restricted.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/Restricted.java
    index d23338d..ed8d805 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/Restricted.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/Restricted.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestPermissions.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestPermissions.java
    index af9649f..4660ade 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestPermissions.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestPermissions.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestReflection.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestReflection.java
    index cd97df4..8136fa3 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestReflection.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestReflection.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestRepackagedAccess.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestRepackagedAccess.java
    index 08bb993..e49b4d2 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestRepackagedAccess.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestRepackagedAccess.java
    @@ -1,18 +1,19 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets.security;
    + */
    +package com.google.apphosting.tests.usercode.testservlets.security;
     
     /**
      * {@link Restricted} gets repackaged into com.google.appengine.repackaged
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestWhiteList.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestWhiteList.java
    index b1fdb21..dd9f136 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestWhiteList.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/security/TestWhiteList.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/AsyncSessionServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/AsyncSessionServlet.java
    index a7a1aea..3695946 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/AsyncSessionServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/AsyncSessionServlet.java
    @@ -1,18 +1,19 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets.session;
    + */
    +package com.google.apphosting.tests.usercode.testservlets.session;
     
     import java.io.IOException;
     
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/DynProxyInSessionServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/DynProxyInSessionServlet.java
    index 5343c3c..c57bae5 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/DynProxyInSessionServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/DynProxyInSessionServlet.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/Foo.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/Foo.java
    index ee6aa2c..6da3f44 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/Foo.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/Foo.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/FooImpl.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/FooImpl.java
    index 2c0faea..4545850 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/FooImpl.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/FooImpl.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/MyProxy.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/MyProxy.java
    index 643a4c5..b26a509 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/MyProxy.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/session/MyProxy.java
    @@ -1,12 +1,12 @@
     /**
      * Copyright 2015 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.
    diff --git a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/xxe/XXEServlet.java b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/xxe/XXEServlet.java
    index 805aa4b..1562a9f 100644
    --- a/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/xxe/XXEServlet.java
    +++ b/testwebapp/src/main/java/com/google/apphosting/tests/usercode/testservlets/xxe/XXEServlet.java
    @@ -1,19 +1,18 @@
     /**
      * Copyright 2015 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.apphosting.tests.usercode.testservlets.xxe;
     
     import java.io.IOException;