Home | History | Annotate | Download | only in impl
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.layoutlib.bridge.impl;
     18 
     19 
     20 import org.kxml2.io.KXmlParser;
     21 import org.xmlpull.v1.XmlPullParser;
     22 import org.xmlpull.v1.XmlPullParserException;
     23 
     24 import java.io.File;
     25 import java.io.FileInputStream;
     26 import java.io.FileNotFoundException;
     27 import java.io.InputStream;
     28 
     29 /**
     30  * A factory for {@link XmlPullParser}.
     31  *
     32  */
     33 public class ParserFactory {
     34 
     35     private final static String ENCODING = "UTF-8"; //$NON-NLS-1$
     36 
     37     public final static boolean LOG_PARSER = false;
     38 
     39     public static XmlPullParser create(File f)
     40             throws XmlPullParserException, FileNotFoundException {
     41         KXmlParser parser = instantiateParser(f.getName());
     42         parser.setInput(new FileInputStream(f), ENCODING);
     43         return parser;
     44     }
     45 
     46     public static XmlPullParser create(InputStream stream, String name)
     47             throws XmlPullParserException {
     48         KXmlParser parser = instantiateParser(name);
     49         parser.setInput(stream, ENCODING);
     50         return parser;
     51     }
     52 
     53     private static KXmlParser instantiateParser(String name) throws XmlPullParserException {
     54         KXmlParser parser;
     55         if (name != null) {
     56             parser = new CustomParser(name);
     57         } else {
     58             parser = new KXmlParser();
     59         }
     60         parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
     61         return parser;
     62     }
     63 
     64     private static class CustomParser extends KXmlParser {
     65         private final String mName;
     66 
     67         CustomParser(String name) {
     68             super();
     69             mName = name;
     70         }
     71 
     72         @Override
     73         public String toString() {
     74             return mName;
     75         }
     76     }
     77 }
     78