Java Code Examples for com.google.apphosting.api.ApiProxy#setDelegate()

The following examples show how to use com.google.apphosting.api.ApiProxy#setDelegate() . 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: VmRuntimeWebAppContext.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new VmRuntimeWebAppContext.
 */
public VmRuntimeWebAppContext() {
  this.serverInfo = VmRuntimeUtils.getServerInfo();
  _scontext = new VmRuntimeServletContext();

  // Configure the Jetty SecurityHandler to understand our method of authentication
  // (via the UserService). Only the default ConstraintSecurityHandler is supported.
  AppEngineAuthentication.configureSecurityHandler(
      (ConstraintSecurityHandler) getSecurityHandler(), this);

  setMaxFormContentSize(MAX_RESPONSE_SIZE);
  setConfigurationClasses(preconfigurationClasses);
  // See http://www.eclipse.org/jetty/documentation/current/configuring-webapps.html#webapp-context-attributes
  // We also want the Jetty container libs to be scanned for annotations.
  setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*\\.jar");
  metadataCache = new VmMetadataCache();
  wallclockTimer = new VmTimer();
  ApiProxy.setDelegate(new VmApiProxyDelegate());
}
 
Example 2
Source File: SessionManagerTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
 public void testDatastoreTimeouts() throws EntityNotFoundException {
   Delegate original = ApiProxy.getDelegate();
   // Throw in a couple of datastore timeouts
   TimeoutGeneratingDelegate newDelegate = new TimeoutGeneratingDelegate(original);
   try {
     ApiProxy.setDelegate(newDelegate);

     HttpServletRequest request = makeMockRequest(true);
        replay(request);
AppEngineSession session = manager.newSession(request);
     session.setAttribute("foo", "bar");
     newDelegate.setTimeouts(3);
     session.save();
     assertEquals(newDelegate.getTimeoutsRemaining(), 0);

     memcache.clearAll();
     manager =
         new SessionManager(Collections.<SessionStore>singletonList(new DatastoreSessionStore()));
     HttpSession session2 = manager.getSession(session.getId());
     assertEquals(session.getId(), session2.getId());
     assertEquals("bar", session2.getAttribute("foo"));
   } finally {
     ApiProxy.setDelegate(original);
   }
 }
 
Example 3
Source File: VmRuntimeJettyKitchenSink2Test.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Test that abandoned transactions are aborted when the request completes.
 *
 * @throws Exception
 */
public void testAbandonTransaction() throws Exception {
  long transactionId = 123456789012345L;
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  // If the filter is installed we expect 2 requests.
  // First: a call to datastore_v3/BeginTransaction
  // Second: a call to datastore_v3/Rollback
  Transaction transactionResponse = new Transaction();
  transactionResponse.setHandle(transactionId);
  transactionResponse.setApp(PROJECT);
  fakeApiProxy.addApiResponse(transactionResponse); // Response to datastore_v3/BeginTransaction.
  fakeApiProxy.addApiResponse(new VoidProto()); // Response to datastore_v3/Rollback.

  String[] lines = fetchUrl(createUrl("/abandonTxn"));
  assertEquals(1, lines.length);
  assertEquals("" + transactionId, lines[0].trim());
  assertEquals(2, fakeApiProxy.requests.size());
  assertEquals("BeginTransaction", fakeApiProxy.requests.get(0).methodName);
  assertEquals("Rollback", fakeApiProxy.requests.get(1).methodName);
}
 
Example 4
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAuth_AdminRequiredNoUser() throws Exception {
  String loginUrl = "http://login-url?url=http://test-app.googleapp.com/user/test-auth";
  CreateLoginURLResponse loginUrlResponse = new CreateLoginURLResponse();
  loginUrlResponse.setLoginUrl(loginUrl);
  // Fake the expected call to "user/CreateLoginUrl".
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  fakeApiProxy.addApiResponse(loginUrlResponse);

  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/admin/test-auth").toString());
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(302, httpCode);
  Header redirUrl = get.getResponseHeader("Location");
  assertEquals(loginUrl, redirUrl.getValue());
}
 
