2

I need to identify a String if the character on it includes only numbers, with alphabet (a custom string, name, code, or whatever) or its a GAE Key.

Here is my code:

    try {
        Class clazz = Class.forName(typeName);
        Object one = null;
        if(key.matches("[0-9]+")){ // Long
            one = store.get(clazz, Long.valueOf(key));
        } else if(key.matches("^[0-9A-Za-z._-]{1,500}$")) { // GAE datastore key
            one = store.get(clazz, KeyFactory.stringToKey(key));
        } else {
            one = store.get(clazz, String.valueOf(key));
        }
        jsonString =new Gson().toJson(one);
    } catch (Exception e){
        setStatus(Status.SERVER_ERROR_INTERNAL);
        e.printStackTrace();
    }

The problem here is that the second statement in the if-else catches even String "aaa" I need to have some way of differentiating a GAE datastore key from a regular strings that is not really a GAE key format.

quarks
  • 29,080
  • 65
  • 239
  • 450
  • 2
    What is the difference between a GAE datastore key and a regular `String`? What is the GAE key format? – Florent Bayle Aug 29 '14 at 09:21
  • http://stackoverflow.com/questions/15864116/regular-expression-for-google-app-engine-entity-keys – quarks Aug 29 '14 at 09:37
  • So, Datastore strings are as a REGEX identical to the other strings. I'd sugggest two work-arounds, that require you to add code before calling this method: (1) Add a prefix to the other strings to use as the token to identify from Datastore strings; (2) to use the information of which was originally a Datastore key and was not and include it along the String. This is OOP not Assembler language after all. – user3852065 Aug 29 '14 at 14:00
  • No, Datastore Key is encoded into Base64-encoded web-safe string. One can use a regex to test if string contains a Base64 encoded data. – Peter Knego Aug 31 '14 at 19:40

1 Answers1

1

The situation you are referring to (second if) are GAE convenience functions for web-safe encoding of whole Keys (not only key IDs): the KeyFactory.stringToKey(..) and KeyFactory.keyToString().

As you can see from the source, encoding used here is web-safe Base64. This is the alphabet used.

You can match it with this regex: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$.

Community
  • 1
  • 1
Peter Knego
  • 78,855
  • 10
  • 118
  • 147
  • The key passed here is actually an earlier output of KeyFactor.keyToString passed to the client by a GET api, now when client wants to get entity, it needs to pass back the String key it got for the GET (or list method). – quarks Aug 31 '14 at 04:49
  • I know. This is exactly what I'm saying: the Key is encoded into web-safe string via Base64 encoding. Use above regex to test of if this is the encoded Key. – Peter Knego Aug 31 '14 at 19:37