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
9 package org.opendaylight.netconf.nettyutil.handler;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import com.siemens.ct.exi.EXIFactory;
16 import com.siemens.ct.exi.api.sax.SAXEncoder;
17 import com.siemens.ct.exi.api.sax.SAXFactory;
18 import com.siemens.ct.exi.exceptions.EXIException;
19 import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
20 import org.xml.sax.EntityResolver;
21 import org.xml.sax.InputSource;
22 import org.xml.sax.XMLReader;
24 public final class NetconfEXICodec {
26 * OpenEXI does not allow us to directly prevent resolution of external entities. In order
27 * to prevent XXE attacks, we reuse a single no-op entity resolver.
29 private static final EntityResolver ENTITY_RESOLVER = (publicId, systemId) -> new InputSource();
32 * Since we have a limited number of options we can have, instantiating a weak cache
33 * will allow us to reuse instances where possible.
35 private static final LoadingCache<EXIParameters, NetconfEXICodec> CODECS =
36 CacheBuilder.newBuilder().weakValues().build(new CacheLoader<EXIParameters, NetconfEXICodec>() {
38 public NetconfEXICodec load(final EXIParameters key) {
39 return new NetconfEXICodec(key.getFactory());
43 private final SAXFactory exiFactory;
45 private NetconfEXICodec(final EXIFactory exiFactory) {
46 this.exiFactory = new SAXFactory(Preconditions.checkNotNull(exiFactory));
49 public static NetconfEXICodec forParameters(final EXIParameters parameters) {
50 return CODECS.getUnchecked(parameters);
53 XMLReader getReader() throws EXIException {
54 final XMLReader reader = exiFactory.createEXIReader();
55 reader.setEntityResolver(ENTITY_RESOLVER);
59 SAXEncoder getWriter() throws EXIException {
60 final SAXEncoder writer = exiFactory.createEXIWriter();