Java Code Examples for com.google.appengine.api.NamespaceManager#set()

The following examples show how to use com.google.appengine.api.NamespaceManager#set() . 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: SchemaTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testKindMetadata() {
    // check non empty namespace only
    for (int i = 1; i < namespaceDat.length; i++) {
        NamespaceManager.set(namespaceDat[i]);
        Query q = new Query("__kind__").addSort(Entity.KEY_RESERVED_PROPERTY);
        int count = 0;
        for (Entity e : service.prepare(q).asIterable()) {
            // do not count those stats entities for namespace.
            if (!e.getKey().getName().startsWith("__Stat_Ns_")) {
                count++;
            }
        }
        // For each namespace, only 3 user defined kinds.
        assertEquals(3, count);
        // check a specified namespace
        Key key1 = Entities.createKindKey("testing");
        q.setFilter(new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, FilterOperator.EQUAL, key1));
        assertEquals(1, service.prepare(q).countEntities(fo));
        Entity ke = service.prepare(q).asSingleEntity();
        assertEquals("testing", ke.getKey().getName());
        assertEquals(namespaceDat[i], ke.getKey().getNamespace());
        assertEquals(namespaceDat[i], ke.getNamespace());
    }
}
 
Example 2
Source File: NamespaceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Before
public void createData() throws InterruptedException {
    List<Entity> eList = new ArrayList<Entity>();
    for (int i = 0; i < namespaceDat.length; i++) {
        NamespaceManager.set(namespaceDat[i]);
        Query q = new Query(kindName);
        if (service.prepare(q).countEntities(FetchOptions.Builder.withDefaults()) == 0) {
            for (int c = 0; c < count; c++) {
                Entity newRec = new Entity(kindName);
                newRec.setProperty("jobType", stringDat[i] + c);
                eList.add(newRec);
            }
        }
    }
    if (eList.size() > 0) {
        service.put(eList);
        sync(waitTime);
    }
}
 
Example 3
Source File: SomeRequestServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

  // Increment the count for the current namespace asynchronously.
  QueueFactory.getDefaultQueue()
      .add(TaskOptions.Builder.withUrl("/_ah/update_count").param("countName", "SomeRequest"));
  // Increment the global count and set the
  // namespace locally.  The namespace is
  // transferred to the invoked request and
  // executed asynchronously.
  String namespace = NamespaceManager.get();
  try {
    NamespaceManager.set("-global-");
    QueueFactory.getDefaultQueue()
        .add(TaskOptions.Builder.withUrl("/_ah/update_count").param("countName", "SomeRequest"));
  } finally {
    NamespaceManager.set(namespace);
  }
  resp.setContentType("text/plain");
  resp.getWriter().println("Counts are being updated.");
}
 
Example 4
Source File: DatastoreMultitenancyTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testQueriesByAncestorInOtherNamespaceThrowsIllegalArgumentException() {
    deleteNsKinds("one", "foo");
    deleteNsKinds("two", "foo");
    sync();

    NamespaceManager.set("one");
    Entity fooOne = new Entity("foo");
    service.put(fooOne);

    NamespaceManager.set("two");
    Entity fooTwo = new Entity("foo");
    service.put(fooTwo);
    sync();

    // java.lang.IllegalArgumentException: Namespace of ancestor key and query must match.
    service.prepare(new Query("foo").setAncestor(fooOne.getKey())).asList(withDefaults());
}
 
Example 5
Source File: DatastoreMultitenancyTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryConsidersCurrentNamespaceWhenCreatedNotWhenPreparedOrExecuted() {
    deleteNsKinds("one", "foo");
    deleteNsKinds("two", "foo");
    sync();

    NamespaceManager.set("one");
    Entity fooOne = new Entity("foo");
    service.put(fooOne);

    NamespaceManager.set("two");
    Entity fooTwo = new Entity("foo");
    service.put(fooTwo);
    sync();

    Query query = new Query("foo").setAncestor(fooTwo.getKey()); // query created in namespace "two"

    NamespaceManager.set("one");
    PreparedQuery preparedQuery = service.prepare(query);
    assertEquals(fooTwo, preparedQuery.asSingleEntity());

    service.delete(fooOne.getKey());
    service.delete(fooTwo.getKey());
}
 
