Example usage for javax.xml.parsers SAXParserFactory newSAXParser

List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newSAXParser.

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:com.travelguide.GuideActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    final String TAG = "Activity2";

    String ln = getIntent().getExtras().getString("tag");
    if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Gracias por usar mi aplicacin.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText("Las ubicaciones de visitantes en el interior "
                + getIntent().getExtras().getString("com.travelguide.radius") + " millas para "
                + getIntent().getExtras().getString("com.travelguide.location"));

    } else {// www.  j  av a2 s  .  c o  m
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Thanks for using my App.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText(
                "Visitor locations found within " + getIntent().getExtras().getString("com.travelguide.radius")
                        + " miles for " + getIntent().getExtras().getString("com.travelguide.location"));

    }

    String url = getIntent().getExtras().getString("com.travelguide.link");
    Log.i(TAG, url);

    try {
        //***** Parsing the xml file*****
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        tgparse myXML_parser = new tgparse();
        xr.setContentHandler(myXML_parser);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url.replace(" ", "%20"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        Log.i(TAG, "responseBody: " + responseBody);
        ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
        xr.parse(new InputSource(is));

        Log.i(TAG, "parse complete");

        TextView placename[];
        TextView placeaddress[];
        TextView placerating[];

        tgxml data;
        data = tgparse.getXMLData();
        placename = new TextView[data.getName().size()];
        placeaddress = new TextView[data.getName().size()];
        placerating = new TextView[data.getName().size()];

        webview = (WebView) findViewById(R.id.myWebView);

        //    webview.setBackgroundColor(0);
        //    webview.setBackgroundResource(R.drawable.openbook);

        String stg1 = new String();
        stg1 = "<html>";
        for (int i = 1; i < (data.getName().size()); i++) {
            Log.i(TAG, " " + i);
            Log.i(TAG, "Name= " + data.getName().get(i));
            Log.i(TAG, "Address= " + data.getAddress().get(i));
            Log.i(TAG, "Rating= " + data.getRating().get(i));

            placename[i] = new TextView(this);
            placename[i].setText("Name= " + data.getName().get(i));

            placeaddress[i] = new TextView(this);
            placeaddress[i].setText("Address= " + data.getAddress().get(i));

            placerating[i] = new TextView(this);
            placerating[i].setText("Rating= " + data.getRating().get(i));

            if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
                stg1 = stg1 + "Nombre: " + data.getName().get(i) + "<br>" + " Direccin: "
                        + data.getAddress().get(i) + "<br>" + " clasificacin= " + data.getRating().get(i)
                        + "<br>" + "<br>";
            } else {
                stg1 = stg1 + "Name: " + data.getName().get(i) + "<br>" + " Address: "
                        + data.getAddress().get(i) + "<br>" + " Rating= " + data.getRating().get(i) + "<br>"
                        + "<br>";
            }

        }
        stg1 = stg1 + "</html>";
        webview.loadDataWithBaseURL(null, stg1, "text/html", "utf-8", "about:blank");

    } catch (Exception e) {
        Log.i(TAG, "Exception caught", e);

    }

}

From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java

@Override
public SAXParser createParser() {
    try {// www . j ava 2 s  .c o  m
        SAXParserFactory parserFactory = createSAXParserFactory();
        SAXParser parser = parserFactory.newSAXParser();
        configureParser(parser);
        return parser;
    } catch (SAXException e) {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_PARSER_CREATION_ERROR, (Object[]) null, e);
    } catch (ParserConfigurationException e) {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_PARSER_CREATION_ERROR, (Object[]) null, e);
    }
}

From source file:com.eventestimator.mvc.ContactCollectionController.java

