1.9.30 sync.
[gae.git] / java / src / main / com / google / appengine / api / datastore / KeyTranslator.java
blob6b8ea465269e22f66e2d59a7d2b1cdc1ca457540
1 // Copyright 2007 Google Inc. All rights reserved.
3 package com.google.appengine.api.datastore;
5 import com.google.storage.onestore.v3.OnestoreEntity.Path;
6 import com.google.storage.onestore.v3.OnestoreEntity.Path.Element;
7 import com.google.storage.onestore.v3.OnestoreEntity.Reference;
9 import java.util.Collections;
10 import java.util.List;
12 /**
13 * {@code KeyTranslator} contains the logic to translate a {@link Key}
14 * into the protocol buffers that are used to pass it to the
15 * implementation of the API.
18 class KeyTranslator {
20 public static Key createFromPb(Reference reference) {
21 Key parentKey = null;
22 Path path = reference.getPath();
23 List<Element> elements = path.elements();
24 if (elements.isEmpty()) {
25 throw new IllegalArgumentException("Invalid Key PB: no elements.");
28 AppIdNamespace appIdNamespace = new AppIdNamespace(reference.getApp(),
29 reference.hasNameSpace() ? reference.getNameSpace() : "");
31 for (Element e : elements) {
32 String kind = e.getType();
33 if (e.hasName() && e.hasId()) {
34 throw new IllegalArgumentException("Invalid Key PB: both id and name are set.");
35 } else if (e.hasName()) {
36 parentKey = new Key(kind, parentKey, Key.NOT_ASSIGNED, e.getName(), appIdNamespace);
37 } else if (e.hasId()) {
38 parentKey = new Key(kind, parentKey, e.getId(), null, appIdNamespace);
39 } else {
40 parentKey = new Key(kind, parentKey, Key.NOT_ASSIGNED, null, appIdNamespace);
44 return parentKey;
47 public static Reference convertToPb(Key key) {
48 Reference reference = new Reference();
50 reference.setApp(key.getAppId());
51 String nameSpace = key.getNamespace();
52 if (!nameSpace.isEmpty()) {
53 reference.setNameSpace(nameSpace);
56 Path path = reference.getMutablePath();
57 while (key != null) {
58 Element pathElement = new Element();
59 pathElement.setType(key.getKind());
60 if (key.getName() != null) {
61 pathElement.setName(key.getName());
62 } else if (key.getId() != Key.NOT_ASSIGNED) {
63 pathElement.setId(key.getId());
65 path.addElement(pathElement);
66 key = key.getParent();
68 Collections.reverse(path.mutableElements());
69 return reference;
72 public static void updateKey(Reference reference, Key key) {
74 if (key.getName() == null) {
75 Path path = reference.getPath();
76 key.setId(path.getElement(path.elementSize() - 1).getId());
80 KeyTranslator() { }