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

The following examples show how to use com.google.appengine.api.NamespaceManager#get() . 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: SecurityChecker.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates {@link Query} from the specified kindName. If the kindName has
 * _private suffix, the key will be created under a namespace for the
 * specified {@link User}.
 *
 * @param kindName
 *          Name of kind
 * @param user
 *          {@link User} of the requestor
 * @return {@link Query}
 */
public Query createKindQueryWithNamespace(String kindName, User user) {

  // save the original namespace
  String origNamespace = NamespaceManager.get();

  // set namespace based on the kind suffix
  if (kindName.startsWith(KIND_PREFIX_PRIVATE)) {
    String userId = getUserId(user);
    NamespaceManager.set(userId);
  } else {
    NamespaceManager.set(NAMESPACE_DEFAULT);
  }

  // create a key
  Query q = new Query(kindName);

  // restore the original namespace
  NamespaceManager.set(origNamespace);
  return q;
}
 
Example 2
Source File: SecurityChecker.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Key} from the specified kindName and CloudEntity id. If
 * the kindName has _private suffix, the key will be created under a namespace
 * for the specified {@link User}.
 *
 * @param kindName
 *          Name of kind
 * @param id
 *          CloudEntity id
 * @param user
 *          {@link User} of the requestor
 * @return {@link Key}
 */
public Key createKeyWithNamespace(String kindName, String id, User user) {

  // save the original namespace
  String origNamespace = NamespaceManager.get();

  // set namespace based on the kind suffix
  if (kindName.startsWith(SecurityChecker.KIND_PREFIX_PRIVATE)) {
    String userId = getUserId(user);
    NamespaceManager.set(userId);
  } else {
    NamespaceManager.set(SecurityChecker.NAMESPACE_DEFAULT);
  }

  // create a key
  Key k = KeyFactory.createKey(kindName, id);

  // restore the original namespace
  NamespaceManager.set(origNamespace);
  return k;
}
 
Example 3
Source File: UpdateCountsServlet.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 java.io.IOException {

  // Update the count for the current namespace.
  updateCount("request");

  // Update the count for the "-global-" namespace.
  String namespace = NamespaceManager.get();
  try {
    // "-global-" is namespace reserved by the application.
    NamespaceManager.set("-global-");
    updateCount("request");
  } finally {
    NamespaceManager.set(namespace);
  }
  resp.setContentType("text/plain");
  resp.getWriter().println("Counts are now updated.");
}
 
Example 4
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 5
Source File: DatastoreSessionStore.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, SessionData> getAllSessions() {
  final String originalNamespace = NamespaceManager.get();
  NamespaceManager.set("");
  try {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery pq = ds.prepare(new Query(SESSION_ENTITY_TYPE));
    Map<String, SessionData> sessions = new HashMap<>();
    for (Entity entity : pq.asIterable()) {
      sessions.put(entity.getKey().getName(), createSessionFromEntity(entity));
    }
    return sessions;
  } finally {
    NamespaceManager.set(originalNamespace);
  }
}
 
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: SecurityChecker.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link com.google.appengine.api.datastore.Key} from the specified kindName and CloudEntity id. If
 * the kindName has _private suffix, the key will be created under a namespace
 * for the specified {@link com.google.appengine.api.users.User}.
 *
 * @param kindName
 *          Name of kind
 * @param id
 *          CloudEntity id
 * @param user
 *          {@link com.google.appengine.api.users.User} of the requestor
 * @return {@link com.google.appengine.api.datastore.Key}
 */
public Key createKeyWithNamespace(String kindName, String id, User user) {

  // save the original namespace
  String origNamespace = NamespaceManager.get();

  // set namespace based on the kind suffix
  if (kindName.startsWith(SecurityChecker.KIND_PREFIX_PRIVATE)) {
    String userId = getUserId(user);
    NamespaceManager.set(userId);
  } else {
    NamespaceManager.set(SecurityChecker.NAMESPACE_DEFAULT);
  }

  // create a key
  Key k = KeyFactory.createKey(kindName, id);

  // restore the original namespace
  NamespaceManager.set(origNamespace);
  return k;
}
 
Example 8
Source File: SecurityChecker.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Creates {@link com.google.appengine.api.datastore.Query} from the specified kindName. If the kindName has
 * _private suffix, the key will be created under a namespace for the
 * specified {@link com.google.appengine.api.users.User}.
 *
 * @param kindName
 *          Name of kind
 * @param user
 *          {@link com.google.appengine.api.users.User} of the requestor
 * @return {@link com.google.appengine.api.datastore.Query}
 */
public Query createKindQueryWithNamespace(String kindName, User user) {

  // save the original namespace
  String origNamespace = NamespaceManager.get();

  // set namespace based on the kind suffix
  if (kindName.startsWith(KIND_PREFIX_PRIVATE)) {
    String userId = getUserId(user);
    NamespaceManager.set(userId);
  } else {
    NamespaceManager.set(NAMESPACE_DEFAULT);
  }

  // create a key
  Query q = new Query(kindName);

  // restore the original namespace
  NamespaceManager.set(origNamespace);
  return q;
}
 
Example 9
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 10
Source File: NamespaceFilter.java    From appengine-gwtguestbook-namespaces-java with Apache License 2.0 5 votes vote down vote up
@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.
  if (NamespaceManager.get() == null) {
    switch (strategy) {
      case SERVER_NAME : {
        NamespaceManager.set(request.getServerName());
        break;
      }
      
      case GOOGLE_APPS_DOMAIN : {
        NamespaceManager.set(NamespaceManager.getGoogleAppsNamespace());
        break;
      }

      case EMPTY : {
        NamespaceManager.set("");
      }
    }
  }
  
  // chain into the next request
  chain.doFilter(request, response) ;
}
 