@RequestMapping(value = "/json.j", method = RequestMethod.GET)
protected ResponseEntity<Object> getContacts(Model model, HttpServletRequest request) throws Exception {

    HttpSession session = request.getSession();
    String userName = (String) session.getAttribute("userName");
    String accessToken = (String) session.getAttribute("accessToken");
    String contactUrl = WS_URL_PREFIX + userName + "/contacts?access_token=" + accessToken;
    Feed contactSource = restTemplate.getForObject(contactUrl, Feed.class);
    List<Entry> contacts = contactSource.getEntries();
    List<Contact> contactObjects = new ArrayList<Contact>(contacts.size());
    for (Entry contact : contacts) {

        Link link = (Link) contact.getOtherLinks().get(0);

        String linkHref = link.getHref();
        String contentXML = restTemplate.getForObject(WS_DOMAIN + linkHref + "?access_token=" + accessToken,
                String.class);
        //            List<Content> contactContents = contactEntry.getBody().getContents();
        //            List<Content> contactContents = contactEntry.getContents();
        ///*from  www  . j a  v a 2 s  .c  om*/
        //            Content contactContent = contactContents.get(0);
        //            String contentXML = contactContent.getValue();

        final SAXParserFactory sax = SAXParserFactory.newInstance();
        sax.setNamespaceAware(false);
        final XMLReader reader;
        try {
            reader = sax.newSAXParser().getXMLReader();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
        InputSource is = new InputSource(new StringReader(contentXML));
        SAXSource source = new SAXSource(reader, is);
        JAXBContext context = JAXBContext.newInstance(ContactEntry.class);
        javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller();
        JAXBElement<ContactEntry> contactEntry = (JAXBElement<ContactEntry>) unmarshaller.unmarshal(source,
                ContactEntry.class);
        Contact contactObject = contactEntry.getValue().getContent().getContact();
        contactObjects.add(contactObject);
    }
    ResponseEntity<Object> response = new ResponseEntity<Object>(contactObjects, HttpStatus.OK);
    return response;

}

From source file:com.google.enterprise.connector.sharepoint.wsclient.mock.XmlClientFactory.java

public XmlClientFactory(String xmlFilePath) {
    XmlHandler handler = new XmlHandler();
    try {/*  w  w  w.ja v  a2  s.co  m*/
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(xmlFilePath, handler);
    } catch (Exception e) {
        handler = null;
        LOGGER.log(Level.WARNING, "Unable to load mock xml.", e);
    }

    if (null != handler) {
        root = handler.getRoot();
    } else {
        root = null;
    }
}

From source file:ValidateXMLInput.java

void validate() throws Exception {
    // Since we're going to use a SAX feature, the transformer must support 
    // input in the form of a SAXSource.
    TransformerFactory tfactory = TransformerFactory.newInstance();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // Standard way of creating an XMLReader in JAXP 1.1.
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setNamespaceAware(true); // Very important!
        // Turn on validation.
        pfactory.setValidating(true);/*from w w  w  . j  a v a  2 s  . com*/
        // Get an XMLReader.
        XMLReader reader = pfactory.newSAXParser().getXMLReader();

        // Instantiate an error handler (see the Handler inner class below) that will report any
        // errors or warnings that occur as the XMLReader is parsing the XML input.
        Handler handler = new Handler();
        reader.setErrorHandler(handler);

        // Standard way of creating a transformer from a URL.
        Transformer t = tfactory.newTransformer(new StreamSource("birds.xsl"));

        // Specify a SAXSource that takes both an XMLReader and a URL.
        SAXSource source = new SAXSource(reader, new InputSource("birds.xml"));

        // Transform to a file.
        try {
            t.transform(source, new StreamResult("birds.out"));
        } catch (TransformerException te) {
            // The TransformerException wraps someting other than a SAXParseException
            // warning or error, either of which should be "caught" by the Handler.
            System.out.println("Not a SAXParseException warning or error: " + te.getMessage());
        }

        System.out.println("=====Done=====");
    } else
        System.out.println("tfactory does not support SAX features!");
}

From source file:com.zergiu.tvman.shows.search.AddShowFlowService.java

/**
 * @return/*  w w  w  .j a va  2 s. c o m*/
 */
private void fillLanguagesTable() {
    log.debug("going to go to TVDB.com to get a list of languages");
    List<TVDBLanguage> languages = new ArrayList<TVDBLanguage>();
    URL url = null;
    try {
        url = new URL("http://www.thetvdb.com/api/CAC7D918A2D6A58F/languages.xml");
        InputStream in = url.openStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        SearchLanguagesHandler handler = new SearchLanguagesHandler(languages);
        parser.parse(in, handler);
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
    tvdbLanguageService.addLanguages(languages);
}

From source file:importer.handler.post.annotate.HTMLConverter.java

/**
 * Turn XML note content for Harpur to HTML
 * @param xml the xml note/*  w  w  w  . ja  v  a  2 s.  c o m*/
 * @param config the JSON config to control the conversion
 * @return a HTML string
 */
String convert(String xml) throws HTMLException {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        HTMLConverter conv = new HTMLConverter(patterns);
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(conv);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(xml.toCharArray());
        InputSource input = new InputSource(car);
        xmlReader.parse(input);
        return conv.body.toString();
    } catch (Exception e) {
        throw new HTMLException(e);
    }
}

From source file:com.itude.mobile.mobbl.core.model.parser.MBXmlDocumentParser.java

