Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FLINK-10134] UTF-16 support for TextInputFormat bug #7157

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -28,6 +28,7 @@
import org.apache.flink.core.fs.FileStatus;
import org.apache.flink.core.fs.Path;
import org.apache.flink.types.parser.FieldParser;
import org.apache.flink.util.LRUCache;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -36,6 +37,7 @@
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
* Base implementation for input formats that split the input at a delimiter into records.
Expand All @@ -62,6 +64,23 @@ public abstract class DelimitedInputFormat<OT> extends FileInputFormat<OT> imple
// Charset is not serializable
private transient Charset charset;

/**
* The charset of bom in the file to process.
*/
private transient Charset bomIdentifiedCharset;
/**
* This is the charset that is configured via setCharset().
*/
private transient Charset configuredCharset;
/**
* The Map to record the BOM encoding of all files.
*/
private transient final Map<String, Charset> fileBomCharsetMap;
/**
* The bytes to BOM check.
*/
byte[] bomBytes = new byte[]{(byte) 0x00, (byte) 0xFE, (byte) 0xFF, (byte) 0xEF, (byte) 0xBB, (byte) 0xBF};

/**
* The default read buffer size = 1MB.
*/
Expand Down Expand Up @@ -184,6 +203,7 @@ protected DelimitedInputFormat(Path filePath, Configuration configuration) {
configuration = GlobalConfiguration.loadConfiguration();
}
loadConfigParameters(configuration);
this.fileBomCharsetMap = new LRUCache<>(1024);
}

