JdkSerializer.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright 2010-2011 the original author or authors.
  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.yiidata.intergration.web.modules.sys.cache.serde;
  17. import java.io.*;
  18. /**
  19. * Java Serialization Redis serializer.
  20. * Delegates to the default (Java based) serializer input Spring 3.
  21. *
  22. * @author zhaopx
  23. */
  24. public class JdkSerializer implements Serializer<Serializable> {
  25. private static final long serialVersionUID = 1L;
  26. public JdkSerializer() {
  27. }
  28. @Override
  29. public Serializable deserialize(byte[] bytes) {
  30. try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));){
  31. Serializable o = (Serializable)in.readObject();
  32. in.close();
  33. return o;
  34. } catch (Exception ex) {
  35. throw new IllegalArgumentException("Cannot deserialize", ex);
  36. }
  37. }
  38. @Override
  39. public byte[] serialize(Serializable object) {
  40. if (object == null) {
  41. return new byte[0];
  42. }
  43. try {
  44. ByteArrayOutputStream out = new ByteArrayOutputStream();
  45. ObjectOutputStream outputStream = new ObjectOutputStream(out);
  46. outputStream.writeObject(object);
  47. outputStream.flush();
  48. outputStream.close();
  49. return out.toByteArray();
  50. } catch (Exception ex) {
  51. throw new IllegalArgumentException("Cannot serialize", ex);
  52. }
  53. }
  54. }