<commit_before>/*
 * $Id: XStreamSerializer.java,v 1.28 2013-07-16 04:36:42 tlipkis Exp $
 */

/*

Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.util;

import java.io.*;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.*;

import org.lockss.app.LockssApp;
import org.lockss.util.SerializationException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.alias.*;
import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.converters.basic.*;
import com.thoughtworks.xstream.converters.reflection.*;
import com.thoughtworks.xstream.core.*;
import com.thoughtworks.xstream.io.*;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * <p>An implementation of {@link ObjectSerializer} based on
 * {@link <a href="http://xstream.codehaus.org/">XStream</a>}.</p>
 * <p>This implementation of {@link ObjectSerializer} is intended to
 * become the preferred way of serializing objects to XML in the
 * LOCKSS codebase because it is much simpler and much lighter than
 * its legacy counterpart, which was based on Castor.</p>
 * <p>It is generally <em>safe</em> to use the same XStreamSerializer
 * instance for multiple unrelated marshalling and unmarshalling
 * operations.</p>
 * <p>This class supports post-deserialization processing. To take
 * advantage of it, you can either use the traditional Java post-
 * deserialization convention with {@link Serializable}, or you can
 * implement {@link org.lockss.util.LockssSerializable}. In that case,
 * your class has to define a method named <code>postUnmarshal</code>
 * that accepts one parameter of type {@link LockssApp} and returns
 * <code>void</code>. Although the underlying implementation does not
 * enforce it, it is <em>strongly recommended</em> that the post-
 * deserialization method be <code>protected</code> so that it can
 * call on post-deserialization methods in a superclass.</p>
 * @author <NAME>
 */
public class XStreamSerializer extends ObjectSerializer {

  /*
   * IMPLEMENTATION NOTES
   *
   * This class is essentially just a wrapper around the XStream
   * class. Because XStream can marshal/unmarshal nearly arbitrary
   * objects (at least as far as the complexity of the LOCKSS codebase
   * goes), its interface was used as a model for ObjectSerializer,
   * hence the vague uselessness of this class. (ObjectSerializer is
   * necessary to refactor Castor-specific code into Castor-specific
   * implementations of serialization. Before ObjectSerializer existed
   * there was Castor-aware code in several data structures that just
   * had no business knowing about XML mappings.)
   */

  /*
   * begin PRIVATE STATIC INNER CLASS
   * ================================
   */
  /**
   * <p>A replacement for XStream's
   * {@link com.thoughtworks.xstream.converters.basic.DateConverter}
   * which uses 'z' for the time zone instead of 'Z'.</p>
   * <p>The problematic discrepancies between 'z' and 'Z' were the
   * subject of Java Bug Report #709654.</p>
   * @author <NAME>
   * @see com.thoughtworks.xstream.converters.basic.DateConverter
   * @see com.thoughtworks.xstream.converters.basic.ThreadSafeSimpleDateFormat
   */
  private static class LockssDateConverter implements Converter {

    public boolean canConvert(Class type) {
      return type.equals(Date.class);
    }

    public void marshal(Object obj,
                        HierarchicalStreamWriter writer,
                        MarshallingContext context) {
      writer.setValue(formatter.format((Date)obj));
    }

    public Object unmarshal(HierarchicalStreamReader reader,
                            UnmarshallingContext context) {
      String value = reader.getValue();
      try {
        return formatter.parse(value);
      }
      catch (ParseException pe) {
        try {
          // Maybe an old (daemon 1.16 and earlier) serialized form
          return oldFormatter.parse(value);
        }
        catch (ParseException pe2) {
          // Cannot parse date
          throw new ConversionException("Cannot parse date: " + value);
        }
      }
    }

    protected static final ThreadSafeSimpleDateFormat formatter = new ThreadSafeSimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z",
                                                                                                 4,
                                                                                                 20);

    protected static final ThreadSafeSimpleDateFormat oldFormatter = new ThreadSafeSimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z",
                                                                                                    4,
                                                                                                    20);

  }
  /*
   * end PRIVATE STATIC INNER CLASS
   * ==============================
   */

  /*
   * begin PRIVATE STATIC INNER CLASS
   * ================================
   */
  /** HashResult converter - writes & reads "alg:hash" */
  private static class LockssHashResultConverter implements Converter {

    public boolean canConvert(Class type) {
      return type.equals(org.lockss.hasher.HashResult.class);
    }

    public void marshal(Object obj,
                        HierarchicalStreamWriter writer,
                        MarshallingContext context) {
      writer.setValue(((org.lockss.hasher.HashResult)obj).toString());
    }

    public Object unmarshal(HierarchicalStreamReader reader,
                            UnmarshallingContext context) {
      String value = reader.getValue();
      try {
	return org.lockss.hasher.HashResult.make(value);
      } catch (Exception e) {
	throw new ConversionException("Cannot parse HashResult: " + value);
      }
    }
  }
  /*
   * end PRIVATE STATIC INNER CLASS
   * ==============================
   */

  /*
   * begin PRIVATE STATIC INNER CLASS<commit_msg>Disallow serializing HashResult without explicit algorithm.<commit_after>/*
 * $Id: XStreamSerializer.java,v 1.29 2013-07-16 04:59:47 tlipkis Exp $
 */

