001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019 package org.apache.isis.viewer.restfulobjects.applib.util;
020
021 import java.io.UnsupportedEncodingException;
022 import java.net.URLDecoder;
023 import java.net.URLEncoder;
024 import java.util.Arrays;
025 import java.util.List;
026
027 import com.google.common.base.Charsets;
028 import com.google.common.base.Function;
029 import com.google.common.collect.Lists;
030
031 import org.codehaus.jackson.JsonNode;
032
033 public final class UrlEncodingUtils {
034
035 public final static Function<String, String> FUNCTION = new Function<String, String>() {
036
037 @Override
038 public String apply(final String input) {
039 try {
040 return URLDecoder.decode(input, "UTF-8");
041 } catch (final UnsupportedEncodingException e) {
042 return "";
043 }
044 }
045 };
046
047 private UrlEncodingUtils() {
048 }
049
050 public static String urlDecode(final String string) {
051 return FUNCTION.apply(string);
052 }
053
054 public static List<String> urlDecode(final List<String> values) {
055 return Lists.transform(values, FUNCTION);
056 }
057
058 public static String[] urlDecode(final String[] values) {
059 final List<String> asList = Arrays.asList(values);
060 return urlDecode(asList).toArray(new String[] {});
061 }
062
063 public static String urlEncode(final JsonNode jsonNode) {
064 return UrlEncodingUtils.urlEncode(jsonNode.toString());
065 }
066
067 public static String urlEncode(final String str) {
068 try {
069 return URLEncoder.encode(str, Charsets.UTF_8.name());
070 } catch (final UnsupportedEncodingException e) {
071 // shouldn't happen
072 throw new RuntimeException(e);
073 }
074 }
075
076 }