/src/main/java/com/googlecode/charts4j/UrlUtil.java

http://charts4j.googlecode.com/ · Java · 77 lines · 29 code · 6 blank · 42 comment · 5 complexity · 799a35e0e0a572b18d67ba7c7bff2aa4 MD5 · raw file

  1. /**
  2. *
  3. * The MIT License
  4. *
  5. * Copyright (c) 2011 the original author or authors.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. package com.googlecode.charts4j;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.List;
  27. import com.googlecode.charts4j.collect.ImmutableList;
  28. import com.googlecode.charts4j.collect.Lists;
  29. /**
  30. * Small URL utility class.
  31. *
  32. * @author Julien Chastang (julien.c.chastang at gmail dot com)
  33. *
  34. */
  35. public final class UrlUtil {
  36. /**
  37. * Cannot be instantiated.
  38. */
  39. private UrlUtil() {
  40. throw new AssertionError();
  41. }
  42. /**
  43. * A method that reformats the URL so that the parameters appear in
  44. * alphabetical order. This is useful for comparing URL strings in unit
  45. * tests, for instance.
  46. *
  47. * @param s
  48. * String to be normalized
  49. * @return Normalized string
  50. */
  51. public static String normalize(final String s) {
  52. if (s == null) {
  53. return "";
  54. }
  55. final ImmutableList<String> stringList = Lists.of(s.split("\\?"));
  56. if (stringList.size() != 2) {
  57. return s;
  58. }
  59. final String args = stringList.get(1);
  60. final List<String> params = Arrays.asList(args.split("&"));
  61. Collections.sort(params);
  62. final StringBuilder sb = new StringBuilder(stringList.get(0) + "?");
  63. int cnt = 0;
  64. for (String p : params) {
  65. sb.append(cnt++ > 0 ? "&" : "").append(p);
  66. }
  67. return sb.toString();
  68. }
  69. }