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.wooki.test.unit.ConversionsTest.java

@Test(enabled = true)
public void testAptConversion() {
    String result = "   ------\n            Title\n            ------\n            Author\n            ------\n             Date\n\n  Paragraph 1, line 1.\n  Paragraph 1, line 2.\n\n  Paragraph 2, line 1.\n  Paragraph 2, line 2.\n\nSection title\n\n* Sub-section title\n\n** Sub-sub-section title\n\n*** Sub-sub-sub-section title\n\n**** Sub-sub-sub-sub-section title\n\n      * List item 1.\n\n      * List item 2.\n\n        Paragraph contained in list item 2.\n\n            * Sub-list item 1.\n\n            * Sub-list item 2.\n\n      * List item 3.\n        Force end of list:\n\n      []\n\n+------------------------------------------+\nVerbatim text not contained in list item 3\n+------------------------------------------+\n\n      [[1]] Numbered item 1.\n\n                [[A]] Numbered item A.\n\n                [[B]] Numbered item B.\n\n      [[2]] Numbered item 2.\n\n  List numbering schemes: [[1]], [[a]], [[A]], [[i]], [[I]].\n\n      [Defined term 1] of definition list.\n\n      [Defined term 2] of definition list.\n\n+-------------------------------+\nVerbatim text\n                        in a box\n+-------------------------------+\n\n  --- instead of +-- suppresses the box around verbatim text.\n\n[Figure name] Figure caption\n\n*----------*--------------+----------------:\n| Centered | Left-aligned | Right-aligned  |\n| cell 1,1 | cell 1,2     | cell 1,3       |\n*----------*--------------+----------------:\n| cell 2,1 | cell 2,2     | cell 2,3       |\n*----------*--------------+----------------:\nTable caption\n\n  No grid, no caption:\n\n*-----*------*\n cell | cell\n*-----*------*\n cell | cell\n*-----*------*\n\n  Horizontal line:\n\n=======================================================================\n\n^L\n  New page.\n\n  <Italic> font. <<Bold>> font. <<<Monospaced>>> font.\n\n  {Anchor}. Link to {{anchor}}. Link to {{http://www.pixware.fr}}.\n  Link to {{{anchor}showing alternate text}}.\n  Link to {{{http://www.pixware.fr}Pixware home page}}.\n\n  Force line\\\n  break.\n\n  Non\\ breaking\\ space.\n\n  Escaped special characters: \\~, \\=, \\-, \\+, \\*, \\[, \\], \\<, \\>, \\{, \\}, \\\\.\n\n  Copyright symbol: \\251, \\xA9, \\u00a9.\n\n~~Commented out.";
    File aptFile = null;/*w  w  w.  j  a  va  2  s. c o m*/
    String from = "apt";
    File out = null;

    try {
        out = File.createTempFile("fromAptToXHTML", ".html");
        InputStream apt = new ByteArrayInputStream(result.getBytes());
        try {
            aptFile = File.createTempFile("wooki", ".apt");
            FileOutputStream fos = new FileOutputStream(aptFile);
            logger.debug("APT File is " + aptFile.getAbsolutePath());
            byte[] content = null;
            int available = 0;
            while ((available = apt.available()) > 0) {
                content = new byte[available];
                apt.read(content);
                fos.write(content);
            }
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String to = "xhtml";
        Converter converter = new DefaultConverter();
        InputFileWrapper input = InputFileWrapper.valueOf(aptFile.getAbsolutePath(), from, "ISO-8859-1",
                converter.getInputFormats());

        OutputFileWrapper output = OutputFileWrapper.valueOf(out.getAbsolutePath(), to, "UTF-8",
                converter.getOutputFormats());

        converter.convert(input, output);
    } catch (UnsupportedFormatException e) {
        e.printStackTrace();
    } catch (ConverterException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    InputStream newHTML = fromAptToDocbook.performTransformation(new FileSystemResource(out));
    SAXParserFactory factory = SAXParserFactory.newInstance();

    // cration d'un parseur SAX
    SAXParser parser;
    try {
        parser = factory.newSAXParser();
        parser.parse(new InputSource(newHTML), htmlParser);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    } catch (SAXException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getLocalizedMessage());
    }

    Book book = htmlParser.getBook();
    logger.debug("The book title is " + book.getTitle());
}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Reads capabilities from the stream./*w w w . j ava  2  s . co  m*/
 *
 * @param stream input stream with capabilities response
 * @return capabilities
 * @throws ParserConfigurationException if unable to create XML parser
 * @throws SAXException if invalid XML response
 * @throws IOException if unable to read response
 */
private Capabilities readCapabilities(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException {
    Capabilities capabilities = new Capabilities();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    CapabilitiesParse cParse = new CapabilitiesParse(capabilities);
    factory.newSAXParser().parse(new InputSource(stream), cParse);
    return capabilities;
}

From source file:ebay.dts.client.CreateLMSParser.java

/**
 * Create the SAX parser/*  w ww. j a v  a2  s.  c  o m*/
 */
private void create() {
    try {
        // Obtain a new instance of a SAXParserFactory.
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // Specifies that the parser produced by this code will provide support for XML namespaces.
        factory.setNamespaceAware(true);
        // Specifies that the parser produced by this code will validate documents as they are parsed.
        factory.setValidating(true);
        // Creates a new instance of a SAXParser using the currently configured factory parameters.
        saxParser = factory.newSAXParser();
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.bordercloud.sparql.Endpoint.java

private void init(String endpoint, Boolean readOnly, Boolean debug, String proxy_host, //todo
        Integer proxy_port//todo
) {// w  ww . ja  v a2s . c o m
    try {
        URL url = new URL(endpoint);

        if (readOnly) {
            _endpoint = endpoint;
        } else {
            _endpoint = endpoint;
            _endpoint_root = url.getProtocol() + "://" + url.getHost() + url.getFile();
        }
    } catch (MalformedURLException mue) {
        System.out.println("Ouch - a MalformedURLException happened.");
        mue.printStackTrace();
    }

    // Init Sax class
    SAXParserFactory parserSPARQL = SAXParserFactory.newInstance();
    _parser = null;

    try {
        _parser = parserSPARQL.newSAXParser();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    _debug = debug;
    _endpoint_write = "";
    _readOnly = readOnly;

    _proxy_host = proxy_host;
    _proxy_port = proxy_port;

    if (_proxy_host != null && _proxy_port != 0) {
        //todo
    } else {
        //todo
    }

    // init parameter in the standard
    _nameParameterQueryRead = "query";
    _nameParameterQueryWrite = "update";

    //FIX for Wikidata
    if (endpoint == "https://query.wikidata.org/sparql") {
        _MethodHTTPRead = "GET";
    } else {
        _MethodHTTPRead = "POST"; // by default
    }
}

From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java

/**
 * Creates a new AbstractHostKeyVerification object.
 *
 * @param hostFileName//from  w ww  .j av a2  s  .c  om
 *
 * @throws InvalidHostFileException
 */
public AbstractHostKeyVerification(String hostFileName) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (hostFileName != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(hostFileName, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(hostFileName);

            if (f.exists()) {
                in = new FileInputStream(f);
                hostFile = hostFileName;

                SAXParserFactory saxFactory = SAXParserFactory.newInstance();
                SAXParser saxParser = saxFactory.newSAXParser();
                saxParser.parse(in, this);
                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file
                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }
        }
    } catch (AccessControlException ace) {
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        throw new InvalidHostFileException("Could not open or read " + hostFileName);
    } catch (SAXException sax) {
        throw new InvalidHostFileException("Failed XML parsing: " + sax.getMessage());
    } catch (ParserConfigurationException pce) {
        throw new InvalidHostFileException("Failed to initialize xml parser: " + pce.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:kmlvalidator.KmlValidatorServlet.java

/**
 * Handles POST requests for the servlet.
 *//*from w  w w .j a  va2  s  .co m*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Our response is always JSON.
    response.setContentType("application/json");

    // Create the JSON response objects to be filled in later.
    JSONObject responseObj = new JSONObject();
    JSONArray responseErrors = new JSONArray();

    try {
        // Load XSD files here. Note that the Java runtime should be caching
        // these files.
        Object[] schemas = {
                new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection()
                        .getInputStream(),
                new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(),
                new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection()
                        .getInputStream() };

        // Create a SAX parser factory (not a DOM parser, we don't need the
        // overhead) and set it to validate and be namespace aware, for
        // we want to validate against multiple XSDs.
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(true);
        parserFactory.setNamespaceAware(true);

        // Create a SAX parser and prepare for XSD validation.
        SAXParser parser = parserFactory.newSAXParser();
        parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        parser.setProperty(JAXP_SCHEMA_SOURCE, schemas);

        // Create a parser handler to trap errors during parse.
        KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler();

        // Parse the KML and send all errors to our handler.
        parser.parse(request.getInputStream(), parserHandler);

        // Check our handler for validation results.
        if (parserHandler.getErrors().size() > 0) {
            // There were errors, enumerate through them and create JSON objects
            // for each one.
            for (KmlValidationError e : parserHandler.getErrors()) {
                JSONObject error = new JSONObject();

                switch (e.getType()) {
                case KmlValidationError.VALIDATION_WARNING:
                    error.put("type", "warning");
                    break;

                case KmlValidationError.VALIDATION_ERROR:
                    error.put("type", "error");
                    break;

                case KmlValidationError.VALIDATION_FATAL_ERROR:
                    error.put("type", "fatal_error");
                    break;

                default:
                    error.put("type", "fatal_error");
                }

                // fill in parse exception details
                SAXParseException innerException = e.getInnerException();
                error.put("message", innerException.getMessage());

                if (innerException.getLineNumber() >= 0)
                    error.put("line", innerException.getLineNumber());

                if (innerException.getColumnNumber() >= 0)
                    error.put("column", innerException.getColumnNumber());

                // add this error to the list
                responseErrors.add(error);
            }

            // The KML wasn't valid.
            responseObj.put("status", "invalid");
        } else {
            // The KML is valid against the XSDs.
            responseObj.put("status", "valid");
        }
    } catch (SAXException e) {
        // We should never get here due to regular parse errors. This error
        // must've been thrown by the schema factory.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal error: " + e.getMessage());
        responseErrors.add(error);

    } catch (ParserConfigurationException e) {
        // Internal error at this point.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal parse error.");
        responseErrors.add(error);
    }

    // If there were errors, add them to the final response JSON object.
    if (responseErrors.size() > 0) {
        responseObj.put("errors", responseErrors);
    }

    // output the JSON object as the HTTP response and append a newline for
    // prettiness
    response.getWriter().print(responseObj);
    response.getWriter().println();
}

From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java

private void getInfoFromXML() {

    //Show a progress dialog while reading XML
    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);//from  w  w w .  j ava2s . co m

            try {

                //Log.d("EMD - ","About to parse");

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                //Log.d("EMD - ","Done Parsing");

                statuscode = myXMLHandler.statuscode;
                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                genre = myXMLHandler.genre;
                genreId = myXMLHandler.genreId;
                labelId = myXMLHandler.labelId;
                label = myXMLHandler.label;
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                imageURL = myXMLHandler.imageURL;
                artist = myXMLHandler.artist;
                artistId = myXMLHandler.artistId;

                //Log.d("EMD - ","Set genre etc..");

                numberOfTracks = myXMLHandler.nItems;
                trackNames = myXMLHandler.tracks;
                //sampleAddresses = myXMLHandler.sampleAddress;
                //sampleExists = myXMLHandler.sampleExists;
                //vSamplesExist = myXMLHandler.samplesExist;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {
                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_album_info);
                    }
                });

            }

            //Remove Progress Dialog
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            handlerDoneLoading.sendEmptyMessage(0);
        }
    };
    t3.start();
}

From source file:cm.aptoide.pt.ManageRepo.java

private Vector<String> getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    Vector<String> out = new Vector<String>();
    try {/*from w w w.ja  v a 2  s  .com*/
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputStreamReader isr = new FileReader(new File(file));
        InputSource is = new InputSource(isr);
        xr.parse(is);
        File xml_file = new File(file);
        xml_file.delete();
        out = handler.getNewSrvs();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return out;
}

From source file:com.openbravo.pos.admin.RolesViewTree.java

public void getPermissions() throws BasicException {
    try {/*from  ww  w  . ja va  2  s .c  om*/
        String m_roles = m_dlAdmin.getRoleID(m_jName.getText());
        String sRolePermisions = m_dlAdmin.findRolePermissions(m_roles);
        m_apermissions = new HashSet<>();
        if (m_sp == null) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            m_sp = spf.newSAXParser();
        }
        m_sp.parse(new InputSource(new StringReader(sRolePermisions)),
                new RolesViewTree.ConfigurationHandler());
    } catch (ParserConfigurationException | SAXException ex) {
        Logger.getLogger(JRootApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RolesViewTree.class.getName()).log(Level.SEVERE, null, ex);
    }
    ;
}

From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java

/**
 * Completes the two-part operation started by startPut(), by
 * collecting status of the PUT operation and converting the
 * WebDAV URI of the newly-created resource back to a Handle,
 * which it returns./*w w w.  j av a 2 s  .  co  m*/
 * <p>
 * Any failure results in an exception.
 *
 * @return Handle of the newly-created DSpace resource.
 */
public String finishPut() throws InterruptedException, IOException, SAXException, SAXNotRecognizedException,
        ParserConfigurationException {
    if (lastPutThread != null) {
        lastPutThread.join();
        lastPutThread = null;
    }

    Header loc = lastPut.getResponseHeader("Location");
    lastStatus = lastPut.getStatusCode();
    if (lastStatus < 100 || lastStatus >= 400)
        throw new IOException("PUT returned status = " + lastStatus + "; text=" + lastPut.getStatusText());

    lastPut = null;
    if (loc != null) {
        String newURL = loc.getValue();

        // do a quick PROPFIND to get the handle
        PropfindMethod pf = new PropfindMethod(newURL, propfindBody);
        pf.setDoAuthentication(true);
        client.executeMethod(pf);

        int pfStatus = pf.getStatusCode();
        if (pfStatus < 200 || pfStatus >= 300)
            throw new IOException(
                    "finishPut.propfind got status = " + pfStatus + "; text=" + pf.getStatusText());

        // Maybe move all this crap to within Propfind class??
        // so it can get the inputstream directly?
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        PropfindHandler handler = new PropfindHandler();

        // XXX FIXME: should turn off validation here explicitly, but
        //  it seems to be off by default.
        xr.setFeature("http://xml.org/sax/features/namespaces", true);
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(pf.getResponseBodyAsStream()));

        return handler.handle;
    } else
        throw new IOException("PUT response was missing a Location: header.");
}