Example 6
Source File: NamespaceExtensionContainer.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
private void runWithinNamespaces(EventContext<Test> context, String[] namespaces) {
    final List<FailedNamespaceException> exceptions = new ArrayList<>();
    final String original = NamespaceManager.get();
    try {
        for (String namespace : namespaces) {
            try {
                NamespaceManager.set(namespace);
                context.proceed();
            } catch (Exception e) {
                exceptions.add(new FailedNamespaceException(e, namespace));
            }
        }
    } finally {
        NamespaceManager.set(original);
    }
    if (exceptions.size() > 1) {
        throw new MultipleExceptions(exceptions);
    } else if (exceptions.size() == 1) {
        throw exceptions.get(0);
    }
}
 
Example 7
Source File: TaskQueueTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserNameSpace() {
    String testMethodTag = "testUserNameSpace";
    NamespaceManager.set("junittest");

    TaskOptions taskOptions = TaskOptions.Builder
        .withMethod(TaskOptions.Method.POST)
        .param(TEST_RUN_ID, testRunId)
        .param(TEST_METHOD_TAG, testMethodTag)
        .url("/queuetask/addentity");
    // task name explicitly not specified.

    QueueFactory.getQueue(E2E_TESTING).add(taskOptions);
    Entity entity = dsUtil.waitForTaskThenFetchEntity(waitInterval, retryMax, testMethodTag);
    Map<String, String> expectedParams = dsUtil.createParamMap(testMethodTag);
    dsUtil.assertTaskParamsMatchEntityProperties(expectedParams, entity);
}
 
Example 8
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
private Key makeBlobstoreKey(GcsFilename filename) {
  String origNamespace = NamespaceManager.get();
  try {
    NamespaceManager.set("");
    return KeyFactory.createKey(
        null, BLOBSTORE_META_KIND, getBlobKeyForFilename(filename).getKeyString());
  } finally {
    NamespaceManager.set(origNamespace);
  }
}
 
Example 9
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamespaceWithBug() throws InterruptedException, ParseException {
    String ns = "ns-indextest";
    String indexName = "ns-index";
    int docCount = 5;
    NamespaceManager.set(ns);
    SearchService searchService2 = SearchServiceFactory.getSearchService();
    Index index = searchService2.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());
    delDocs(index);
    addDocs(index, docCount);

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
        .setIndexNamePrefix(indexName)
        .setOffset(0)
        .setNamespace(ns)
        .setLimit(10)
        .build();
    assertEquals(ns, request.getNamespace());
    GetResponse<Index> response = searchService2.getIndexes(request);
    List<Index> listIndexes = response.getResults();
    for (Index oneIndex : listIndexes) {
        assertEquals(ns, listIndexes.get(0).getNamespace());
        assertEquals(indexName, listIndexes.get(0).getName());
        verifyDocCount(oneIndex, docCount);
    }
    assertEquals(ns, searchService2.getNamespace());
    NamespaceManager.set("");
}
 
Example 10
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Before
public void createData() throws InterruptedException {
    List<Entity> eList = new ArrayList<Entity>();
    for (int i = 0; i < namespaceDat.length; i++) {
        NamespaceManager.set(namespaceDat[i]);
        for (int k = 0; k < kindDat.length; k++) {
            Query q = new Query(kindDat[k]);
            if (service.prepare(q).countEntities(fo) == 0) {
                for (int c = 0; c < count; c++) {
                    Entity newRec = new Entity(kindDat[k]);
                    newRec.setProperty("name", kindDat[k] + c);
                    newRec.setProperty("timestamp", new Date());
                    newRec.setProperty("shortBlobData", new ShortBlob("shortBlobData".getBytes()));
                    newRec.setProperty("intData", 12345);
                    newRec.setProperty("textData", new Text("textData"));
                    newRec.setProperty("floatData", new Double(12345.12345));
                    newRec.setProperty("booleanData", true);
                    newRec.setProperty("urlData", new Link("http://www.google.com"));
                    newRec.setProperty("emailData", new Email("[email protected]"));
                    newRec.setProperty("phoneData", new PhoneNumber("408-123-4567"));
                    newRec.setProperty("adressData", new PostalAddress("123 st. CA 12345"));
                    newRec.setProperty("ratingData", new Rating(55));
                    newRec.setProperty("geoptData", new GeoPt((float) 12.12, (float) 98.98));
                    newRec.setProperty("categoryData", new Category("abc"));
                    eList.add(newRec);
                }
            }
        }
    }
    if (eList.size() > 0) {
        service.put(eList);
        sync(waitTime);
    }
}
 
