Line data Source code
1 : // Copyright (C) 2018 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.cache.serialize; 16 : 17 : import static java.nio.charset.StandardCharsets.UTF_8; 18 : 19 : import com.google.common.annotations.VisibleForTesting; 20 : import java.nio.ByteBuffer; 21 : import java.nio.CharBuffer; 22 : import java.nio.charset.CharacterCodingException; 23 : import java.nio.charset.Charset; 24 : import java.nio.charset.CodingErrorAction; 25 : 26 154 : public enum StringCacheSerializer implements CacheSerializer<String> { 27 154 : INSTANCE; 28 : 29 : @Override 30 : public byte[] serialize(String object) { 31 2 : return serialize(UTF_8, object); 32 : } 33 : 34 : @VisibleForTesting 35 : static byte[] serialize(Charset charset, String s) { 36 2 : if (s.isEmpty()) { 37 1 : return new byte[0]; 38 : } 39 : try { 40 2 : ByteBuffer buf = 41 : charset 42 2 : .newEncoder() 43 2 : .onMalformedInput(CodingErrorAction.REPORT) 44 2 : .onUnmappableCharacter(CodingErrorAction.REPORT) 45 2 : .encode(CharBuffer.wrap(s)); 46 2 : byte[] result = new byte[buf.remaining()]; 47 2 : buf.get(result); 48 2 : return result; 49 1 : } catch (CharacterCodingException e) { 50 1 : throw new IllegalStateException("Failed to serialize string", e); 51 : } 52 : } 53 : 54 : @Override 55 : public String deserialize(byte[] in) { 56 2 : if (in.length == 0) { 57 1 : return ""; 58 : } 59 : try { 60 2 : return UTF_8 61 2 : .newDecoder() 62 2 : .onMalformedInput(CodingErrorAction.REPORT) 63 2 : .onUnmappableCharacter(CodingErrorAction.REPORT) 64 2 : .decode(ByteBuffer.wrap(in)) 65 2 : .toString(); 66 1 : } catch (CharacterCodingException e) { 67 1 : throw new IllegalStateException("Failed to deserialize string", e); 68 : } 69 : } 70 : }