Example 5
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAuth_UserRequiredNoUser() throws Exception {
  String loginUrl = "http://login-url?url=http://test-app.googleapp.com/user/test-auth";
  CreateLoginURLResponse loginUrlResponse = new CreateLoginURLResponse();
  loginUrlResponse.setLoginUrl(loginUrl);
  // Fake the expected call to "user/CreateLoginUrl".
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  fakeApiProxy.addApiResponse(loginUrlResponse);

  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/user/test-auth").toString());
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(302, httpCode);
  Header redirUrl = get.getResponseHeader("Location");
  assertEquals(loginUrl, redirUrl.getValue());
}
 
Example 6
Source File: VmRuntimeJettyKitchenSinkTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAsyncRequests_WaitUntilDone() throws Exception {
  long sleepTime = 2000;
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
  GetMethod get = new GetMethod(createUrl("/sleep").toString());
  get.addRequestHeader("Use-Async-Sleep-Api", "true");
  get.addRequestHeader("Sleep-Time", Long.toString(sleepTime));
  long startTime = System.currentTimeMillis();
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  Header vmApiWaitTime = get.getResponseHeader(VmRuntimeUtils.ASYNC_API_WAIT_HEADER);
  assertNotNull(vmApiWaitTime);
  assertTrue(Integer.parseInt(vmApiWaitTime.getValue()) > 0);
  long elapsed = System.currentTimeMillis() - startTime;
  assertTrue(elapsed >= sleepTime);
}
 
Example 7
Source File: TestSocketServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  ApiProxy.Delegate oldDelegate = setUpMockDelegate();

  response.setContentType("text/plain");
  try {
    testConnectWriteAndRead(response);
    testTimedConnect(response);
    testSocketOpt(response);
    testSetSocketImpl(response);
    testShutDownAndClose(response);
    testProxyConstructor(response);
    testSocketImplConstructor(response);
  } catch (AssertionFailedException e) {
    return;
    //return the error response
  } finally {
    ApiProxy.setDelegate(oldDelegate);
  }
  response.getWriter().print("Success!");
}
 
Example 8
Source File: TestDatagramSocketServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  ApiProxy.Delegate oldDelegate = setUpMockDelegate();

  response.setContentType("text/plain");
  try {
    testOpenAndClose(response);

    testConnectWriteAndRead(response);
    testSocketOpt(response);
    testSetDatagramSocketImpl(response);
    testSocketImplConstructor(response);
  } catch (AssertionFailedException e) {
    return;
    //return the error response
  } finally {
    ApiProxy.setDelegate(oldDelegate);
  }
  response.getWriter().print("Success!");
}
 
Example 9
Source File: VmRuntimeJettyKitchenSink2Test.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the count servlet was loaded, and that memcache calls are
 * forwarded through the VmApiProxyDelegate.
 *
 * @throws Exception
 */
public void testCountMemcache() throws Exception {
  // Replace the API proxy delegate so we can fake API responses.
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);

  for (int i = 1; i <= 5; i++) {
    MemcacheIncrementResponse responsePb = MemcacheIncrementResponse.newBuilder()
            .setIncrementStatus(IncrementStatusCode.OK).setNewValue(i).build();
    fakeApiProxy.addApiResponse(responsePb);
    String[] lines = fetchUrl(createUrl("/count?type=memcache"));
    assertEquals(1, lines.length);
    assertEquals("" + i, lines[0].trim());
  }
}
 
Example 10
Source File: VmRuntimeJettyKitchenSink2Test.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the deferredTask handler is installed.
 */
public void testDeferredTask() throws Exception {
  // Replace the API proxy delegate so we can fake API responses.
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);

  // Add a api response so the task queue api is happy.
  TaskQueueBulkAddResponse taskAddResponse = new TaskQueueBulkAddResponse();
  TaskResult taskResult = taskAddResponse.addTaskResult();
  taskResult.setResult(ErrorCode.OK.getValue());
  taskResult.setChosenTaskName("abc");
  fakeApiProxy.addApiResponse(taskAddResponse);

  // Issue a deferredTaskRequest with payload.
  String testData = "0987654321acbdefghijklmn";
  String[] lines = fetchUrl(createUrl("/testTaskQueue?deferredTask=1&deferredData=" + testData));
  TaskQueueBulkAddRequest request = new TaskQueueBulkAddRequest();
  request.parseFrom(fakeApiProxy.getLastRequest().requestData);
  assertEquals(1, request.addRequestSize());
  TaskQueueAddRequest addRequest = request.getAddRequest(0);
  assertEquals(TaskQueueAddRequest.RequestMethod.POST.getValue(), addRequest.getMethod());

  // Pull out the request and fire it at the app.
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  PostMethod post = new PostMethod(createUrl(addRequest.getUrl()).toString());
  post.getParams().setVersion(HttpVersion.HTTP_1_0);
  // Add the required Task queue header, plus any headers from the request.
  post.addRequestHeader("X-AppEngine-QueueName", "1");
  for (TaskQueueAddRequest.Header header : addRequest.headers()) {
    post.addRequestHeader(header.getKey(), header.getValue());
  }
  post.setRequestEntity(new ByteArrayRequestEntity(addRequest.getBodyAsBytes()));
  int httpCode = httpClient.executeMethod(post);
  assertEquals(HttpURLConnection.HTTP_OK, httpCode);

  // Verify that the task was handled and that the payload is correct.
  lines = fetchUrl(createUrl("/testTaskQueue?getLastPost=1"));
  assertEquals("deferredData:" + testData, lines[lines.length - 1]);
}
 
Example 11
Source File: TestInetAddressServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Set up a mock delegate to handle resolve calls.
 */
private ApiProxy.Delegate setUpMockDelegate() {
  ApiProxy.Delegate oldDelegate = ApiProxy.getDelegate();
  ApiProxy.setDelegate(new MockDelegate());
  return oldDelegate;
}
 
Example 12
Source File: UrlOverSocketsTestServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Set up a mock delegate to handle resolve calls.
 */
private ApiProxy.Delegate setUpMockDelegate() {
  ApiProxy.Delegate oldDelegate = ApiProxy.getDelegate();
  ApiProxy.setDelegate(new UrlMockDelegate());
  return oldDelegate;
}
 
Example 13
Source File: LogTest.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
public LogRecorder() {
  oldDelegate = ApiProxy.getDelegate();
  ApiProxy.setDelegate(this);
}
 
Example 14
Source File: TestSocketServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Set up a mock delegate to handle resolve calls.
 */
private ApiProxy.Delegate setUpMockDelegate() {
  ApiProxy.Delegate oldDelegate = ApiProxy.getDelegate();
  ApiProxy.setDelegate(new MockDelegate());
  return oldDelegate;
}
 
Example 15
Source File: VmRuntimeJettySessionTest.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Test that sessions are persisted in the datastore and memcache, and that
 * any data stored is available to subsequent requests.
 *
 * @throws Exception
 */
public void testSessions() throws Exception {
  URL url = createUrl("/count?type=session");

  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);

  // Add responses for session create.
  fakeApiProxy.addApiResponse(createDatastorePutResponse());
  fakeApiProxy.addApiResponse(
          MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build());
  // Add responses for session save.
  fakeApiProxy.addApiResponse(createDatastorePutResponse());
  fakeApiProxy.addApiResponse(
          MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build());

  // Make a call to count and save the session cookie.
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod firstGet = new GetMethod(url.toString());
  int returnCode = httpClient.executeMethod(firstGet);
  assertEquals(HttpServletResponse.SC_OK, returnCode);
  // Check the count, should be 1 for the first request.
  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());
  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();
  fakeApiProxy.addApiResponse(getResponse);

  // Add responses for session save.
  fakeApiProxy.addApiResponse(createDatastorePutResponse());
  fakeApiProxy.addApiResponse(
          MemcacheSetResponse.newBuilder().addSetStatus(SetStatusCode.STORED).build());

  // Make a call to count with the session cookie.
  GetMethod secondGet = new GetMethod(url.toString());
  returnCode = httpClient.executeMethod(secondGet);
  assertEquals(HttpServletResponse.SC_OK, returnCode);
  // Check the count, should be "2" for the second request.
  assertEquals("2", secondGet.getResponseBodyAsString().trim());
}
 
Example 16
Source File: TestDatagramSocketServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
/**
 * Set up a mock delegate to socket resolve calls.
 */
private ApiProxy.Delegate setUpMockDelegate() {
  ApiProxy.Delegate oldDelegate = ApiProxy.getDelegate();
  ApiProxy.setDelegate(new MockDelegate());
  return oldDelegate;
}
 
Example 17
Source File: LogTest.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
public void reset() {
  ApiProxy.setDelegate(oldDelegate);
}