Example 11
Source File: IndexTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
public void testNamespace() throws InterruptedException, ParseException {
    String ns = "ns-indextest";
    String indexName = "ns-index";
    int docCount = 5;
    NamespaceManager.set(ns);
    Index index = searchService.getIndex(IndexSpec.newBuilder()
            .setName(indexName)
            .build());
    delDocs(index);
    addDocs(index, docCount);

    GetIndexesRequest request = GetIndexesRequest.newBuilder()
        .setIndexNamePrefix(indexName)
        .setOffset(0)
        .setNamespace(ns)
        .setLimit(10)
        .build();
    assertEquals(ns, request.getNamespace());
    GetResponse<Index> response = searchService.getIndexes(request);
    List<Index> listIndexes = response.getResults();
    for (Index oneIndex : listIndexes) {
        assertEquals(ns, listIndexes.get(0).getNamespace());
        assertEquals(indexName, listIndexes.get(0).getName());
        verifyDocCount(oneIndex, docCount);
    }
    assertEquals(ns, searchService.getNamespace());
    NamespaceManager.set("");
}
 
Example 12
Source File: SessionManagerTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
private AppEngineSession createSession() {
  NamespaceManager.set(startNamespace());
  SessionManager localManager =
      new SessionManager(Arrays.asList(new DatastoreSessionStore(), new MemcacheSessionStore()));
  NamespaceManager.set(testNamespace());
  HttpServletRequest request = makeMockRequest(true);

return localManager.newSession(request);
}
 
Example 13
Source File: NamespaceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSort() {
    for (String ns : namespaceDat) {
        NamespaceManager.set(ns);
        doSort(kindName, "jobType", 3, Query.SortDirection.ASCENDING);
        doSort(kindName, "jobType", 3, Query.SortDirection.DESCENDING);
    }
}
 
Example 14
Source File: NamespaceFilter.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}. Each request this method set the namespace. (Namespace is by version)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {

  // If the NamespaceManager state is already set up from the context of the task creator the
  // current namespace will not be null. It's important to check that the current namespace
  // has not been set before setting it for this request.
  String applicationVersion = TechGalleryUtil.getApplicationVersion();

  if (NamespaceManager.get() == null && !applicationVersion.contains("$")) {
    logger.info("SystemProperty.applicationVersion.get():" + applicationVersion);
    String[] version = applicationVersion.split("\\.");
    if (version.length > 0 && version[0].contains("-")) {
      String namespace = version[0].split("-")[0];
      NamespaceManager.set(namespace);
    } else if (version.length > 0) {
      NamespaceManager.set(version[0]);
    } else {
      NamespaceManager.set(applicationVersion);
    }

    logger.info("set namespace:" + NamespaceManager.get());
  }
  // chain into the next request
  chain.doFilter(request, response);
}
 
Example 15
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntityGroupMetadata() throws EntityNotFoundException {
    if (service.getDatastoreAttributes().getDatastoreType() == DatastoreAttributes.DatastoreType.HIGH_REPLICATION) {
        NamespaceManager.set(namespaceDat[2]);
        Entity entity1 = new Entity(kindDat[2]);
        entity1.setProperty("name", "entity1");
        entity1.setProperty("timestamp", new Date());
        Key k1 = service.put(entity1);
        Key entityGroupKey = Entities.createEntityGroupKey(k1);
        long version1 = Entities.getVersionProperty(service.get(entityGroupKey));

        Entity entity2 = new Entity(kindDat[2]);
        entity2.setProperty("name", "entity2");
        entity2.setProperty("timestamp", new Date());
        service.put(entity2);
        // Get entity1's version again.  There should be no change.
        long version2 = Entities.getVersionProperty(service.get(entityGroupKey));
        assertEquals(version1, version2);

        Entity entity3 = new Entity(kindDat[2], k1);
        entity3.setProperty("name", "entity3");
        entity3.setProperty("timestamp", new Date());
        service.put(entity3);
        // Get entity1's version again.  There should be change since it is used as parent.
        long version3 = Entities.getVersionProperty(service.get(entityGroupKey));
        assertTrue(version3 > version1);
        // clean test data
        service.delete(entity3.getKey(), entity2.getKey(), k1);
    }
}
 
