001/*
002 * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
003 *
004 * Project and contact information: http://www.cascading.org/
005 *
006 * This file is part of the Cascading project.
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *     http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020
021package cascading.tuple.hadoop.io;
022
023import java.io.IOException;
024
025import cascading.tuple.hadoop.TupleSerialization;
026import cascading.tuple.io.TupleOutputStream;
027import cascading.tuple.io.TuplePair;
028
029public class TuplePairSerializer extends BaseSerializer<TuplePair>
030  {
031  private final TupleOutputStream.TupleElementWriter[] keyWriters;
032  private final TupleOutputStream.TupleElementWriter[] sortWriters;
033
034  public TuplePairSerializer( TupleSerialization.SerializationElementWriter elementWriter )
035    {
036    super( elementWriter );
037
038    Class[] keyClasses = elementWriter.getTupleSerialization().getKeyTypes();
039    Class[] sortClasses = elementWriter.getTupleSerialization().getSortTypes();
040
041    if( elementWriter.getTupleSerialization().areTypesRequired() )
042      {
043      if( keyClasses == null )
044        throw new IllegalStateException( "types are required to perform serialization, grouping declared fields: " + elementWriter.getTupleSerialization().getKeyFields() );
045
046      if( sortClasses == null )
047        throw new IllegalStateException( "types are required to perform serialization, sorting declared fields: " + elementWriter.getTupleSerialization().getSortFields() );
048      }
049
050    keyWriters = HadoopTupleOutputStream.getWritersFor( elementWriter, keyClasses );
051    sortWriters = HadoopTupleOutputStream.getWritersFor( elementWriter, sortClasses );
052    }
053
054  public void serialize( TuplePair tuple ) throws IOException
055    {
056    if( keyWriters == null )
057      outputStream.writeUnTyped( tuple.getLhs() );
058    else
059      outputStream.writeWith( keyWriters, tuple.getLhs() );
060
061    if( sortWriters == null )
062      outputStream.writeUnTyped( tuple.getRhs() );
063    else
064      outputStream.writeWith( sortWriters, tuple.getRhs() );
065    }
066  }