private void doParseFragment(byte[] data, MBDocument document, String rootPath, boolean copyRootAttributes) {
    if (data != null) {
        try {/*from  w  w w.ja  v a2 s .c  o  m*/
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            _stack = new Stack<MBElementContainer>();
            _pathStack = new Stack<String>();
            _definition = document.getDefinition();
            _characters = new StringBuilder();
            _copyRootAttributes = copyRootAttributes;
            _ignoredPaths = new HashSet<String>();

            if (rootPath != null) {
                List<String> parts = MBPathUtil.splitPath(rootPath);
                for (String part : parts) {
                    _pathStack.add(NUMBERPATTERN.matcher(part).replaceAll(""));
                }

                _rootElementName = _pathStack.peek();
                _rootElement = (MBElementContainer) document.getValueForPath(rootPath);
            } else {
                _rootElement = document;
                _rootElementName = (_definition.getRootElement() != null) ? _definition.getRootElement()
                        : _definition.getName();
            }

            parser.parse(new ByteArrayInputStream(data), this);
        } catch (Exception e) {
            MBLog.d(MBConstants.APPLICATION_NAME, new String(data));
            MBLog.e(MBConstants.APPLICATION_NAME,
                    "MBXmlDocumentParser.doParseFragment (for the data, see debug log above)", e);
        }
    }
}

From source file:com.myjeeva.poi.ExcelReader.java

/**
 * Parses the content of one sheet using the specified styles and shared-strings tables.
 * /* w  ww  . ja  v a  2s  . c  o  m*/
 * @param styles a {@link StylesTable} object
 * @param sharedStringsTable a {@link ReadOnlySharedStringsTable} object
 * @param sheetInputStream a {@link InputStream} object
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
private void readSheet(StylesTable styles, ReadOnlySharedStringsTable sharedStringsTable,
        InputStream sheetInputStream) throws IOException, ParserConfigurationException, SAXException {

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    XMLReader sheetParser = saxFactory.newSAXParser().getXMLReader();

    ContentHandler handler = new XSSFSheetXMLHandler(styles, sharedStringsTable, sheetContentsHandler, true);

    sheetParser.setContentHandler(handler);
    sheetParser.parse(new InputSource(sheetInputStream));
}

From source file:io.dataapps.chlorine.mask.MaskFactory.java

public MaskFactory(FinderEngine fEngine, InputStream in) {
    engine = fEngine;/*from w  ww . j av  a 2s  . c  om*/
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

            boolean bName = false;
            boolean bClass = false;
            boolean bConfiguration = false;
            boolean bDefault = false;

            String name = "";
            String className = "";
            String configuration = "";
            String defaultStr;

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                if (qName.equalsIgnoreCase("NAME")) {
                    bName = true;
                } else if (qName.equalsIgnoreCase("CLASS")) {
                    bClass = true;
                } else if (qName.equalsIgnoreCase("CONFIGURATION")) {
                    bConfiguration = true;
                } else if (qName.equalsIgnoreCase("DEFAULT")) {
                    bDefault = true;
                }
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {

                if (qName.equalsIgnoreCase("NAME")) {
                    bName = false;
                    name = name.trim();
                } else if (qName.equalsIgnoreCase("CLASS")) {
                    bClass = false;
                    className = className.trim();
                } else if (qName.equalsIgnoreCase("CONFIGURATION")) {
                    bConfiguration = false;
                    configuration = configuration.trim();
                } else if (qName.equalsIgnoreCase("DEFAULT")) {
                    bDefault = false;
                    defaultMasker = defaultStr.trim();
                } else if (qName.equalsIgnoreCase("MASKER")) {

                    if (!name.isEmpty() && !className.isEmpty() && !configuration.isEmpty()) {
                        try {
                            Class<?> klass = Thread.currentThread().getContextClassLoader()
                                    .loadClass(className);
                            Masker masker = (Masker) klass.newInstance();
                            masker.init(engine, configuration);
                            maskers.put(name, masker);
                        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                            LOG.error(e);
                        }
                    } else {
                        if (name.isEmpty()) {
                            LOG.error("The name for a masker cannot be empty");
                        }
                        if (className.isEmpty()) {
                            LOG.error("The class name for a masker cannot be empty");
                        }
                        if (configuration.isEmpty()) {
                            LOG.error("The configuration for a masker cannot be empty");
                        }
                    }
                    name = "";
                    configuration = "";
                    className = "";
                    defaultStr = "";
                }
            }

            public void characters(char ch[], int start, int length) throws SAXException {
                if (bName) {
                    name += new String(ch, start, length);
                } else if (bClass) {
                    className += new String(ch, start, length);
                } else if (bConfiguration) {
                    configuration += new String(ch, start, length);
                } else if (bDefault) {
                    defaultStr += new String(ch, start, length);
                }
            }
        };

        saxParser.parse(in, handler);

    } catch (Exception e) {
        LOG.error(e);
    }
}