Example 16
Source File: TenantManager.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void addTenant(String tenantId, String name, String description, RentService rentService) {
		/*
		 * Tenant & Rent Service
		 */
		_tenantMpr.addTenant(tenantId, name, description, rentService);

		/*
		 * Account
		 */
		
		// fix later
		String adminAccountName = rentService.getAdminName();// + "@" + tenantId + ".com";
//		IAccountManager am = AccountFactory.getManager();
//		ExtensionFieldMapper extensionFieldMapper = new ExtensionFieldMapper();
		
		NamespaceManager.set(tenantId);
//		Account account = AccountFactory.createAccount(adminAccountName, adminAccountName, adminAccountName);
		
		Account account = new Account(adminAccountName, adminAccountName, ezScrumUtil.getMd5(adminAccountName), false);
		
		account.addPermission(new Permission(ScrumEnum.ADMINISTRATOR_PERMISSION, "system","admin"));
		account.addPermission(new Permission(ScrumEnum.CREATEPROJECT_PERMISSION, "system","createProject"));
		account.setEnable("true");
		account.setEmail("[email protected]");
		
		_tenantMpr.addTenantAdmin(account);
				
//		am.addAccount(account);
		
//		extensionFieldMapper.newExtensionField(Configuration.TARGET_STRING[Configuration.TARGET_PROJECT]);
//		
//		extensionFieldMapper.newExtensionField(Configuration.TARGET_STRING[Configuration.TARGET_ACCOUNT]);
//		
//		extensionFieldMapper.newExtensionField(Configuration.TARGET_STRING[Configuration.TARGET_STORY]);
//		
//		extensionFieldMapper.newExtensionField(Configuration.TARGET_STRING[Configuration.TARGET_TASK]);
		
		NamespaceManager.set("");
	}
 
Example 17
Source File: MetadataNamespacesTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void printAllNamespaces_printsNamespaces() throws Exception {
  datastore.put(new Entity("Simple"));
  NamespaceManager.set("another-namespace");
  datastore.put(new Entity("Simple"));

  printAllNamespaces(datastore, new PrintWriter(responseWriter));

  String response = responseWriter.toString();
  assertThat(response).contains("<default>");
  assertThat(response).contains("another-namespace");
}
 
Example 18
Source File: DatastoreMultitenancyTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private void deleteNsKinds(String namespace, String kind) {
    String originalNs = NamespaceManager.get();
    NamespaceManager.set(namespace);

    List<Entity> entities = service.prepare(new Query(kind)).asList(withDefaults());
    deleteEntityList(entities);
    NamespaceManager.set(originalNs);
}
 
Example 19
Source File: NamespaceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntity() {
    for (String ns : namespaceDat) {
        NamespaceManager.set(ns);
        Query query = new Query(kindName);
        Entity readRec = service.prepare(query).asIterator().next();
        assertEquals(ns, readRec.getNamespace());
        String appId = readRec.getAppId();
        appId = appId.substring(appId.indexOf("~") + 1);
        assertEquals(SystemProperty.applicationId.get(), appId);
        assertTrue(readRec.hasProperty("jobType"));
    }
}
 
Example 20
Source File: TaskQueueServlet.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
private void addTask(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String queue = req.getParameter("queue");
  Queue q;
  if (queue == null) {
    q = QueueFactory.getDefaultQueue();
  } else {
    q = QueueFactory.getQueue(queue);
  }
  TaskOptions.Method method = TaskOptions.Method.valueOf(req.getParameter("httpmethod"));
  String url = req.getParameter("taskUrl");
  if (url == null) {
    url = req.getServletPath();
  }
  TaskOptions opts =
      TaskOptions.Builder.withUrl(url).header("myheader", "blarg29").method(method);

  if (method == TaskOptions.Method.POST || method == TaskOptions.Method.PUT) {
    opts.payload("this=that");
  } else {
    opts.param("myparam", "yam28");
  }
  String execTimeMs = req.getParameter("execTimeMs");
  if (execTimeMs != null) {
    opts.etaMillis(Long.valueOf(execTimeMs));
  }
  String requestNamespace = req.getParameter("requestNamespace");
  if (requestNamespace != null) {
    /* We could override the current environment and set the request namespace
     * but that's a little overkill and already tested in
     * com.google.appengine.api.taskqueue.TaskQueueTest .
     */
    opts.header(DEFAULT_NAMESPACE_HEADER, requestNamespace);
  }
  String currentNamespace = req.getParameter("currentNamespace");
  if (currentNamespace != null) {
    /* We could also do this:
     * opts.header(CURRENT_NAMESPACE_HEADER, currentNamespace);
     */
    NamespaceManager.set(currentNamespace);
  }
  latch = new CountDownLatch(1);
  TaskHandle handle = q.add(opts);
  resp.getWriter().print(handle.getQueueName());
}