/*

Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.util;

import java.io.*;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.*;

import org.lockss.app.LockssApp;
import org.lockss.util.SerializationException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.alias.*;
import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.converters.basic.*;
import com.thoughtworks.xstream.converters.reflection.*;
import com.thoughtworks.xstream.core.*;
import com.thoughtworks.xstream.io.*;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * <p>An implementation of {@link ObjectSerializer} based on
 * {@link <a href="http://xstream.codehaus.org/">XStream</a>}.</p>
 * <p>This implementation of {@link ObjectSerializer} is intended to
 * become the preferred way of serializing objects to XML in the
 * LOCKSS codebase because it is much simpler and much lighter than
 * its legacy counterpart, which was based on Castor.</p>
 * <p>It is generally <em>safe</em> to use the same XStreamSerializer
 * instance for multiple unrelated marshalling and unmarshalling
 * operations.</p>
 * <p>This class supports post-deserialization processing. To take
 * advantage of it, you can either use the traditional Java post-
 * deserialization convention with {@link Serializable}, or you can
 * implement {@link org.lockss.util.LockssSerializable}. In that case,
 * your class has to define a method named <code>postUnmarshal</code>
 * that accepts one parameter of type {@link LockssApp} and returns
 * <code>void</code>. Although the underlying implementation does not
 * enforce it, it is <em>strongly recommended</em> that the post-
 * deserialization method be <code>protected</code> so that it can
 * call on post-deserialization methods in a superclass.</p>
 * @author <NAME>
 */
public class XStreamSerializer extends ObjectSerializer {

  /*
   * IMPLEMENTATION NOTES
   *
   * This class is essentially just a wrapper around the XStream
   * class. Because XStream can marshal/unmarshal nearly arbitrary
   * objects (at least as far as the complexity of the LOCKSS codebase
   * goes), its interface was used as a model for ObjectSerializer,
   * hence the vague uselessness of this class. (ObjectSerializer is
   * necessary to refactor Castor-specific code into Castor-specific
   * implementations of serialization. Before ObjectSerializer existed
   * there was Castor-aware code in several data structures that just
   * had no business knowing about XML mappings.)
   */

  /*
   * begin PRIVATE STATIC INNER CLASS
   * ================================
   */
  /**
   * <p>A replacement for XStream's
   * {@link com.thoughtworks.xstream.converters.basic.DateConverter}
   * which uses 'z' for the time zone instead of 'Z'.</p>
   * <p>The problematic discrepancies between 'z' and 'Z' were the
   * subject of Java Bug Report #709654.</p>
   * @author <NAME>
   * @see com.thoughtworks.xstream.converters.basic.DateConverter
   * @see com.thoughtworks.xstream.converters.basic.ThreadSafeSimpleDateFormat
   */
  private static class LockssDateConverter implements Converter {

    public boolean canConvert(Class type) {
      return type.equals(Date.class);
    }

    public void marshal(Object obj,
                        HierarchicalStreamWriter writer,
                        MarshallingContext context) {
      writer.setValue(formatter.format((Date)obj));
    }

    public Object unmarshal(HierarchicalStreamReader reader,
                            UnmarshallingContext context) {
      String value = reader.getValue();
      try {
        return formatter.parse(value);
      }
      catch (ParseException pe) {
        try {
          // Maybe an old (daemon 1.16 and earlier) serialized form
          return oldFormatter.parse(value);
        }
        catch (ParseException pe2) {
          // Cannot parse date
          throw new ConversionException("Cannot parse date: " + value);
        }
      }
    }

    protected static final ThreadSafeSimpleDateFormat formatter = new ThreadSafeSimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z",
                                                                                                 4,
                                                                                                 20);

    protected static final ThreadSafeSimpleDateFormat oldFormatter = new ThreadSafeSimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z",
                                                                                                    4,
                                                                                                    20);

  }
  /*
   * end PRIVATE STATIC INNER CLASS
   * ==============================
   */

  /*
   * begin PRIVATE STATIC INNER CLASS
   * ================================
   */
  /** HashResult converter - writes & reads "alg:hash" */
  private static class LockssHashResultConverter implements Converter {

    public boolean canConvert(Class type) {
      return type.equals(org.lockss.hasher.HashResult.class);
    }

    public void marshal(Object obj,
                        HierarchicalStreamWriter writer,
                        MarshallingContext context) {
      
      org.lockss.hasher.HashResult hr = (org.lockss.hasher.HashResult)obj;
      if (hr.getAlgorithm() == null) {
	throw new ConversionException("Can't serialize HashResult with no algorithm");
      }
      writer.setValue(((org.lockss.hasher.HashResult)obj).toString());
    }

    public Object unmarshal(HierarchicalStreamReader reader,
                            UnmarshallingContext context) {
      String value = reader.getValue();
      try {
	return org.lockss.hasher.HashResult.make(value);
      } catch (Exception e) {
	throw new ConversionException("Cannot parse HashResult: " + value);
      }
    }
  }
  /*
   * end PRIVATE STATIC INNER CLASS
   * ==============================
   */

  /*
   * begin PRIVATE STATIC INNER CLASS
{'fraction_non_alphanumeric': 0.09316897091874958, 'fraction_numerical': 0.005584689777293469, 'mean_word_length': 2.8100674623767516, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5889289', 'n_tokens_mistral': 3854, 'n_tokens_neox': 3648, 'n_words': 1366}