Merge "Remove deprecated AsyncWriteTransaction#commit method"
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / NetconfEXICodec.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.nettyutil.handler;
10
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;
23
24 public final class NetconfEXICodec {
25     /**
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.
28      */
29     private static final EntityResolver ENTITY_RESOLVER = new EntityResolver() {
30         @Override
31         public InputSource resolveEntity(final String publicId, final String systemId) {
32             return new InputSource();
33         }
34     };
35
36     /**
37      * Since we have a limited number of options we can have, instantiating a weak cache
38      * will allow us to reuse instances where possible.
39      */
40     private static final LoadingCache<EXIParameters, NetconfEXICodec> CODECS =
41             CacheBuilder.newBuilder().weakValues().build(new CacheLoader<EXIParameters, NetconfEXICodec>() {
42                 @Override
43                 public NetconfEXICodec load(final EXIParameters key) {
44                     return new NetconfEXICodec(key.getFactory());
45                 }
46             });
47
48     private final SAXFactory exiFactory;
49
50     private NetconfEXICodec(final EXIFactory exiFactory) {
51         this.exiFactory = new SAXFactory(Preconditions.checkNotNull(exiFactory));
52     }
53
54     public static NetconfEXICodec forParameters(final EXIParameters parameters) {
55         return CODECS.getUnchecked(parameters);
56     }
57
58     XMLReader getReader() throws EXIException {
59         final XMLReader reader = exiFactory.createEXIReader();
60         reader.setEntityResolver(ENTITY_RESOLVER);
61         return reader;
62     }
63
64     SAXEncoder getWriter() throws EXIException {
65         final SAXEncoder writer = exiFactory.createEXIWriter();
66         return writer;
67     }
68 }