001// Licensed under the MIT license. See LICENSE file in the project root for full license information. 002 003package de.bytefish.pgbulkinsert.pgsql.handlers; 004 005import java.io.ByteArrayOutputStream; 006import java.io.DataOutputStream; 007import java.util.Collection; 008 009public class CollectionValueHandler<TElementType, TCollectionType extends Collection<TElementType>> extends BaseValueHandler<TCollectionType> { 010 011 private final int oid; 012 private final IValueHandler<TElementType> valueHandler; 013 014 public CollectionValueHandler(int oid, IValueHandler<TElementType> valueHandler) { 015 this.oid = oid; 016 this.valueHandler = valueHandler; 017 } 018 019 @Override 020 protected void internalHandle(DataOutputStream buffer, TCollectionType value) throws Exception { 021 022 ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); 023 DataOutputStream arrayOutput = new DataOutputStream(byteArrayOutput); 024 025 arrayOutput.writeInt(1); // Dimensions, use 1 for one-dimensional arrays at the moment 026 arrayOutput.writeInt(1); // The Array can contain Null Values 027 arrayOutput.writeInt(oid); // Write the Values using the OID 028 arrayOutput.writeInt(value.size()); // Write the number of elements 029 arrayOutput.writeInt(1); // Ignore Lower Bound. Use PG Default for now 030 031 // Now write the actual Collection elements using the inner handler: 032 for (TElementType element : value) { 033 valueHandler.handle(arrayOutput, element); 034 } 035 036 buffer.writeInt(byteArrayOutput.size()); 037 buffer.write(byteArrayOutput.toByteArray()); 038 } 039 040 @Override 041 public int getLength(TCollectionType value) { 042 throw new UnsupportedOperationException(); 043 } 044}