| 1 | /** |
| 2 | * Licensed to jclouds, Inc. (jclouds) under one or more |
| 3 | * contributor license agreements. See the NOTICE file |
| 4 | * distributed with this work for additional information |
| 5 | * regarding copyright ownership. jclouds licenses this file |
| 6 | * to you under the Apache License, Version 2.0 (the |
| 7 | * "License"); you may not use this file except in compliance |
| 8 | * with the License. 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, |
| 13 | * software distributed under the License is distributed on an |
| 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | * KIND, either express or implied. See the License for the |
| 16 | * specific language governing permissions and limitations |
| 17 | * under the License. |
| 18 | */ |
| 19 | package org.jclouds.http.functions; |
| 20 | |
| 21 | import java.util.List; |
| 22 | import java.util.Map; |
| 23 | import java.util.Set; |
| 24 | |
| 25 | import javax.inject.Inject; |
| 26 | import javax.inject.Singleton; |
| 27 | |
| 28 | import org.jclouds.http.HttpResponse; |
| 29 | |
| 30 | import com.google.common.base.Function; |
| 31 | import com.google.common.collect.ImmutableList; |
| 32 | import com.google.common.collect.ImmutableMap; |
| 33 | import com.google.common.collect.ImmutableSet; |
| 34 | import com.google.common.collect.Iterables; |
| 35 | import com.google.inject.TypeLiteral; |
| 36 | |
| 37 | /** |
| 38 | * @author Adrian Cole |
| 39 | */ |
| 40 | @Singleton |
| 41 | public class UnwrapOnlyNestedJsonValue<T> implements Function<HttpResponse, T> { |
| 42 | |
| 43 | private final ParseJson<Map<String, Map<String, T>>> json; |
| 44 | private final TypeLiteral<T> type; |
| 45 | |
| 46 | @Inject |
| 47 | UnwrapOnlyNestedJsonValue(ParseJson<Map<String, Map<String, T>>> json, TypeLiteral<T> type) { |
| 48 | this.json = json; |
| 49 | this.type = type; |
| 50 | } |
| 51 | |
| 52 | @SuppressWarnings("unchecked") |
| 53 | @Override |
| 54 | public T apply(HttpResponse arg0) { |
| 55 | Map<String, Map<String, T>> map = json.apply(arg0); |
| 56 | if (map == null || map.size() == 0) |
| 57 | return null; |
| 58 | Map<String, T> map1 = Iterables.getOnlyElement(map.values()); |
| 59 | if (map1 == null || map1.size() == 0) { |
| 60 | if (type.getRawType().isAssignableFrom(Set.class)) |
| 61 | return (T) ImmutableSet.of(); |
| 62 | else if (type.getRawType().isAssignableFrom(List.class)) |
| 63 | return (T) ImmutableList.of(); |
| 64 | else if (type.getRawType().isAssignableFrom(Map.class)) |
| 65 | return (T) ImmutableMap.of(); |
| 66 | return null; |
| 67 | } |
| 68 | return Iterables.getOnlyElement(map1.values()); |
| 69 | } |
| 70 | } |