Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  // Copyright 2008 Google Inc.
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  // Unless required by applicable law or agreed to in writing, software
 // distributed under the License is distributed on an "AS IS" BASIS,
 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 // See the License for the specific language governing permissions and
 // limitations under the License.

Common utility functions for Key implementors.
 public class KeyUtil {
   private static Encoder ENCODER_IMPL;

Set the encoder implementation to a valid implementation.

Server-side code needs to set the encoder to a instance prior to invoking any methods in this class. Typically this is done by the implementation's static initializer.

   public static void setEncoderImpl(final Encoder e) {
      = e;

Determine if two keys are equal, supporting null references.

<T> type of the key entity.
a first key to test; may be null.
b second key to test; may be null.
true if both a and b are null, or if both are not-null and a.equals(b) is true. Otherwise false.
   public static <T extends Key<?>> boolean eq(final T afinal T b) {
     if (a == b) {
       return true;
     if (a == null || b == null) {
       return false;
     return a.equals(b);

Encode a string to be safe for use within a URL like string.

The returned encoded string has URL component characters escaped with hex escapes (e.g. ' ' is '+' and '%' is '%25'). The special character '/' is left literal. The comma character (',') is always encoded, permitting multiple encoded string values to be joined together safely.

e the string to encode, must not be null.
the encoded string.
   public static String encode(final String e) {
     return .encode(e);

Decode a string previously encoded by encode(java.lang.String).

e the string to decode, must not be null.
the decoded string.
   public static String decode(final String e) {
     return .decode(e);

Split a string along the last comma and parse into the parent.

parent parent key; parent.fromString(in[0..comma]).
in the input string.
text (if any) after the last comma in the input.
   public static String parseFromString(final Key<?> parentfinal String in) {
     final int comma = in.lastIndexOf(',');
     if (comma < 0 && parent == null) {
       return decode(in);
     if (comma < 0 && parent != null) {
       throw new IllegalArgumentException("Not enough components: " + in);
     assert(parent != null);
     parent.fromString(in.substring(0, comma));
     return decode(in.substring(comma + 1));
   public static abstract class Encoder {
     public abstract String encode(String e);
    public abstract String decode(String e);
  private KeyUtil() {
New to GrepCode? Check out our FAQ X