Merge "Simplify code using Java 8 features"
[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 = (publicId, systemId) -> new InputSource();
30
31     /**
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.
34      */
35     private static final LoadingCache<EXIParameters, NetconfEXICodec> CODECS =
36             CacheBuilder.newBuilder().weakValues().build(new CacheLoader<EXIParameters, NetconfEXICodec>() {
37                 @Override
38                 public NetconfEXICodec load(final EXIParameters key) {
39                     return new NetconfEXICodec(key.getFactory());
40                 }
41             });
42
43     private final SAXFactory exiFactory;
44
45     private NetconfEXICodec(final EXIFactory exiFactory) {
46         this.exiFactory = new SAXFactory(Preconditions.checkNotNull(exiFactory));
47     }
48
49     public static NetconfEXICodec forParameters(final EXIParameters parameters) {
50         return CODECS.getUnchecked(parameters);
51     }
52
53     XMLReader getReader() throws EXIException {
54         final XMLReader reader = exiFactory.createEXIReader();
55         reader.setEntityResolver(ENTITY_RESOLVER);
56         return reader;
57     }
58
59     SAXEncoder getWriter() throws EXIException {
60         final SAXEncoder writer = exiFactory.createEXIWriter();
61         return writer;
62     }
63 }