2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.nettyutil.handler;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
16 import org.opendaylight.netconf.shaded.exificient.core.EXIFactory;
17 import org.opendaylight.netconf.shaded.exificient.core.exceptions.EXIException;
18 import org.opendaylight.netconf.shaded.exificient.main.api.sax.SAXEncoder;
19 import org.xml.sax.EntityResolver;
20 import org.xml.sax.InputSource;
22 public final class NetconfEXICodec {
24 * OpenEXI does not allow us to directly prevent resolution of external entities. In order
25 * to prevent XXE attacks, we reuse a single no-op entity resolver.
27 private static final EntityResolver ENTITY_RESOLVER = (publicId, systemId) -> new InputSource();
30 * Since we have a limited number of options we can have, instantiating a weak cache
31 * will allow us to reuse instances where possible.
33 private static final LoadingCache<EXIParameters, NetconfEXICodec> CODECS =
34 CacheBuilder.newBuilder().weakValues().build(new CacheLoader<EXIParameters, NetconfEXICodec>() {
36 public NetconfEXICodec load(final EXIParameters key) {
37 return new NetconfEXICodec(key.getFactory());
41 private final ThreadLocalSAXFactory exiFactory;
43 private NetconfEXICodec(final EXIFactory exiFactory) {
44 this.exiFactory = new ThreadLocalSAXFactory(requireNonNull(exiFactory));
47 public static NetconfEXICodec forParameters(final EXIParameters parameters) {
48 return CODECS.getUnchecked(parameters);
51 ThreadLocalSAXDecoder getReader() throws EXIException {
52 final ThreadLocalSAXDecoder reader = exiFactory.createEXIReader();
53 reader.setEntityResolver(ENTITY_RESOLVER);
57 SAXEncoder getWriter() throws EXIException {
58 return exiFactory.createEXIWriter();