1 | /** |
2 | * |
3 | * Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com> |
4 | * |
5 | * ==================================================================== |
6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
7 | * you may not use this file except in compliance with the License. |
8 | * You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, software |
13 | * distributed under the License is distributed on an "AS IS" BASIS, |
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 | * See the License for the specific language governing permissions and |
16 | * limitations under the License. |
17 | * ==================================================================== |
18 | */ |
19 | |
20 | package org.jclouds.functions; |
21 | |
22 | import static com.google.common.base.Preconditions.checkArgument; |
23 | import static com.google.common.base.Preconditions.checkNotNull; |
24 | |
25 | import java.lang.reflect.Array; |
26 | |
27 | import javax.inject.Singleton; |
28 | |
29 | import com.google.common.base.Function; |
30 | import com.google.common.base.Joiner; |
31 | import com.google.common.collect.ImmutableList; |
32 | import com.google.common.collect.Iterables; |
33 | import com.google.common.collect.ImmutableList.Builder; |
34 | |
35 | /** |
36 | * |
37 | * @author Adrian Cole |
38 | * |
39 | */ |
40 | @Singleton |
41 | public class JoinOnComma implements Function<Object, String> { |
42 | |
43 | public String apply(Object o) { |
44 | checkNotNull(o, "input cannot be null"); |
45 | if (o.getClass().isArray()) { |
46 | Builder<Object> builder = ImmutableList.builder(); |
47 | for (int i = 0; i < Array.getLength(o); i++) |
48 | builder.add(Array.get(o, i)); |
49 | o = builder.build(); |
50 | } |
51 | checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); |
52 | Iterable<?> toJoin = (Iterable<?>) o; |
53 | checkArgument(Iterables.size(toJoin) > 0, "you must pass an iterable or array with elements"); |
54 | return Joiner.on(',').join(toJoin); |
55 | } |
56 | } |