2012-03-06 47 views
0

在Tom White的書「Hadoop:權威指南」中學習Apache Avro時,出現錯誤。創建SpecificDatumWriter時出現NullPointerException <T>

的示例具有3個步驟:

  1. 創建阿夫羅模式文件(Pair.avsc

    { 
        "type":"record", 
        "name":"Pair", 
        "doc":"A pair of strings.", 
        "fields":[ 
         { "name":"left", "type":"string" }, 
         { "name":"right", "type":"string" } 
        ] 
    } 
    
  2. 編譯模式文件來創建使用一個Java類(Pair.java

    $ java -jar $AVRO_HOME/avro-tools-1.6.2.jar compile schema src/main/resources/Pair.avsc src/main/java/

  3. 使用SpecificDatumWriter<Pair>SpecificDatumReader<Pair>來序列化/反序列化數據。

最初的示例方法是testPairSpecific()https://github.com/tomwhite/hadoop-book/blob/master/avro/src/main/java/AvroTest.java

我重寫了與原始代碼幾乎相似的示例代碼(createPairAndSerializeThenDeserialize(),代碼爲https://github.com/philipjkim/avro-examples/blob/master/src/test/java/org/sooo/AvroTest.java)。不同的是:

  1. 我使用的Avro版本是1.6.2,在原來的1.3.2。
  2. 通過的Avro-tools.jar中創建的Pair.java內容不同(原:https://github.com/tomwhite/hadoop-book/blob/master/avro/src/main/java/Pair.java,礦山:https://github.com/philipjkim/avro-examples/blob/master/src/main/java/org/sooo/Pair.java

運行測試後,我得到了一個錯誤:

java.lang.NullPointerException 
at java.lang.String.replace(String.java:2228) 
at org.apache.avro.specific.SpecificData.createSchema(SpecificData.java:195) 
at org.apache.avro.specific.SpecificData.getSchema(SpecificData.java:140) 
at org.apache.avro.specific.SpecificDatumWriter.<init>(SpecificDatumWriter.java:33) 
at org.sooo.AvroTest.createPairAndSerializeThenDeserialize(AvroTest.java:86) 
    ... 

AvroTest.createPairAndSerializeThenDeserialize()是:

@Test 
public void createPairAndSerializeThenDeserialize() throws IOException { 
    // given 
    Pair datum = new Pair(); 
    datum.setLeft(new Utf8("L")); 
    datum.setRight(new Utf8("R")); 

    // serialize 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    DatumWriter<Pair> writer = new SpecificDatumWriter<Pair>(Pair.class); /* Line 86 */ 
    Encoder encoder = EncoderFactory.get().binaryEncoder(out, null); 
    writer.write(datum, encoder); 
    encoder.flush(); 
    out.close(); 

    // deserialize 
    DatumReader<Pair> reader = new SpecificDatumReader<Pair>(Pair.class); 
    Decoder decoder = DecoderFactory.get().binaryDecoder(out.toByteArray(), 
    null); 
    Pair result = reader.read(null, decoder); 

    // then 
    assertThat(result.getLeft().toString(), is("L")); 
    assertThat(result.getRight().toString(), is("R")); 
} 

我想知道這個例子有什麼問題。感謝您的任何意見。

僅供參考,我的示例項目回購是https://github.com/philipjkim/avro-examples

回答

3

Pair.avsc文件缺少一個命名空間字段中輸入自定義的包名:

... 
    "namespace": "org.sooo", 
... 
+0

它完美。謝謝! – philipjkim 2012-03-07 01:02:43

相關問題