Example 11
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
private Query makeQuery(String bucket) {
  String origNamespace = NamespaceManager.get();
  try {
    NamespaceManager.set("");
    return new Query(ENTITY_KIND_PREFIX + bucket);
  } finally {
    NamespaceManager.set(origNamespace);
  }
}
 
Example 12
Source File: LocalRawGcsService.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
private Key makeKey(String bucket, String object) {
  String origNamespace = NamespaceManager.get();
  try {
    NamespaceManager.set("");
    return KeyFactory.createKey(ENTITY_KIND_PREFIX + bucket, object);
  } finally {
    NamespaceManager.set(origNamespace);
  }
}
 
Example 13
Source File: DatastoreSessionStore.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Return an {@link Entity} for the given key and data in the empty
 * namespace.
 */
static Entity createEntityForSession(String key, SessionData data) {
  String originalNamespace = NamespaceManager.get();
  try {
    NamespaceManager.set("");
    Entity entity = new Entity(SESSION_ENTITY_TYPE, key);
    entity.setProperty(EXPIRES_PROP, data.getExpirationTime());
    entity.setProperty(VALUES_PROP, new Blob(serialize(data.getValueMap())));
    return entity;
  } finally {
    NamespaceManager.set(originalNamespace);
  }
}
 
Example 14
Source File: DatastoreSessionStore.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link Key} for the given session "key" string
 * ({@link SessionManager#SESSION_PREFIX} + sessionId) in the empty namespace.
 */
static Key createKeyForSession(String key) {
  String originalNamespace = NamespaceManager.get();
  try {
    NamespaceManager.set("");
    return KeyFactory.createKey(SESSION_ENTITY_TYPE, key);
  } finally {
    NamespaceManager.set(originalNamespace);
  }
}
 
Example 15
Source File: NamespaceFilter.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws IOException, ServletException {
  // Make sure set() is only called if the current namespace is not already set.
  if (NamespaceManager.get() == null) {
    // If your app is hosted on appspot, this will be empty. Otherwise it will be the domain
    // the app is hosted on.
    NamespaceManager.set(NamespaceManager.getGoogleAppsNamespace());
  }
  chain.doFilter(req, res); // Pass request back down the filter chain
}
 
Example 16
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 17
Source File: DatastoreMultitenancyTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    super.setUp();
    originalNamespace = NamespaceManager.get();
}
 
Example 18
Source File: ChatSocketServer.java    From appengine-websocketchat-java with Apache License 2.0 4 votes vote down vote up
private ChatServerBridge() {
  namespace = NamespaceManager.get();
  chatRoomParticipantsKeyList = new CopyOnWriteArrayList<>();
}
 
Example 19
Source File: AppengineNamespaceDriver.java    From yawp with MIT License 4 votes vote down vote up
@Override
public String get() {
    return NamespaceManager.get();
}
 
Example 20
Source File: MultitenancyServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String namespace;

  PrintWriter out = resp.getWriter();
  out.println("Code Snippets -- not yet fully runnable as an app");

  // [START temp_namespace]
  // Set the namepace temporarily to "abc"
  String oldNamespace = NamespaceManager.get();
  NamespaceManager.set("abc");
  try {
    //      ... perform operation using current namespace ...
  } finally {
    NamespaceManager.set(oldNamespace);
  }
  // [END temp_namespace]

  // [START per_user_namespace]
  if (com.google.appengine.api.NamespaceManager.get() == null) {
    // Assuming there is a logged in user.
    namespace = UserServiceFactory.getUserService().getCurrentUser().getUserId();
    NamespaceManager.set(namespace);
  }
  // [END per_user_namespace]
  String value = "something here";

  // [START ns_memcache]
  // Create a MemcacheService that uses the current namespace by
  // calling NamespaceManager.get() for every access.
  MemcacheService current = MemcacheServiceFactory.getMemcacheService();

  // stores value in namespace "abc"
  oldNamespace = NamespaceManager.get();
  NamespaceManager.set("abc");
  try {
    current.put("key", value); // stores value in namespace “abc”
  } finally {
    NamespaceManager.set(oldNamespace);
  }
  // [END ns_memcache]

  // [START specific_memcache]
  // Create a MemcacheService that uses the namespace "abc".
  MemcacheService explicit = MemcacheServiceFactory.getMemcacheService("abc");
  explicit.put("key", value); // stores value in namespace "abc"
  // [END specific_memcache]

  //[START searchns]
  // Set the current namespace to "aSpace"
  NamespaceManager.set("aSpace");
  // Create a SearchService with the namespace "aSpace"
  SearchService searchService = SearchServiceFactory.getSearchService();
  // Create an IndexSpec
  IndexSpec indexSpec = IndexSpec.newBuilder().setName("myIndex").build();
  // Create an Index with the namespace "aSpace"
  Index index = searchService.getIndex(indexSpec);
  // [END searchns]

  // [START searchns_2]
  // Create a SearchServiceConfig, specifying the namespace "anotherSpace"
  SearchServiceConfig config =
      SearchServiceConfig.newBuilder().setNamespace("anotherSpace").build();
  // Create a SearchService with the namespace "anotherSpace"
  searchService = SearchServiceFactory.getSearchService(config);
  // Create an IndexSpec
  indexSpec = IndexSpec.newBuilder().setName("myindex").build();
  // Create an Index with the namespace "anotherSpace"
  index = searchService.getIndex(indexSpec);
  // [END searchns_2]

}