public class TextRecordEncoder implements WellKnownRecordPayloadEncoder {
@Override
public byte[] encodePayload(WellKnownRecord wellKnownRecord, NdefMessageEncoder messageEncoder) {
TextRecord textRecord = (TextRecord)wellKnownRecord;
if(!textRecord.hasLocale()) {
throw new NdefEncoderException("Expected locale", wellKnownRecord);
}
if(!textRecord.hasEncoding()) {
throw new NdefEncoderException("Expected encoding", wellKnownRecord);
}
if(!textRecord.hasText()) {
throw new NdefEncoderException("Expected text", wellKnownRecord);
}
Locale locale = textRecord.getLocale();
byte[] languageData = (locale.getLanguage() + (locale.getCountry() == null || locale.getCountry().length() == 0 ? ""
: ("-" + locale.getCountry()))).getBytes();
if (languageData.length > TextRecord.LANGUAGE_CODE_MASK) {
throw new NdefEncoderException("language code length longer than 2^5. this is not supported.", wellKnownRecord);
}
Charset encoding = textRecord.getEncoding();
byte[] textData = getTextAsBytes(textRecord, encoding);
byte[] payload = new byte[1 + languageData.length + textData.length];
byte status = (byte)(languageData.length | (TextRecord.UTF16.equals(encoding) ? 0x80 : 0x00));