1 // Copyright 2010 Google Inc. All Rights Reserved.
3 package com
.google
.appengine
.api
.search
;
5 import com
.google
.apphosting
.api
.AppEngineInternal
;
7 import java
.util
.Iterator
;
8 import java
.util
.LinkedList
;
11 * A utility class that does various checks on search and indexing parameters.
15 public final class Util
{
17 private static final long MILLISECONDS_IN_DAY
= 1000L * 60 * 60 * 24;
23 * A helper method for testing two objects are equal.
25 * @return whether the two objects a and b are equal
27 public static boolean equalObjects(Object a
, Object b
) {
28 return a
== b
|| (a
!= null && a
.equals(b
));
32 * A helper method for overriding null values with a default value.
34 * @param value the value of some field
35 * @param defaultValue the default value for the field
36 * @return value if it is not null, otherwise the defaultValue
38 public static <T
> T
defaultIfNull(T value
, T defaultValue
) {
39 return value
== null ? defaultValue
: value
;
43 * Returns a string representation of the iterable objects. This is
44 * used in debugging. The limit parameter is used to control how many
45 * elements of the iterable are used to build the final string. Use
46 * 0 or negative values, to include all.
48 * @param objects an iterable of objects to be turned into a string
49 * @param limit the maximum number of objects from iterable to be used
52 public static <T
> String
iterableToString(Iterable
<T
> objects
, int limit
) {
53 StringBuilder builder
= new StringBuilder()
56 int head
= (limit
<= 0) ? Integer
.MAX_VALUE
: (limit
+ 1) / 2;
57 int tail
= (limit
<= 0) ?
0 : limit
- head
;
58 Iterator
<T
> iter
= objects
.iterator();
59 while (iter
.hasNext() && --head
>= 0) {
60 builder
.append(sep
).append(iter
.next().toString());
63 LinkedList
<T
> tailMembers
= new LinkedList
<T
>();
65 while (iter
.hasNext()) {
66 tailMembers
.add(iter
.next());
68 tailMembers
.removeFirst();
72 builder
.append(", ...");
74 for (T o
: tailMembers
) {
75 builder
.append(sep
).append(o
.toString());
78 return builder
.append("]").toString();
82 * Returns a string which can be used to append an iterable field to a debug
85 public static <T
> String
iterableFieldToString(String fieldName
, Iterable
<T
> objects
) {
86 if (!objects
.iterator().hasNext()) {
89 return String
.format(", %s=%s", fieldName
, Util
.iterableToString(objects
, 0));
93 * Returns a string that allows a field value pair to be added to a debug
96 public static String
fieldToString(String name
, Object value
) {
97 return fieldToString(name
, value
, false);
101 * Returns a string that allows a field value pair to be added to a debug
104 public static String
fieldToString(String name
, Object value
, boolean firstParameter
) {
108 if (firstParameter
) {
109 return String
.format("%s=%s", name
, value
);
111 return String
.format(", %s=%s", name
, value
);