ExternalSerializer.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. import java.io.Externalizable;
  19. /**
  20. * Java Serialization Redis serializer.
  21. * Delegates to the default (Java based) serializer input Spring 3.
  22. *
  23. * @author ZhenQin
  24. */
  25. public class ExternalSerializer implements Serializer<Externalizable> {
  26. /**
  27. * 序列化表格
  28. */
  29. private static final long serialVersionUID = 1L;
  30. protected final Class<Externalizable> objectClass;
  31. public ExternalSerializer(Class<Externalizable> t) {
  32. this.objectClass = t;
  33. }
  34. @Override
  35. public Externalizable deserialize(byte[] bytes) {
  36. try {
  37. ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
  38. Externalizable object = objectClass.newInstance();
  39. object.readExternal(in);
  40. in.close();
  41. return object;
  42. } catch (Exception ex) {
  43. throw new IllegalArgumentException("Cannot deserialize", ex);
  44. }
  45. }
  46. @Override
  47. public byte[] serialize(Externalizable object) {
  48. if (object == null) {
  49. return new byte[0];
  50. }
  51. try {
  52. ByteArrayOutputStream out = new ByteArrayOutputStream();
  53. ObjectOutputStream outputStream = new ObjectOutputStream(out);
  54. object.writeExternal(outputStream);
  55. outputStream.flush();
  56. outputStream.close();
  57. return out.toByteArray();
  58. } catch (Exception ex) {
  59. throw new IllegalArgumentException("Cannot serialize", ex);
  60. }
  61. }
  62. }