JdkSerializer.java 1.9 KB

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