1 /*
2 * Copyright 2012 DTO Labs, Inc. (http://dtolabs.com)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18 /*
19 * QueryParameterBuilder.java
20 *
21 * User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
22 * Created: 9/13/12 4:21 PM
23 *
24 */
25 package org.rundeck.api;
26
27 import java.text.SimpleDateFormat;
28 import java.util.*;
29
30
31 /**
32 * Abstract utility base class for building query parameters from a query object.
33 *
34 * @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
35 */
36 abstract class QueryParameterBuilder implements ApiPathBuilder.BuildsParameters {
37 public static final String W3C_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
38 static final SimpleDateFormat format = new SimpleDateFormat(W3C_DATE_FORMAT);
39
40 /**
41 * Add a value to the builder for a given key
42 *
43 * @param key parameter name
44 * @param value value which can be a String, Boolean, Date or collection of Strings. Other types will be converted
45 * via {@link Object#toString()}
46 * @param doPost if true, add POST field instead of query parameters
47 * @param builder the builder
48 *
49 * @return true if the value was not null and was added to the builder
50 */
51 protected boolean visit(String key, Object value, boolean doPost, ApiPathBuilder builder) {
52 if (null != value) {
53 if (doPost) {
54 if (value instanceof Collection) {
55 builder.field(key, (Collection<String>) value);
56 } else {
57 builder.field(key, stringVal(value));
58 }
59 return true;
60 } else {
61 if (value instanceof Collection) {
62 builder.param(key, (Collection<String>) value);
63 } else {
64 builder.param(key, stringVal(value));
65 }
66 return true;
67 }
68 }
69 return false;
70 }
71
72 private String stringVal(Object value) {
73 return value instanceof String ? (String) value :
74 value instanceof Boolean ? Boolean.toString((Boolean) value) :
75 value instanceof Date ? formatDate((Date) value)
76
77 : value.toString();
78 }
79
80 private String formatDate(Date value) {
81 return format.format(value);
82 }
83 }