@Inject public NinjaAppengineEnvironmentProvider(Injector injector, NinjaProperties ninjaProperties) { this.ninjaProperties = ninjaProperties; // make sure we return null when we are in production // or the environment is already registered (will be the case in appengine:devserver mode if (ninjaProperties.isProd() || ApiProxy.getCurrentEnvironment() != null) { ninjaAppengineEnvironment = injector.getInstance(NinjaAppengineEnvironmentNull.class); } else { ninjaAppengineEnvironment = injector.getInstance(NinjaAppengineEnvironmentImpl.class); } }
@Override public void initOrSkip() { // Create a fake development environment if not run in the Google SDK if (ApiProxy.getCurrentEnvironment() == null) { ApiProxy.setEnvironmentForCurrentThread(this); } }
/** * @return {@code true} if there is time and space left to continue adding more snapshots, * or if we should stop here. */ public boolean timeAndSpaceRemaining() { // Do we have enough time left in this request to do any more work? long timeRemaining = ApiProxy.getCurrentEnvironment().getRemainingMillis(); if(timeRemaining < BUFFER_MS) { return false; } if(estimatedSizeInBytes > MAX_RESPONSE_SIZE) { return false; } return true; }
/** * Runs calls in a background thread so that the results will actually be asynchronous. * * @see com.google.appengine.tools.cloudstorage.RawGcsService#continueObjectCreationAsync( * com.google.appengine.tools.cloudstorage.RawGcsService.RawGcsCreationToken, * java.nio.ByteBuffer, long) */ @Override public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token, final ByteBuffer chunk, long timeoutMillis) { try { ensureInitialized(); } catch (IOException e) { throw new RuntimeException(e); } final Environment environment = ApiProxy.getCurrentEnvironment(); return writePool.schedule(new Callable<RawGcsCreationToken>() { @Override public RawGcsCreationToken call() throws Exception { ApiProxy.setEnvironmentForCurrentThread(environment); return append(token, chunk); } }, 50, TimeUnit.MILLISECONDS); }
/** * Wait for caching to finish, if there is time left in this request. */ @Override public void waitForCachingToFinish(List<Future<Integer>> pendingCachePuts) { Stopwatch stopwatch = Stopwatch.createStarted(); int columnCount = 0; for (Future<Integer> future : pendingCachePuts) { if (!future.isDone()) { long remainingMillis = ApiProxy.getCurrentEnvironment().getRemainingMillis(); if (remainingMillis > 100) { try { Integer cachedCount = future.get(remainingMillis - 50, TimeUnit.MILLISECONDS); columnCount += cachedCount; } catch (InterruptedException | TimeoutException e) { LOGGER.warning("Ran out of time while waiting for caching of results to complete."); return; } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Exception caching results of query", e); } } } } LOGGER.info("Waited " + stopwatch + " for " + columnCount + " columns to finish caching."); }
private static Queue getQueue(String queueName) { if (queueName == null) { Map<String, Object> attributes = ApiProxy.getCurrentEnvironment().getAttributes(); queueName = (String) attributes.get(TaskHandler.TASK_QUEUE_NAME_HEADER); } return queueName == null ? QueueFactory.getDefaultQueue() : QueueFactory.getQueue(queueName); }
public static ListeningExecutorService currentRequestExecutorService() { ThreadFactory factory = checkNotNull(ThreadManager.currentRequestThreadFactory(), "ThreadManager.currentRequestThreadFactory()"); // GAE requests cannot exceed 10 threads per request int maxThreads = 10; long keepAlive = ApiProxy.getCurrentEnvironment().getRemainingMillis(); ExecutorService pool = newScalingThreadPool(0, maxThreads, keepAlive, factory); return WithSubmissionTrace.wrap(MoreExecutors.listeningDecorator(pool)); }
public static ListeningExecutorService currentRequestExecutorService() { ThreadFactory factory = checkNotNull(ThreadManager.currentRequestThreadFactory(), "ThreadManager.currentRequestThreadFactory()"); // GAE requests cannot exceed 10 threads per request int maxThreads = 10; long keepAlive = ApiProxy.getCurrentEnvironment().getRemainingMillis(); ExecutorService pool = newScalingThreadPool(0, maxThreads, keepAlive, factory); return WithSubmissionTrace.wrap(MoreExecutors.listeningDecorator(pool)); }
private static Task reconstructTask(HttpServletRequest request) { Properties properties = new Properties(); Enumeration<?> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); String paramValue = request.getParameter(paramName); properties.setProperty(paramName, paramValue); } String taskName = request.getHeader(TASK_NAME_REQUEST_HEADER); Task task = Task.fromProperties(taskName, properties); task.getQueueSettings().setDelayInSeconds(null); String queueName = request.getHeader(TASK_QUEUE_NAME_HEADER); if (queueName != null && !queueName.isEmpty()) { String onQueue = task.getQueueSettings().getOnQueue(); if (onQueue == null || onQueue.isEmpty()) { task.getQueueSettings().setOnQueue(queueName); } Map<String, Object> attributes = ApiProxy.getCurrentEnvironment().getAttributes(); attributes.put(TASK_QUEUE_NAME_HEADER, queueName); } return task; } }
public static String getCurrentRequestId() { return (String) ApiProxy.getCurrentEnvironment().getAttributes().get("com.google.appengine.runtime.request_log_id"); } }
protected static URL getUrl(String path) throws MalformedURLException { ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); Object localhost = env.getAttributes().get("com.google.appengine.runtime.default_version_hostname"); return new URL("http://" + localhost + "/" + path); }
public String getApp() { return ApiProxy.getCurrentEnvironment().getAppId(); }
if (ApiProxy.getCurrentEnvironment() == null) {
@Test public void testGetVersionedHostname() { String expectedHostname = getExpectedAppHostname("testGetVersionedHostname"); ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); String hostname = (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname"); String errMsg = "The versioned hostname should end with " + expectedHostname + ", but was " + hostname; Assert.assertTrue(errMsg, hostname.endsWith(expectedHostname)); }
@Test public void testInstanceId() { ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); String instanceId = (String) env.getAttributes().get("com.google.appengine.instance.id"); String errMsg = "The instance id should not be null"; Assert.assertNotNull(errMsg, instanceId); }
@Test public void testRequestId() { ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); String requestId = (String) env.getAttributes().get("com.google.appengine.runtime.request_log_id"); String errMsg = "The request id should not be null"; Assert.assertNotNull(errMsg, requestId); } }
@Test public void testGetAppId() { String expectedAppId = getExpectedAppId("testGetAppId"); String appId = ApiProxy.getCurrentEnvironment().getAppId(); // AppIds in the US are prefixed with s~ and in Europe e~ so just match the end. String errMsg = "The appId should end with " + expectedAppId + ", but was " + appId; Assert.assertTrue(errMsg, appId.endsWith(expectedAppId)); }
@Test public void testGetDefaultGcsBucketName() { ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); String expectedBucketName; Property property = property("testGetDefaultGcsBucketName"); if (property.exists()) { expectedBucketName = property.getPropertyValue(); } else { expectedBucketName = (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname"); } try { String bucketName = appIdentity.getDefaultGcsBucketName(); Assert.assertEquals(expectedBucketName, bucketName); } catch (AppIdentityServiceFailureException aisfe) { //TODO: This means that there is no default bucket setup for this project. Have a better way to verify this. } }
@Override protected void doStart() throws Exception { this.helper = createHelper(); this.environment = ApiProxy.getCurrentEnvironment(); getServletContext().setAttribute(API_PROXY_LOCAL, ApiProxy.getDelegate()); getServletContext().setAttribute(APPENGINE_WEB_XML, readAppengineWebXml()); getServletContext().setAttribute(WEB_XML, readWebXml()); SystemProperty.environment.set(SystemProperty.Environment.Value.Development); configureUserRealmAppengineHelper(); super.doStart(); }
@Test public void testParseFullAppId() { // [(partition)~][(domain):](display-app-id) ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); String hostname = (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname"); AppIdentityService.ParsedAppId parsed = appIdentity.parseFullAppId(hostname); String message = createParsed(parsed); Assert.assertEquals(message, property("testParseFullAppId_partition").getPropertyValue(), parsed.getPartition()); Assert.assertEquals(message, getExpectedAppHostname("testParseFullAppId_domain"), parsed.getDomain()); Assert.assertEquals(message, getExpectedAppId("testParseFullAppId_id"), parsed.getId()); }