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 de.bytefish.pgbulkinsert.util.StringUtils; 006 007import java.io.ByteArrayOutputStream; 008import java.io.DataOutputStream; 009import java.util.Map; 010 011public class HstoreValueHandler extends BaseValueHandler<Map<String, String>> { 012 013 @Override 014 protected void internalHandle(DataOutputStream buffer, final Map<String, String> value) throws Exception { 015 016 // Write into a Temporary ByteArrayOutputStream: 017 ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); 018 019 // And wrap it in a DataOutputStream: 020 DataOutputStream hstoreOutput = new DataOutputStream(byteArrayOutput); 021 022 // First the Amount of Values to write: 023 hstoreOutput.writeInt(value.size()); 024 025 // Now Iterate over the Array and write each value: 026 for (Map.Entry<String, String> entry : value.entrySet()) { 027 // Write the Key: 028 writeKey(hstoreOutput, entry.getKey()); 029 // The Value can be null, use a different method: 030 writeValue(hstoreOutput, entry.getValue()); 031 } 032 033 // Now write the entire ByteArray to the COPY Buffer: 034 buffer.writeInt(byteArrayOutput.size()); 035 buffer.write(byteArrayOutput.toByteArray()); 036 } 037 038 private void writeKey(DataOutputStream buffer, String key) throws Exception { 039 writeText(buffer, key); 040 } 041 042 private void writeValue(DataOutputStream buffer, String value) throws Exception { 043 if(value == null) { 044 buffer.writeInt(-1); 045 } else { 046 writeText(buffer, value); 047 } 048 } 049 050 private void writeText(DataOutputStream buffer, String text) throws Exception { 051 byte[] textBytes = StringUtils.getUtf8Bytes(text); 052 053 buffer.writeInt(textBytes.length); 054 buffer.write(textBytes); 055 } 056 057 @Override 058 public int getLength(Map<String, String> value) { 059 throw new UnsupportedOperationException(); 060 } 061}