All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cedarsoft.serialization.stax.AbstractDelegatingStaxMateSerializer Maven / Gradle / Ivy

The newest version!
package com.cedarsoft.serialization.stax;

import com.cedarsoft.VersionRange;
import com.cedarsoft.serialization.SerializingStrategySupport;
import org.codehaus.staxmate.out.SMOutputElement;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

/**
 * @param  the type
 * @param  the type of the context
 */
public class AbstractDelegatingStaxMateSerializer extends AbstractStaxMateSerializer {
  @NotNull
  @NonNls
  private static final String ATTRIBUTE_TYPE = "type";

  private final SerializingStrategySupport> serializingStrategySupport;

  public AbstractDelegatingStaxMateSerializer( @NotNull String defaultElementName, @NotNull VersionRange formatVersionRange, @NotNull StaxMateSerializingStrategy... strategies ) {
    this( defaultElementName, formatVersionRange, Arrays.asList( strategies ) );
  }

  public AbstractDelegatingStaxMateSerializer( @NotNull String defaultElementName, @NotNull VersionRange formatVersionRange, @NotNull Collection> strategies ) {
    super( defaultElementName, formatVersionRange );
    serializingStrategySupport = new SerializingStrategySupport>( strategies );
  }

  @Override
  @NotNull
  public SMOutputElement serialize( @NotNull SMOutputElement serializeTo, @NotNull T object, @Nullable C context ) throws IOException {
    try {
      StaxMateSerializingStrategy strategy = serializingStrategySupport.findStrategy( object );
      serializeTo.addAttribute( ATTRIBUTE_TYPE, strategy.getId() );
      strategy.serialize( serializeTo, object, null );

      return serializeTo;
    } catch ( XMLStreamException e ) {
      throw new IOException( e );
    }
  }

  @Override
  @NotNull
  public T deserialize( @NotNull XMLStreamReader deserializeFrom, @Nullable C context ) throws IOException, XMLStreamException {
    String type = deserializeFrom.getAttributeValue( null, ATTRIBUTE_TYPE );

    StaxMateSerializingStrategy strategy = serializingStrategySupport.findStrategy( type );
    return strategy.deserialize( deserializeFrom, null );
  }

  @NotNull
  public Collection> getStrategies() {
    return serializingStrategySupport.getStrategies();
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy