@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); } }
/** * Install our hook in the delegate system. This happens automatically when this class is * loaded, which is typically what you want when working with Objectify. It gets a lot * more complicated when you're working with the RemoteApiInstaller. */ public static synchronized void install() { // Already installed if (ApiProxy.getDelegate() instanceof TriggerFutureHook) return; @SuppressWarnings("unchecked") TriggerFutureHook hook = new TriggerFutureHook(ApiProxy.getDelegate()); if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) ApiProxy.setDelegate(hook); else ApiProxy.setDelegate(wrapPartially(ApiProxy.getDelegate(), hook)); }
@Override public void initOrSkip() { // Create a fake development environment if not run in the Google SDK if (ApiProxy.getCurrentEnvironment() == null) { ApiProxy.setEnvironmentForCurrentThread(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(); }
if (ApiProxy.getCurrentEnvironment() == null) { ApiProxy.setDelegate(proxy);
private static BlobStorageAdapter getInstance() throws IOException { Delegate<?> apiProxyDelegate = ApiProxy.getDelegate(); if (instance == null || instance.apiProxyDelegate != apiProxyDelegate) { try { instance = new BlobStorageAdapter(apiProxyDelegate); } catch (Exception e) { throw new IOException(e); } } return instance; } }
@Override public RawGcsCreationToken call() throws Exception { ApiProxy.setEnvironmentForCurrentThread(environment); return append(token, chunk); } }, 50, TimeUnit.MILLISECONDS);
static RawGcsService createRawGcsService(Map<String, String> headers) { ImmutableSet.Builder<HTTPHeader> builder = ImmutableSet.builder(); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { builder.add(new HTTPHeader(header.getKey(), header.getValue())); } } RawGcsService rawGcsService; Value location = SystemProperty.environment.value(); if (location == SystemProperty.Environment.Value.Production || hasCustomAccessTokenProvider()) { rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build()); } else if (location == SystemProperty.Environment.Value.Development) { rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService(); } else { Delegate<?> delegate = ApiProxy.getDelegate(); if (delegate == null || delegate.getClass().getName().startsWith("com.google.appengine.tools.development")) { rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService(); } else { rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build()); } } return rawGcsService; }
@Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { ApiProxy.setEnvironmentForCurrentThread(environment); super.handle(target, request, response, dispatch); }
/** * @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; }
@Override protected void doStop() throws Exception { ApiProxy.setEnvironmentForCurrentThread(environment); helper.tearDown(); environment = null; super.doStop(); }
/** * 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(); }