PageRenderTime 42ms CodeModel.GetById 2ms app.highlight 35ms RepoModel.GetById 1ms app.codeStats 1ms

/ocr/ocrservice/src/com/googlecode/eyesfree/ocr/intent/XmlLoader.java

http://eyes-free.googlecode.com/
Java | 249 lines | 177 code | 50 blank | 22 comment | 16 complexity | cc185d1ed9ae46c2bc20228a1a636129 MD5 | raw file
  1/*
  2 * Copyright (C) 2011 Google Inc.
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5 * use this file except in compliance with the License. You may obtain a copy of
  6 * 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, WITHOUT
 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13 * License for the specific language governing permissions and limitations under
 14 * the License.
 15 */
 16
 17package com.googlecode.eyesfree.ocr.intent;
 18
 19import android.app.Activity;
 20import android.app.ProgressDialog;
 21import android.os.AsyncTask;
 22import android.util.Log;
 23
 24import com.googlecode.eyesfree.ocr.R;
 25import com.googlecode.eyesfree.ocr.client.Language;
 26import com.googlecode.eyesfree.ocr.intent.LanguagesActivity.LanguageData;
 27
 28import org.w3c.dom.Document;
 29import org.w3c.dom.NamedNodeMap;
 30import org.w3c.dom.Node;
 31import org.w3c.dom.NodeList;
 32import org.xml.sax.InputSource;
 33import org.xml.sax.SAXException;
 34
 35import java.io.ByteArrayOutputStream;
 36import java.io.IOException;
 37import java.io.StringReader;
 38import java.net.HttpURLConnection;
 39import java.net.MalformedURLException;
 40import java.net.URL;
 41import java.util.List;
 42import java.util.TreeSet;
 43
 44import javax.xml.parsers.DocumentBuilder;
 45import javax.xml.parsers.DocumentBuilderFactory;
 46import javax.xml.parsers.ParserConfigurationException;
 47import javax.xml.transform.Transformer;
 48import javax.xml.transform.TransformerException;
 49import javax.xml.transform.TransformerFactory;
 50import javax.xml.transform.dom.DOMSource;
 51import javax.xml.transform.stream.StreamResult;
 52
 53/**
 54 * @author alanv@google.com (Alan Viverette)
 55 */
 56class XmlLoader extends AsyncTask<String, Integer, TreeSet<LanguageData>> {
 57    private static final String TAG = "XmlLoader";
 58
 59    private static final String TYPE_LANGUAGE = "language";
 60
 61    private static final int VERSION = 3;
 62
 63    private final List<Language> mAvailable;
 64
 65    private String mCachedXml;
 66
 67    private ProgressDialog mDialog;
 68
 69    public XmlLoader(Activity activity, List<Language> available) {
 70        mAvailable = available;
 71        mCachedXml = null;
 72
 73        String message = activity.getString(R.string.manage_loading);
 74
 75        mDialog = new ProgressDialog(activity);
 76        mDialog.setMax(100);
 77        mDialog.setProgress(0);
 78        mDialog.setIndeterminate(false);
 79        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
 80        mDialog.setMessage(message);
 81        mDialog.setCancelable(true);
 82        mDialog.setOwnerActivity(activity);
 83    }
 84
 85    public XmlLoader setCachedXml(String cachedXml) {
 86        mCachedXml = cachedXml;
 87
 88        return this;
 89    }
 90
 91    protected String getCachedXml() {
 92        return mCachedXml;
 93    }
 94
 95    @Override
 96    protected void onPreExecute() {
 97        mDialog.show();
 98    }
 99
100    @Override
101    protected void onProgressUpdate(Integer... progress) {
102        mDialog.setProgress(progress[0]);
103    }
104
105    @Override
106    protected void onPostExecute(TreeSet<LanguageData> result) {
107        mDialog.dismiss();
108    }
109
110    @Override
111    protected TreeSet<LanguageData> doInBackground(String... urls) {
112        Document xmldoc = null;
113
114        if (mCachedXml != null) {
115            xmldoc = loadFromCachedXML();
116        } else {
117            xmldoc = loadFromURL(urls[0]);
118        }
119
120        if (xmldoc == null) {
121            return null;
122        }
123
124        Node languages = xmldoc.getFirstChild();
125
126        if (languages == null || !languages.getNodeName().equals("languages")) {
127            Log.e(TAG, "Missing languages node");
128            return null;
129        }
130
131        NamedNodeMap attr = languages.getAttributes();
132        Node node = attr.getNamedItem("version");
133
134        // Check version of remote languages list
135        int version = Integer.parseInt(node.getNodeValue());
136        if (version != VERSION) {
137            Log.e(TAG, "Incorrect version (is " + VERSION + ", should be " + version);
138            return null;
139        }
140
141        // Load the ISO 639-2 name of each language into a set
142        TreeSet<String> available6392 = new TreeSet<String>();
143
144        for (Language lang : mAvailable) {
145            available6392.add(lang.iso_639_2);
146        }
147
148        // Traverse the XML document and create LanguageData objects
149        final TreeSet<LanguageData> displayLanguages = new TreeSet<LanguageData>();
150        final NodeList nodes = languages.getChildNodes();
151        final int count = nodes.getLength();
152
153        for (int i = 0; i < count; i++) {
154            publishProgress(100 * i / count);
155
156            Node language = nodes.item(i);
157
158            if (TYPE_LANGUAGE.equals(language.getNodeName())) {
159                LanguageData data = inflateLanguage(language, available6392);
160
161                // Display the language if it is installed or visible
162                if (data.installed || !data.hidden) {
163                    displayLanguages.add(data);
164                }
165            }
166        }
167
168        return displayLanguages;
169    }
170
171    private Document loadFromCachedXML() {
172        Document xmldoc = null;
173
174        try {
175            InputSource source = new InputSource(new StringReader(mCachedXml));
176            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
177            DocumentBuilder builder = factory.newDocumentBuilder();
178            xmldoc = builder.parse(source);
179
180        } catch (MalformedURLException e) {
181            e.printStackTrace();
182        } catch (IOException e) {
183            e.printStackTrace();
184        } catch (ParserConfigurationException e) {
185            e.printStackTrace();
186        } catch (SAXException e) {
187            e.printStackTrace();
188        }
189
190        mCachedXml = null;
191
192        return xmldoc;
193    }
194
195    private Document loadFromURL(String url) {
196        Document xmldoc = null;
197
198        try {
199            URL xmlUrl = new URL(url);
200            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
201            DocumentBuilder builder = factory.newDocumentBuilder();
202            HttpURLConnection http = (HttpURLConnection) xmlUrl.openConnection();
203            xmldoc = builder.parse(http.getInputStream());
204
205            DOMSource xmlSource = new DOMSource(xmldoc);
206            ByteArrayOutputStream output = new ByteArrayOutputStream();
207            StreamResult outputTarget = new StreamResult(output);
208
209            try {
210                Transformer transformer = TransformerFactory.newInstance().newTransformer();
211                transformer.transform(xmlSource, outputTarget);
212                mCachedXml = output.toString();
213            } catch (TransformerException e) {
214                e.printStackTrace();
215            }
216        } catch (MalformedURLException e) {
217            e.printStackTrace();
218        } catch (IOException e) {
219            e.printStackTrace();
220        } catch (ParserConfigurationException e) {
221            e.printStackTrace();
222        } catch (SAXException e) {
223            e.printStackTrace();
224        }
225
226        return xmldoc;
227    }
228
229    private LanguageData inflateLanguage(Node language, TreeSet<String> available6392) {
230        LanguageData data = new LanguageData();
231        NamedNodeMap attr = language.getAttributes();
232        Node node;
233
234        node = attr.getNamedItem("size");
235        data.size = node.getNodeValue();
236        node = attr.getNamedItem("file");
237        data.file = node.getNodeValue();
238        node = attr.getNamedItem("iso6392");
239        data.iso6392 = node.getNodeValue();
240        node = attr.getNamedItem("name");
241        data.name = node.getNodeValue();
242        node = attr.getNamedItem("hidden");
243        data.hidden = (node != null);
244
245        data.installed = available6392.contains(data.iso6392);
246
247        return data;
248    }
249}