/**
Expand All @@ -195,12 +215,25 @@ protected DelimitedInputFormat(Path filePath, Configuration configuration) {
*/
@PublicEvolving
public Charset getCharset() {
if (this.charset == null) {
if (this.configuredCharset != null) {
this.charset = this.configuredCharset;
} else if (this.bomIdentifiedCharset != null) {
this.charset = this.bomIdentifiedCharset;
} else {
this.charset = Charset.forName(charsetName);
}
return this.charset;
}

/**
* get the charsetName.
*
* @return the charsetName
*/
public String getCharsetName() {
return charsetName;
}

/**
* Set the name of the character set used for the row delimiter. This is
* also used by subclasses to interpret field delimiters, comment strings,
Expand All @@ -214,7 +247,7 @@ public Charset getCharset() {
@PublicEvolving
public void setCharset(String charset) {
this.charsetName = Preconditions.checkNotNull(charset);
this.charset = null;
this.configuredCharset = getSpecialCharset(charset);

if (this.delimiterString != null) {
this.delimiter = delimiterString.getBytes(getCharset());
Expand Down Expand Up @@ -472,6 +505,7 @@ public void open(FileInputSplit split) throws IOException {

this.offset = splitStart;
if (this.splitStart != 0) {
setBomFileCharset(split);
this.stream.seek(offset);
readLine();
// if the first partial record already pushes the stream over
Expand All @@ -481,6 +515,7 @@ public void open(FileInputSplit split) throws IOException {
}
} else {
fillBuffer(0);
setBomFileCharset(split);
}
}

Expand Down Expand Up @@ -536,6 +571,71 @@ public void close() throws IOException {
super.close();
}

/**
* Special default processing for utf-16 and utf-32 is performed.
*
* @param charsetName
* @return
*/
private Charset getSpecialCharset(String charsetName) {
Charset charset;
switch (charsetName.toUpperCase()) {
case "UTF-16":
charset = Charset.forName("UTF-16BE");
break;
case "UTF-32":
charset = Charset.forName("UTF-32BE");
break;
default:
charset = Charset.forName(charsetName);
break;
}
return charset;
}
/**
* Set file bom encoding.
*
* @param split
*/
private void setBomFileCharset(FileInputSplit split) {
try {
if (configuredCharset == null) {
String filePath = split.getPath().toString();
if (this.fileBomCharsetMap.containsKey(filePath)) {
this.bomIdentifiedCharset = this.fileBomCharsetMap.get(filePath);
} else {
byte[] bomBuffer = new byte[4];
if (this.splitStart != 0) {
this.stream.seek(0);
this.stream.read(bomBuffer, 0, bomBuffer.length);
this.stream.seek(split.getStart());
} else {
System.arraycopy(this.readBuffer, 0, bomBuffer, 0, 4);
}
if ((bomBuffer[0] == bomBytes[0]) && (bomBuffer[1] == bomBytes[0]) && (bomBuffer[2] == bomBytes[1])
&& (bomBuffer[3] == bomBytes[2])) {
this.bomIdentifiedCharset = Charset.forName("UTF-32BE");
} else if ((bomBuffer[0] == bomBytes[2]) && (bomBuffer[1] == bomBytes[1]) && (bomBuffer[2] == bomBytes[0])
&& (bomBuffer[3] == bomBytes[0])) {
this.bomIdentifiedCharset = Charset.forName("UTF-32LE");
} else if ((bomBuffer[0] == bomBytes[3]) && (bomBuffer[1] == bomBytes[4]) && (bomBuffer[2] == bomBytes[5])) {
this.bomIdentifiedCharset = Charset.forName("UTF-8");
} else if ((bomBuffer[0] == bomBytes[1]) && (bomBuffer[1] == bomBytes[2])) {
this.bomIdentifiedCharset = Charset.forName("UTF-16BE");
} else if ((bomBuffer[0] == bomBytes[2]) && (bomBuffer[1] == bomBytes[1])) {
this.bomIdentifiedCharset = Charset.forName("UTF-16LE");
} else {
this.bomIdentifiedCharset = Charset.forName(charsetName);
}
this.fileBomCharsetMap.put(filePath, this.bomIdentifiedCharset);
}
}
} catch (Exception e) {
LOG.warn("Failed to get file bom encoding.");
this.bomIdentifiedCharset = Charset.forName(charsetName);
}
}

// --------------------------------------------------------------------------------------------

protected final boolean readLine() throws IOException {
Expand Down
49 changes: 49 additions & 0 deletions flink-core/src/main/java/org/apache/flink/util/LRUCache.java
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.flink.util;

import java.util.LinkedHashMap;
import java.util.Map;

/**
* A LRUCache by LinkedHashMap.
*/
public class LRUCache<K, V> extends LinkedHashMap<K, V> implements java.io.Serializable {

private final int maxCacheSize;

public LRUCache(int cacheSize) {
super((int) Math.ceil(cacheSize / 0.75) + 1, 0.75f, true);
maxCacheSize = cacheSize;
}

@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxCacheSize;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<K, V> entry : entrySet()) {
sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
}
return sb.toString();
}
}
Expand Up @@ -21,6 +21,7 @@
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.io.DelimitedInputFormat;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileInputSplit;
import org.apache.flink.core.fs.Path;

import java.io.IOException;
Expand Down Expand Up @@ -58,16 +59,30 @@ public TextInputFormat(Path filePath) {

// --------------------------------------------------------------------------------------------

public String getCharsetName() {
return charsetName;
}

public void setCharsetName(String charsetName) {
if (charsetName == null) {
throw new IllegalArgumentException("Charset must not be null.");
}

this.charsetName = charsetName;
this.setCharset(charsetName);
}

/**
* Processing for Delimiter special cases.
*/
private void setSpecialDelimiter() {
String delimiterString = "\n";
if (this.getDelimiter() != null && this.getDelimiter().length == 1
&& this.getDelimiter()[0] == (byte) '\n') {
this.setDelimiter(delimiterString);
}
}

@Override
public void open(FileInputSplit split) throws IOException {
super.open(split);
setSpecialDelimiter();
}

// --------------------------------------------------------------------------------------------
Expand All @@ -92,7 +107,7 @@ public String readRecord(String reusable, byte[] bytes, int offset, int numBytes
numBytes -= 1;
}

return new String(bytes, offset, numBytes, this.charsetName);
return new String(bytes, offset, numBytes, this.getCharset());
}

// --------------------------------------------------------------------------------------------
Expand Down