You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EncodeUtil.java 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * 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, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.util;
  17. import static java.nio.charset.StandardCharsets.UTF_8;
  18. /**
  19. * Utilities related to various encoding schemes.
  20. *
  21. * @author Vaadin Ltd
  22. * @since 7.7.7
  23. */
  24. public final class EncodeUtil {
  25. private EncodeUtil() {
  26. // Static utils only
  27. }
  28. /**
  29. * Encodes the given string to UTF-8 <code>value-chars</code> as defined in
  30. * RFC5987 for use in e.g. the <code>Content-Disposition</code> HTTP header.
  31. *
  32. * @param value
  33. * the string to encode, not <code>null</code>
  34. * @return the encoded string
  35. */
  36. public static String rfc5987Encode(String value) {
  37. StringBuilder builder = new StringBuilder();
  38. for (int i = 0; i < value.length();) {
  39. int cp = value.codePointAt(i);
  40. if (cp < 127 && (Character.isLetterOrDigit(cp) || cp == '.')) {
  41. builder.append((char) cp);
  42. } else {
  43. // Create string from a single code point
  44. String cpAsString = new String(new int[] { cp }, 0, 1);
  45. appendHexBytes(builder, cpAsString.getBytes(UTF_8));
  46. }
  47. // Advance to the next code point
  48. i += Character.charCount(cp);
  49. }
  50. return builder.toString();
  51. }
  52. private static void appendHexBytes(StringBuilder builder, byte[] bytes) {
  53. for (byte byteValue : bytes) {
  54. // mask with 0xFF to compensate for "negative" values
  55. int intValue = byteValue & 0xFF;
  56. String hexCode = Integer.toString(intValue, 16);
  57. builder.append('%').append(hexCode);
  58. }
  59. }
  60. }