/bson/src/main/org/bson/codecs/CharacterCodec.java

https://github.com/foursquare/mongo-java-driver · Java · 54 lines · 26 code · 8 blank · 20 comment · 2 complexity · fc34ed0bf8ab4a674093df2f41188946 MD5 · raw file

  1. /*
  2. * Copyright 2015 MongoDB, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of 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,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.bson.codecs;
  17. import org.bson.BsonInvalidOperationException;
  18. import org.bson.BsonReader;
  19. import org.bson.BsonWriter;
  20. import static java.lang.String.format;
  21. import static org.bson.assertions.Assertions.notNull;
  22. /**
  23. * Encodes and decodes {@code Character} objects.
  24. *
  25. * @since 3.0
  26. */
  27. public class CharacterCodec implements Codec<Character> {
  28. @Override
  29. public void encode(final BsonWriter writer, final Character value, final EncoderContext encoderContext) {
  30. notNull("value", value);
  31. writer.writeString(value.toString());
  32. }
  33. @Override
  34. public Character decode(final BsonReader reader, final DecoderContext decoderContext) {
  35. String string = reader.readString();
  36. if (string.length() != 1) {
  37. throw new BsonInvalidOperationException(format("Attempting to decode the string '%s' to a character, but its length is not "
  38. + "equal to one", string));
  39. }
  40. return string.charAt(0);
  41. }
  42. @Override
  43. public Class<Character> getEncoderClass() {
  44. return Character.class;
  45. }
  46. }