Java Code Examples for com.google.apphosting.api.ApiProxy#setEnvironmentForCurrentThread()
The following examples show how to use
com.google.apphosting.api.ApiProxy#setEnvironmentForCurrentThread() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OrphanedJobGraphTest.java From appengine-pipelines with Apache License 2.0 | 6 votes |
@Override public void run() { PipelineService service = PipelineServiceFactory.newPipelineService(); ApiProxy.setEnvironmentForCurrentThread(apiProxyEnvironment); // TODO(user): Try something better than sleep to make sure // this happens after the processing the caller's runTask try { Thread.sleep(1000); } catch (InterruptedException e1) { // ignore - use uninterruptables } try { service.submitPromisedValue(promiseHandle, 0); } catch (NoSuchObjectException e) { throw new RuntimeException(e); } catch (OrphanedObjectException f) { orphanedObjectExcetionCount.incrementAndGet(); } }
Example 2
Source File: VmRequestThreadFactory.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
/** * Create a new {@link Thread} that executes {@code runnable} for the duration of the current * request. This thread will be interrupted at the end of the current request. * * @param runnable The object whose run method is invoked when this thread is started. If null, * this classes run method does nothing. * * @throws ApiProxy.ApiProxyException If called outside of a running request. * @throws IllegalStateException If called after the request thread stops. */ @Override public Thread newThread(final Runnable runnable) { 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(); } }); checkState( allowNewRequestThreadCreation, "Cannot create new threads after the request thread stops."); synchronized (mutex) { createdThreads.add(thread); } return thread; }
Example 3
Source File: AppEngineEnvironment.java From nomulus with Apache License 2.0 | 5 votes |
public AppEngineEnvironment() { isPlaceHolderNeeded = ApiProxy.getCurrentEnvironment() == null; // isPlaceHolderNeeded may be true when we are invoked in a test with AppEngineRule. if (isPlaceHolderNeeded) { ApiProxy.setEnvironmentForCurrentThread(PLACEHOLDER_ENV); } }
Example 4
Source File: GCDTest.java From appengine-pipelines with Apache License 2.0 | 5 votes |
private void doAsyncGcdTest(final String userName, final int x, final int y, String expectedMessage) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final StringBuilder builder = new StringBuilder(); AsyncGCDExample.callback = new AsyncGCDExample.Callback() { @Override public String getUserName() { ApiProxy.setEnvironmentForCurrentThread(apiProxyEnvironment); return userName; } @Override public int getSecondInt() { ApiProxy.setEnvironmentForCurrentThread(apiProxyEnvironment); return y; } @Override public int getFirstInt() { ApiProxy.setEnvironmentForCurrentThread(apiProxyEnvironment); return x; } @Override public void acceptOutput(String output) { builder.append(output); latch.countDown(); } }; PipelineService service = PipelineServiceFactory.newPipelineService(); String pipelineId = service.startNewPipeline(new PrintGCDJob()); assertTrue(latch.await(3, TimeUnit.MINUTES)); assertEquals(expectedMessage, builder.toString()); // Wait for job task thread to complete Thread.sleep(2000); JobInfo jobInfo = service.getJobInfo(pipelineId); assertEquals(JobInfo.State.COMPLETED_SUCCESSFULLY, jobInfo.getJobState()); }
Example 5
Source File: AppengineWebAppContext.java From yawp with MIT License | 5 votes |
@Override protected void doStop() throws Exception { ApiProxy.setEnvironmentForCurrentThread(environment); helper.tearDown(); environment = null; super.doStop(); }
Example 6
Source File: ChatSocketServer.java From appengine-websocketchat-java with Apache License 2.0 | 5 votes |
/** * Handles incoming messages. * * If the type of the incoming message is MessageType.ENTER, we need to check the username * against the current participant list and change the requested name with trailing underscores. * Regardless of the type, we invoke sendToClient method with every incoming messages. * * @param conn a websocket connection object. * @param rawMessage a raw message from the clients. */ @Override public void onMessage(WebSocket conn, String rawMessage) { // TODO: Make it threadsafe LOG.info(conn + ": " + rawMessage); ApiProxy.setEnvironmentForCurrentThread( ChatServerBridge.getInstance().getBackgroundEnvironment()); ChatMessage message = GSON.fromJson(rawMessage, ChatMessage.class); if (message.getType().equals(OutgoingMessage.MessageType.ENTER)) { // Check if there's a participant with the same name in the room. Set<String> participantSet = ChatRoomParticipants.getParticipants(message.getRoom()); if (participantSet.contains(message.getName())) { // Adding a trailing underscore until the conflict resolves. String newName = message.getName() + "_"; while (participantSet.contains(newName)) { newName = newName + "_"; } // New name decided. message = new ChatMessage(message.getType(), newName, message.getRoom(), message.getMessage()); ChatMessage systemMessage = new ChatMessage(OutgoingMessage.MessageType.SYSTEM, newName, message.getRoom(), "Changed the name to " + newName + "."); conn.send(GSON.toJson(systemMessage)); } metaInfoManager.addConnection(conn, message.getName(), message.getRoom()); if (! updateAndSendParticipantListQueue.contains(message.getRoom())) { updateAndSendParticipantListQueue.add(message.getRoom()); } } this.sendToClients(message); }
Example 7
Source File: AppEngineEnvironment.java From nomulus with Apache License 2.0 | 4 votes |
@Override public void close() { if (isPlaceHolderNeeded) { ApiProxy.setEnvironmentForCurrentThread(null); } }
Example 8
Source File: DatastoreEntityExtension.java From nomulus with Apache License 2.0 | 4 votes |
@Override public void beforeEach(ExtensionContext context) { ApiProxy.setEnvironmentForCurrentThread(PLACEHOLDER_ENV); }
Example 9
Source File: DatastoreEntityExtension.java From nomulus with Apache License 2.0 | 4 votes |
@Override public void afterEach(ExtensionContext context) { // Clear the cached instance. ApiProxy.setEnvironmentForCurrentThread(null); }
Example 10
Source File: VmRuntimeWebAppContext.java From appengine-java-vm-runtime with Apache License 2.0 | 4 votes |
/** * Initialize the WebAppContext for use by the VmRuntime. * * This method initializes the WebAppContext by setting the context path and application folder. * It will also parse the appengine-web.xml file provided to set System Properties and session * manager accordingly. * * @param appengineWebXmlFile The appengine-web.xml file path (relative to appDir). * @throws AppEngineConfigException If there was a problem finding or parsing the * appengine-web.xml configuration. * @throws IOException If the runtime was unable to find/read appDir. */ 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); ApiProxy.setEnvironmentForCurrentThread(defaultEnvironment); if (ApiProxy.getEnvironmentFactory() == null) { // Need the check above since certain unit tests initialize the context multiple times. ApiProxy.setEnvironmentFactory(new VmEnvironmentFactory(defaultEnvironment)); } isDevMode = defaultEnvironment.getPartition().equals("dev"); AppEngineWebXml appEngineWebXml = null; File appWebXml = new File(appDir, appengineWebXmlFile); if (appWebXml.exists()) { AppEngineWebXmlReader appEngineWebXmlReader = new AppEngineWebXmlReader(appDir, appengineWebXmlFile); appEngineWebXml = appEngineWebXmlReader.readAppEngineWebXml(); } VmRuntimeUtils.installSystemProperties(defaultEnvironment, appEngineWebXml); VmRuntimeLogHandler.init(); VmRuntimeFileLogHandler.init(); for (String systemClass : SYSTEM_CLASSES) { addSystemClass(systemClass); } if (appEngineWebXml == null) { // No need to configure the session manager. return; } AbstractSessionManager sessionManager; if (appEngineWebXml.getSessionsEnabled()) { sessionManager = new SessionManager(createSessionStores(appEngineWebXml)); getSessionHandler().setSessionManager(sessionManager); } setProtectedTargets(ArrayUtil.addToArray(getProtectedTargets(), "/app.yaml", String.class)); }
Example 11
Source File: VmRuntimeWebAppContext.java From appengine-java-vm-runtime with Apache License 2.0 | 4 votes |
/** * Overrides doScope from ScopedHandler. * * Configures a thread local environment before the request is forwarded on to be handled by the * SessionHandler, SecurityHandler, and ServletHandler in turn. The environment is required for * AppEngine APIs to function. A request specific environment is required since some information * is encoded in request headers on the request (for example current user). */ @Override public final void doScope( String target, Request baseRequest, HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse) throws IOException, ServletException { HttpRequest request = new HttpServletRequestAdapter(httpServletRequest); HttpResponse response = new HttpServletResponseAdapter(httpServletResponse); // For JSP Includes do standard processing, everything else has been done // in the main request before the include. if (DispatcherType.INCLUDE.equals(httpServletRequest.getDispatcherType()) || DispatcherType.FORWARD.equals(httpServletRequest.getDispatcherType())) { super.doScope(target, baseRequest, httpServletRequest, httpServletResponse); return; } // Install a thread local environment based on request headers of the current request. VmApiProxyEnvironment requestSpecificEnvironment = VmApiProxyEnvironment.createFromHeaders( System.getenv(), metadataCache, request, VmRuntimeUtils.getApiServerAddress(), wallclockTimer, VmRuntimeUtils.ONE_DAY_IN_MILLIS, defaultEnvironment); CommitDelayingResponse wrappedResponse; if (httpServletResponse instanceof CommitDelayingResponse) { wrappedResponse = (CommitDelayingResponse) httpServletResponse; } else { wrappedResponse = new CommitDelayingResponse(httpServletResponse); } try { ApiProxy.setEnvironmentForCurrentThread(requestSpecificEnvironment); // Check for SkipAdminCheck and set attributes accordingly. VmRuntimeUtils.handleSkipAdminCheck(request); // Change scheme to HTTPS based on headers set by the appserver. setSchemeAndPort(baseRequest); // Forward the request to the rest of the handlers. super.doScope(target, baseRequest, httpServletRequest, wrappedResponse); } finally { try { // Interrupt any remaining request threads and wait for them to complete. VmRuntimeUtils.interruptRequestThreads( requestSpecificEnvironment, VmRuntimeUtils.MAX_REQUEST_THREAD_INTERRUPT_WAIT_TIME_MS); // Wait for any pending async API requests to complete. if (!VmRuntimeUtils.waitForAsyncApiCalls(requestSpecificEnvironment, new HttpServletResponseAdapter(wrappedResponse))) { logger.warning("Timed out or interrupted while waiting for async API calls to complete."); } if (!response.isCommitted()) { // Flush and set the flush count header so the appserver knows when all logs are in. VmRuntimeUtils.flushLogsAndAddHeader(response, requestSpecificEnvironment); } else { logger.warning("Response for request to '" + target + "' was already committed (code=" + httpServletResponse.getStatus() + "). This might result in lost log messages.'"); } } finally { try { // Complete any pending actions. wrappedResponse.commit(); } finally { // Restore the default environment. ApiProxy.setEnvironmentForCurrentThread(defaultEnvironment); } } } }
Example 12
Source File: AppengineWebAppContext.java From yawp with MIT License | 4 votes |
@Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { ApiProxy.setEnvironmentForCurrentThread(environment); super.handle(target, request, response, dispatch); }