本文整理汇总了Java中com.google.apphosting.api.ApiProxy.setEnvironmentForCurrentThread方法的典型用法代码示例。如果您正苦于以下问题:Java ApiProxy.setEnvironmentForCurrentThread方法的具体用法?Java ApiProxy.setEnvironmentForCurrentThread怎么用?Java ApiProxy.setEnvironmentForCurrentThread使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.apphosting.api.ApiProxy
的用法示例。
在下文中一共展示了ApiProxy.setEnvironmentForCurrentThread方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: run
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
@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();
}
}
示例2: newThread
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
/**
* 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;
}
示例3: doAsyncGcdTest
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
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());
}
示例4: doStop
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
@Override
protected void doStop() throws Exception {
ApiProxy.setEnvironmentForCurrentThread(environment);
helper.tearDown();
environment = null;
super.doStop();
}
示例5: onMessage
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
/**
* 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);
}
示例6: init
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
/**
* 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));
}
示例7: doScope
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
/**
* 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);
}
}
}
}
示例8: handle
import com.google.apphosting.api.ApiProxy; //导入方法依赖的package包/类
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException,
ServletException {
ApiProxy.setEnvironmentForCurrentThread(environment);
super.handle(target, request, response, dispatch);
}