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 static {
40 format.setTimeZone(TimeZone.getTimeZone("GMT"));
41 }
42
43 /**
44 * Add a value to the builder for a given key
45 *
46 * @param key parameter name
47 * @param value value which can be a String, Boolean, Date or collection of Strings. Other types will be converted
48 * via {@link Object#toString()}
49 * @param doPost if true, add POST field instead of query parameters
50 * @param builder the builder
51 *
52 * @return true if the value was not null and was added to the builder
53 */
54 protected boolean visit(String key, Object value, boolean doPost, ApiPathBuilder builder) {
55 if (null != value) {
56 if (doPost) {
57 if (value instanceof Collection) {
58 builder.field(key, (Collection<String>) value);
59 } else {
60 builder.field(key, stringVal(value));
61 }
62 return true;
63 } else {
64 if (value instanceof Collection) {
65 builder.param(key, (Collection<String>) value);
66 } else {
67 builder.param(key, stringVal(value));
68 }
69 return true;
70 }
71 }
72 return false;
73 }
74
75 private String stringVal(Object value) {
76 return value instanceof String ? (String) value :
77 value instanceof Boolean ? Boolean.toString((Boolean) value) :
78 value instanceof Date ? formatDate((Date) value)
79
80 : value.toString();
81 }
82
83 private String formatDate(Date value) {
84 return format.format(value);
85 }
86 }