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.

SnakeYamlTypeAdapter.java 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2014 James Moger.
  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 com.iciql.adapter;
  17. import com.iciql.Iciql.DataTypeAdapter;
  18. import com.iciql.Iciql.Mode;
  19. import org.yaml.snakeyaml.DumperOptions.FlowStyle;
  20. import org.yaml.snakeyaml.Yaml;
  21. import org.yaml.snakeyaml.nodes.Tag;
  22. /**
  23. * Base class for inserting/retrieving a Java Object (de)serialized as YAML using SnakeYaml.
  24. */
  25. public abstract class SnakeYamlTypeAdapter<T> implements DataTypeAdapter<T> {
  26. protected Mode mode;
  27. protected Yaml yaml() {
  28. return new Yaml();
  29. }
  30. @Override
  31. public void setMode(Mode mode) {
  32. this.mode = mode;
  33. }
  34. @Override
  35. public String getDataType() {
  36. return "TEXT";
  37. }
  38. @Override
  39. public abstract Class<T> getJavaType();
  40. @Override
  41. public Object serialize(Object value) {
  42. return yaml().dumpAs(value, Tag.MAP, FlowStyle.BLOCK);
  43. }
  44. @Override
  45. public T deserialize(Object value) {
  46. String yaml = value.toString();
  47. Yaml processor = yaml();
  48. T t = processor.loadAs(yaml, getJavaType());
  49. return t;
  50. }
  51. }