1 // Copyright 2010 Google Inc. All Rights Reserved.
3 package com
.google
.appengine
.api
.search
;
5 import java
.util
.Iterator
;
6 import java
.util
.LinkedList
;
9 * A utility class that does various checks on search and indexing parameters.
13 * A helper method for testing two objects are equal.
15 * @return whether the two objects a and b are equal
17 static boolean equalObjects(Object a
, Object b
) {
18 return a
== b
|| (a
!= null && a
.equals(b
));
22 * A helper method for overriding null values with a default value.
24 * @param value the value of some field
25 * @param defaultValue the default value for the field
26 * @return value if it is not null, otherwise the defaultValue
28 static <T
> T
defaultIfNull(T value
, T defaultValue
) {
29 return value
== null ? defaultValue
: value
;
33 * Returns a string representation of the iterable objects. This is
34 * used in debugging. The limit parameter is used to control how many
35 * elements of the iterable are used to build the final string. Use
36 * 0 or negative values, to include all.
38 * @param objects an iterable of objects to be turned into a string
39 * @param limit the maximum number of objects from iterable to be used
42 static <T
> String
iterableToString(Iterable
<T
> objects
, int limit
) {
43 StringBuilder builder
= new StringBuilder()
46 int head
= (limit
<= 0) ? Integer
.MAX_VALUE
: (limit
+ 1) / 2;
47 int tail
= (limit
<= 0) ?
0 : limit
- head
;
48 Iterator
<T
> iter
= objects
.iterator();
49 while (iter
.hasNext() && --head
>= 0) {
50 builder
.append(sep
).append(iter
.next());
53 LinkedList
<T
> tailMembers
= new LinkedList
<T
>();
55 while (iter
.hasNext()) {
56 tailMembers
.add(iter
.next());
58 tailMembers
.removeFirst();
62 builder
.append(", ...");
64 for (T o
: tailMembers
) {
65 builder
.append(sep
).append(o
);
68 return builder
.append("]").toString();
72 * Helper for constructing {@link String} representations of Search API objects.
74 static class ToStringHelper
{
75 private final StringBuilder sb
;
76 private boolean first
= true;
77 private boolean done
= false;
79 ToStringHelper(String objectName
) {
80 sb
= new StringBuilder(objectName
+ "(");
83 ToStringHelper
addField(String fieldName
, Object value
) {
85 throw new IllegalStateException();
93 sb
.append(fieldName
).append("=").append(value
);
98 ToStringHelper
addIterableField(String fieldName
, Iterable
<?
> objects
, int max
) {
100 throw new IllegalStateException();
102 Iterator
<?
> iterator
= objects
.iterator();
103 if (iterator
.hasNext()) {
109 sb
.append(fieldName
).append("=").append(Util
.iterableToString(objects
, max
));
114 ToStringHelper
addIterableField(String fieldName
, Iterable
<?
> objects
) {
115 return addIterableField(fieldName
, objects
, 0);
121 return sb
.toString();
125 public String
toString() {
126 return done ? sb
.toString() : sb
+ ")";