com.ifengxue.http.codec.CodecFactory Maven / Gradle / Ivy
/*
* Copyright 2019 https://www.ifengxue.com
*
* Licensed 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 com.ifengxue.http.codec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* codec factory
*/
public final class CodecFactory {
private static final Map, Codec> codecCache = new ConcurrentHashMap<>();
private static final List codecs = new ArrayList<>();
static {
registerCodec(new FastjsonJsonCodec());
}
/**
* register new or replace old codec
*/
public static synchronized void registerCodec(Codec codec) {
codecCache.put(codec.getClass(), codec);
codecs.add(codec);
}
/**
* find codec by codec class
*/
@SuppressWarnings("unchecked")
public static T findCodec(Class codecClass) {
Codec codec = codecCache.computeIfAbsent(codecClass, clazz -> {
for (Codec c : codecs) {
if (codecClass.isAssignableFrom(c.getClass())) {
return c;
}
}
return null;
});
return (T) Optional.ofNullable(codec)
.orElseThrow(() -> new NoSuchElementException("codec type " + codecClass.getName() + " can't be found."));
}
}